Skip to content

Size GDeflate pages by a bound that holds for every input - #127910

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/gdeflate-page-bound
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/gdeflate-page-bound

Conversation

@groeneai

@groeneai groeneai commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Description

Related: #127422 (the codec; master only, absent on 26.10, hence Not for changelog).

The GDeflate codec could reject a valid INSERT with Cannot compress a chunk of 65536 bytes with GDeflate. (CANNOT_COMPRESS) (seen on 05443_gdeflate_codec with index_granularity = 49963), and for other pages libdeflate wrote past the buffer the codec reserved.

Root cause: each 64 KiB page was sized by libdeflate_gdeflate_compress_bound (65708 bytes). That bound omits the two 32-bit packets each of the 32 GDeflate streams can reserve beyond its bits (the library's #ifdef GDEFLATE term for it is compiled out; NVIDIA/libdeflate#1, fix NVIDIA/libdeflate#3 unmerged), and the GDeflate writer does not check its packet writes against the buffer. A page whose output ends exactly at the writer's end is refused; one that passes it is written out of bounds (the new gtest measured 65769 bytes against a reserve of 65725).

Change: each page gets the library bound plus 256 bytes, through libdeflate_gdeflate_compress_ex, which honours the buffer size (libdeflate_gdeflate_compress uses the library's own bound whatever the buffer). The bytes written are unchanged (the column files of the 05443 tables are byte-identical before and after), so existing parts stay readable; the reserve grows by 256 bytes per chunk.

Validation: a new block in 05443_gdeflate_codec fails 20/20 on the unfixed server under random settings and passes 50/50 with the fix. The new gtest GDeflateCodec.CompressedChunkFitsReserve compresses into exactly getCompressedReserveSize bytes: before the fix ASan reports heap-buffer-overflow in deflate_add_bits (debug: the size exceeds the reserve); after it passes on debug and ASan.


Workflow [PR]
Sync PR [sync-upstream/pr/127910]

`CompressionCodecGDeflate` gave libdeflate a page buffer of
`libdeflate_gdeflate_compress_bound(65536)` = 65708 bytes and called
`libdeflate_gdeflate_compress`, which hands the writer the library's own
bound whatever the buffer size. That bound is too small for GDeflate: the
bit stream is split over 32 interleaved streams of 32-bit packets, and each
stream can reserve up to two packets beyond its bits (`deflate_init_output`
reserves one per stream up front, `deflate_add_bits` reserves the next one
as soon as the emulated decoder has fewer than 32 bits left), i.e. up to
256 bytes beyond the deflate bit count. The library accounts for this in an
`#ifdef GDEFLATE` term of `libdeflate_deflate_compress_bound`, but that
function is compiled only in the plain-deflate translation unit, where
`GDEFLATE` is not defined (NVIDIA/libdeflate#1, fix NVIDIA/libdeflate#3 not
merged). The GDeflate writer has no bounds checks, so:

- a page whose output ends exactly at the writer's end (65700) is reported
  as an overflow: a valid INSERT fails with `Cannot compress a chunk of
  65536 bytes with GDeflate (CANNOT_COMPRESS)`, seen on
  `05443_gdeflate_codec` with `index_granularity = 49963`;
- a page whose output passes it is written past the buffer and returned
  (up to 65748 bytes measured, against a reserve of 65716).

Each page now gets the library bound + 2 * 32 * 4 = 65964 bytes, through
`libdeflate_gdeflate_compress_ex`, which hands `nbytes` to the writer.
Why that holds: the output is 4 bytes per packet allocated; per stream,
`input_bitcount + bitcount = 32 * live packets`, and a reservation happens
only when `input_bitcount < 32`, so a stream holding B_s bits allocates at
most B_s/32 + 2 packets and a page is at most B/8 + 256 bytes, where B/8 is
bounded by the plain-deflate bound 65580. The capacity is 65580 + 128 + 256
= 65964, the writer's end 65956 >= 65836. Measured on 80048 page shapes x
levels 1..12 with exact-size ASan allocations: 0 refusals, 0 overruns,
largest page 65748.

The bytes written do not change (the column files of the 05443 tables are
byte-identical before and after), so existing parts stay readable and no
format change is needed. The reserve grows by 256 bytes per 64 KiB chunk.

Tests: a page in `05443_gdeflate_codec` that compressed to exactly the old
end (failed 20/20 under random settings before, passes 50/50 after), and
`GDeflateCodec.CompressedChunkFitsReserve`, which compresses into exactly
`getCompressedReserveSize` bytes (ASan reported heap-buffer-overflow in
`deflate_add_bits` before).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (2 nits, both on the PR description).

# Sev Finding Verdict Evidence / action
1 💡 The description compared a page size with the block reserve and quoted a smaller overrun than the new gtest measures AGREE, fixed before publication The description now quotes the gtest: 65769 bytes against a reserve of 65725
2 💡 "The GDeflate writer has no bounds checks" overstated: stored blocks are fit-checked (deflate_compress.c:2113) AGREE, fixed before publication Reworded: the writer does not check its packet writes (deflate_add_bits) against the buffer

Not taken: patching the library in a fork. contrib/gdeflate points at NVIDIA/libdeflate directly, the codec is its only caller and owns the page buffer, and a later bump to a fixed library (NVIDIA/libdeflate#3) only adds margin to this bound.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-10:20261027-022500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A 64 KiB UInt8 page if(number < 117, number % 7, cityHash64(number) % 256) with min_compress_block_size = max_compress_block_size = 65536 gives CANNOT_COMPRESS on every unfixed run (clickhouse local); so does 05443_gdeflate_codec with index_granularity = 49963.
b Root cause explained? Each page was sized by libdeflate_gdeflate_compress_bound (65708 bytes), which omits the up to two 32-bit packets each of the 32 GDeflate streams can reserve beyond its bits (its #ifdef GDEFLATE term is compiled out, NVIDIA/libdeflate#1). The writer does not check its packet writes against the buffer: output ending exactly at its end is refused, output past it is written out of bounds.
c Fix matches root cause? Yes. The page capacity is now a real upper bound (library bound + 256), passed through libdeflate_gdeflate_compress_ex, which honours it. No retry or fallback.
d Test intent preserved / new tests added? Yes. Additions-only block in 05443_gdeflate_codec; new gtest GDeflateCodec.CompressedChunkFitsReserve compressing into exactly the reserved size.
e Both directions demonstrated? Yes. SQL block: 20/20 fail unfixed, 50/50 pass fixed, both under random settings and random MergeTree settings. gtest: unfixed ASan heap-buffer-overflow in deflate_add_bits (debug: size over the reserve), fixed passes on debug and ASan.
f Fix is general across code paths? Yes. Chunk::compress is the codec's only compressor call, and maxPageBytes() feeds both the page capacity and the reserve. Decompression never uses the bound. No other codec uses this library.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. gtest covers levels 1, 6, 12 x 256 page shapes; a standalone sweep of 80048 page shapes (including short last chunks) x levels 1..12 with exact-size ASan buffers gave 0 refusals and 0 overruns. All column kinds of 05443 still pass.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change. Written bytes are identical before and after, and parts written by either binary read back with the other.
i Invariants and contracts preserved? Yes. A compressed chunk never exceeds Chunk::maxCompressedBytes() and libdeflate writes only inside the page buffer, so doCompressData stays within getMaxCompressedDataSize. The error path and the zeroed alignment tail are unchanged.

Session id: cron:clickhouse-impl-slot-6:20261027-011300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @rienath, could you review this and add the can be tested label so CI runs? libdeflate_gdeflate_compress_bound omits the two 32-bit packets each of the 32 GDeflate streams can reserve, so a page ending at that bound was refused with CANNOT_COMPRESS and one past it was written out of bounds; each page now gets the bound plus 256 bytes through libdeflate_gdeflate_compress_ex, which honours the buffer size.

@clickhouse-gh

clickhouse-gh Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [544fcdb]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes the CompressionCodecGDeflate reserve-size contract for 64 KiB pages by carrying the missing per-stream packet margin into maxPageBytes and by switching the actual compression call to libdeflate_gdeflate_compress_ex, which honors the caller-provided page capacity. The changed invariant is wired through both reservation and execution, and the added stateless plus gtest coverage exercises the previously failing full-page case, so I did not find any unresolved correctness, compatibility, or safety issues in the current diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... labels Oct 27, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 544fcdb

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 282 of 286 runs since 2026-10-26 22:00 UTC are red, on 236 PRs #126200 (mine, open)
PR praktika rollup of the row above #126200 (the owner of the row above)

The first run of this head stopped at Config Workflow / Pre Hooks because the can be tested label was not set yet; the run after the label was added is the one above. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261027-203012

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: the codec was reverted in #128947.

@groeneai groeneai closed this Nov 3, 2026
scanhex12 added a commit that referenced this pull request Nov 3, 2026
… and writes

`contrib/gdeflate` now points at the branch `gdeflate` of `ClickHouse/libdeflate`, with
ClickHouse/libdeflate#9 on top of `NVIDIA/libdeflate@8ba9502`:

- The decoder refilled a stream with 4 bytes without comparing its position with the end of the
  page, so a page shorter than 128 bytes or a corrupt one was read past its end
  (`multiple_decompress_fuzzer`, heap-buffer-overflow in `deflate_decompress_default`).
- `libdeflate_gdeflate_compress_bound` left out the two packets each of the 32 streams may hold at
  its end, and the encoder did not check its packet writes against the buffer: a valid `INSERT`
  failed with `CANNOT_COMPRESS` (`05443_gdeflate_codec` with a random `index_granularity`), and a
  page past the bound was written out of bounds.

The bytes of every page that compressed before are unchanged. The library is no longer built with
`deflate_compress.c` on its own: it was there only for `libdeflate_deflate_compress_bound`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=b08434c5500c10180f0c43fedb0f5e860b20f46f&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29

Related: #128625
Related: #127910
Related: #128947
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants