Repository navigation
Revive SZ3 compression codec - #108788
Revive SZ3 compression codec#108788
Conversation
This reverts the removal of the SZ3 lossy floating-point compression codec done in #84358 (itself a revert of #83088), and adapts it to the current `master`, finishing the work that the fuzzer crashes (#84345) had left unfinished. `SZ3` is an experimental, error-bounded lossy codec for `Float32`, `Float64`, `Array(Float32)` and `Array(Float64)` columns. It requires `SET allow_experimental_codecs = 1`. Changes needed to revive it on top of `master`: - Method byte: the original `SZ3` used `0x9c`, but that byte is now taken by the `ALP` codec, so `SZ3` is assigned the next free byte `0x9d`. The `SZ3` was never part of a stable release, so no persisted data depends on the old byte. - `doDecompressData` now returns `UInt32` (the base class signature changed) and the codec registration was moved to the shared `registerCompressionCodecs.h`. - Re-integrated the vector-dimension and lossy-offset handling into the refactored `MergeTreeDataPartWriterCompact`/`Wide`/`OnDisk`. - `flake.nix` and the `aspell` dictionary entries are not restored, because both were removed from `master` in the meantime. - `SZ3` is intentionally not re-added to the BuzzHouse codec fuzzer: its codec generator is now type-aware and only emits lossless codecs, and `SZ3` is lossy, which would produce false oracle mismatches. Hardening of `doDecompressData` against corrupted input (the reason for the original revert): - The trusted `uncompressed_size` is now enforced. The previous code ignored it and let SZ3 write `config.num` (taken from the untrusted compressed data) elements into `dest`, which is only `uncompressed_size` bytes long - a heap buffer overflow. The decompressed element count is now validated against `uncompressed_size` before decompression. - The float width is validated and `uncompressed_size` must be a multiple of it. - The serialized `SZ3::Config` is parsed from a zero-padded copy of the data, after validating the dimension count and bit width, to avoid out-of-bounds reads, and `config.size_est()` is checked against the compressed size to prevent the payload-size underflow inside `SZ_decompress`. Closes: #84345 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [fa1b53f] Summary: ✅
AI ReviewSummaryThis PR revives the experimental Findings❌ Blockers
Tests
Final VerdictStatus: Minimum required actions:
|
Style check: replace `std::vector` with `std::array` (compression) and the memory-tracked `PODArray` (decompression scratch buffer). Fixes from the automated review: - `isGenericCompression` now returns `false`. SZ3 only applies to floating point data, so reporting it as generic was wrong and caused it to be selected for structural substreams (such as `Array` sizes) where only generic codecs are allowed. This matches the other specialized float codecs (`ALP`, `Gorilla`, `FPC`). The `system.codecs` reference is updated accordingly. - `getMaxCompressedDataSize` reserved less than SZ3's own worst-case output. `SZ_compress` can fall back to a lossless path whose bound is `4096 + config.size_est() + ZSTD_compressBound(...)`, which can exceed `uncompressed_size` and overflow the destination buffer. The bound is now a conservative upper bound. - The `ABS_AND_REL` and `ABS_OR_REL` error bound modes are documented and accepted at parse time but fell into the `default` branch of the compression switch, so a valid `CREATE TABLE` failed on first insert with a `LOGICAL_ERROR`. They are now handled (both bounds set to the value). - Decompression validated only `config.num`, but SZ3 also drives some algorithms from `config.dims`. The product of the dimensions is now validated against the expected element count (with an overflow check) too. - In compact parts, codecs are shared between streams via `streams_by_codec`, which broke SZ3 because the vector dimension is per-stream state: two `Array(Float*) CODEC(SZ3)` columns with different cardinalities shared one codec and rejected each other. Codecs that need the vector dimension upfront now get a per-stream key so each stream uses its own codec instance, while still being tracked for finalize/cancel. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the review feedback and the failing style check in
|
Updates the `contrib/sz3` submodule from the previous ClickHouse fork
(a snapshot of upstream's `sz3.3_develop`) to upstream SZ3 `v3.3.2`. The
two ClickHouse-specific fork patches ("fix segfault", "fix ub") are
already part of upstream `v3.3.2`, so nothing needed to be ported.
On top of `v3.3.2`, the fork branch `ClickHouse/v3.3.2` adds bounds
checking to the decompression path so that the `sz3_decompress_fuzzer`
can no longer read or write out of bounds on corrupted input (the reason
the codec was reverted in the first place, see issue #84345):
- `MemoryUtil` bounded reads throw instead of `assert` (which is a no-op
in release builds).
- `HuffmanEncoder::load`/`decode` validate the node count, the tree size
and the encoded length against the available buffer.
- `SZ_decompress` validates the header and payload sizes against the
compressed buffer size.
- `Config::load` is bounds-checked against the size of the config blob,
validates the dimension count and bit width, and checks that the
product of the dimensions equals the element count.
The codec wrapper is reworked for the new `v3.3.2` wire format (the
serialized config moved to the end of the stream and `SZ_decompress`
itself checks the magic number and data version). It now lets SZ3
allocate the output buffer so a corrupted element count can not overflow
the destination, and validates the element count against the trusted
uncompressed size before copying. `version.hpp` is regenerated for
`v3.3.2`.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Updated Update / patch porting. The previous submodule was a snapshot of upstream's Decompression hardening (the residual
Codec wrapper reworked for v3.3.2's new wire format (config moved to the end of the stream; Verified locally (debug build): |
- Initialize `compressed_size` in `doCompressData` (clang-tidy `cppcoreguidelines-init-variables`, which fails the `arm_tidy` build). - Restrict the `SZ3` algorithm argument to the documented and tested `ALGO_LORENZO_REG`, `ALGO_INTERP_LORENZO` and `ALGO_INTERP`; the other SZ3 algorithms use different, unhardened decompositions/encoders. A test is added for the rejection. - Do not treat a `Tuple` as a vector dimension in `setVectorDimensionsIfNeeded`. A tuple is serialized as one stream per element, so each element stream is scalar; using the tuple arity as the dimension made the codec read several values from a single-value stream (out of bounds, e.g. for a one-row `Tuple(Float64, Float64)`). - Set the SZ3 vector dimension before serializing the granule in the wide part writer. Previously it was set afterwards, so a large array elements stream that filled the compressed buffer during serialization could be compressed before the dimension was set. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the review feedback and the failing
Two I did not change, with rationale:
|
- `getSZ3ErrorBoundMode` used `SZ3::EB_MAP.at` directly, so an unknown
error-bound-mode string (as produced by the AST fuzzer) threw
`std::out_of_range` ("map::at: key not found"), surfacing as a logical
error. It now validates the documented modes (`ABS`, `REL`, `PSNR`,
`ABS_AND_REL`) and throws `ILLEGAL_CODEC_PARAMETER` otherwise, matching
the algorithm-argument handling. A test is added.
- Mark `03202_sz3_codec` as `no-random-settings, no-random-merge-tree-settings`.
SZ3 is lossy and its output depends on how the data is split into
compressed blocks (part type, block sizes), so the error-magnitude
assertions in the test are only stable with fixed settings (the flaky
check exercised it with random settings).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address two review findings on the SZ3 codec. 1. Different array cardinalities across parts no longer get background merges permanently stuck. `SZ3` uses the array length as the inner dimension to exploit inter-element correlation, and previously `setAndCheckVectorDimension` threw when a single codec instance saw two different lengths. Two separate inserts of `[1, 2]` and `[1, 2, 3]` each produced an internally consistent part, but the first merge combining them reused one codec instance and failed forever. The codec now falls back to flat 1D compression instead of failing, and `doCompressData` guards the inner dimension against blocks that do not contain a whole number of fixed-width vectors (variable-length arrays, or a compression-block boundary that splits an array), which would otherwise drop the trailing elements and make the block undecompressable. Each compressed block stores its own dimensions, so blocks with different dimensions still decompress correctly. 2. `Map` columns are now rejected. A `Map` exposes its keys as a substream, so `Map(Float64, Float64) CODEC(SZ3)` previously passed validation and `SZ3` was applied to the key stream, lossily rounding the keys on disk and breaking lookups, grouping and ordering. Lossy codecs are now rejected on any column type that contains a `Map`, matching the documented set of supported types (Float*/Array(Float*)). The `03202_sz3_codec` test gains a positive cross-part merge round-trip (two inserts + forced merge, for both wide and compact parts) and a negative test for float-key maps. The documentation is updated accordingly.
- Mark `SZ3` as a floating-point time series codec (like `ALP`/`Gorilla`/`FPC`). SZ3 must be applied to raw float data, so codec-stack validation now rejects combinations such as `CODEC(Delta, SZ3)` (which previously created a table that failed on read because `Delta` feeds `SZ3` a non-float-aligned block). `system.codecs` now reports `is_timeseries_codec = 1` for `SZ3`; reference and a negative test added. - Bounds-check the SZ3 lossless (zstd) decompression path (the outer layer of every SZ3 block): `Lossless_zstd::decompress` validated the size header against the buffer, checks the allocation, and checks `ZSTD_isError` instead of passing a zstd error code back as a size. (`contrib/sz3` bumped to the `ClickHouse/v3.3.2` fork commit with this fix.) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…3-codec # Conflicts: # tests/queries/0_stateless/03202_sz3_codec.sql
|
Addressed the two latest review findings and merged with the concurrent work on this branch (
Both verified locally together with the just-merged |
Constant float data compresses to a single Huffman symbol, giving a zero-length code. The encoder's build_code then shifted a 64-bit value by 64 bits, which is undefined behavior and aborts the server under UndefinedBehaviorSanitizer. This caused the stateless asan_ubsan test configs to fail (server crash with collateral ATTEMPT_TO_READ_AFTER_EOF errors across in-flight queries). Bumps the contrib/sz3 fork to include the encoder fix. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The error bound (3rd codec argument) is user-controlled and was passed to SZ3's quantizer without validation. A non-finite (NaN/Inf) or non-positive bound makes the quantizer produce out-of-range indices that are cast to integers, which is undefined behavior - a likely AST-fuzzer crash on the asan_ubsan build, the same class of issue that caused the original revert. Reject such bounds at DDL time with a user-facing error. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…House) The number of quantization indices is read from the compressed data and was trusted. Every decomposition reachable here consumes exactly conf.num indices while walking the data grid, so a smaller count caused an out-of-bounds read of quant_inds during decompression and a larger one drove an untrusted allocation. Read the count with the bounded overload and require it to equal conf.num. Found while integrating SZ3 into ClickHouse: ClickHouse/ClickHouse#108788
On decompression these walked vectors filled from the compressed data using running indices that were not bounded against the vector sizes, so crafted input could read past their ends: - LinearQuantizer::recover_unpred indexed unpred[index++] unbounded, and load resized unpred to an untrusted count before the bounded read could reject it; - RegressionPredictor consumed N+1 coefficients per block without checking the coefficient vector size; - ComposedPredictor read selection[current_index++] and indexed predictors[sid] with an unbounded index and an unchecked predictor id. Found while integrating SZ3 into ClickHouse: ClickHouse/ClickHouse#108788
|
Re the AI review "Request changes" verdict on head The AI correctly traces the code path — a table with I'm keeping the current behavior deliberately, because the suggested alternative is worse and there is no useful third option:
So the loud, typed |
# Conflicts: # tests/queries/0_stateless/01222_system_codecs.reference
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 393/428 (91.82%) · Uncovered code |
| } | ||
| } | ||
|
|
||
| void MergeTreeDataPartWriterOnDisk::setVectorDimensionsIfNeeded(CompressionCodecPtr codec, const IColumn * column) |
There was a problem hiding this comment.
A little bit inefficient, but what else can we do?
Ok to accept.
|
📊 Cloud Performance Report ✅ AI verdict: This is a sync PR; the private and public diffs are identical and add a new opt-in, experimental lossy floating-point compression codec (SZ3) plus its contrib, validation, and fuzzer wiring. Enabling it requires allow_experimental_codecs and explicitly declaring CODEC(SZ3) on a Float column, so no ClickBench table exercises this code path and the server's query-execution hot path is untouched. The ~-20% deltas on Q4 and Q15 therefore cannot be caused by this PR: Q4's improvement is already correctly suppressed as within master's recent variance band, and Q15's flagged improvement is downgraded to not-sure as run-to-run variance. No action needed on either query. 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
|
|
Hi @alexey-milovidov — while reviewing this PR I found the following:
Happy to discuss — close anything that's wrong or already addressed. |
`SZ3::LinearQuantizer::quantize_and_overwrite` cast `fabs(data - pred) * error_bound_reciprocal` straight to `int64_t`. For NaN or infinite input (or a finite value out of int64 range) that cast is undefined behavior, reported by UBSan in stress tests as `LinearQuantizer.hpp:45:49: runtime error: nan is outside the range of representable values of type 'long'`. Such values can never be quantized - the error-bound recheck sends them to the unpredictable (lossless) path anyway - so the fix routes them there before the cast, in the `ClickHouse/SZ3` fork (commit dda0caee243719d1dad10a9f05bc18eeedc2ab6b on `ClickHouse/v3.3.2`). Behavior for in-range values is unchanged. The new test `04603_sz3_codec_non_finite` checks that NaN and infinities round-trip exactly through `SZ3` (they are stored losslessly), both on insert and after a merge, and would trigger the UBSan report without the fix. Seen in: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110430&sha=2f139250fec65930580e67de7ebd07b87392fd16&name_0=PR&name_1=Stress%20test%20%28amd_asan_ubsan%29 On PR: ClickHouse#110430 Caused by: ClickHouse#108788 Co-Authored-By: Claude Fable 5 <[email protected]>
Query forwarding to external databases (ClickHouse#107740) is based on Denis Vidiaev's ClickHouse#79652, the GeoJSON output format (ClickHouse#108065) on Mark Needham's ClickHouse#98124, and SZ3 (ClickHouse#108788) revives Konstantin Vedernikov's ClickHouse#83088. Co-Authored-By: Claude Fable 5 <[email protected]>
…ception-safe Addresses the two remaining decompression-hardening blockers from the AI review on ClickHouse#108788, both reachable from a crafted (untrusted) `SZ3` payload. - `ALGO_INTERP` stores its own dimensions array inside the compressed payload (`InterpolationDecomposition`), separate from the trusted `config.dims`. A block could keep `config.num` equal to the trusted output size while declaring larger interpolation dimensions, so the decompressor would iterate past the end of the output buffer and the decoded quantization vector. The contrib fork now rejects a block whose stored dimensions do not match the trusted configuration. - The generic decompressor owned its internal scratch buffer with a raw `malloc` and freed it only on the success path, so the parsing steps that run on untrusted data (`decomposition.load`, `encoder.load`, the quantization-index count read/check, `encoder.decode`) leaked it on a corrupted block. The fork now owns the buffer with RAII and frees a self-allocated lossless buffer when zstd decompression fails. `contrib/sz3` is bumped to the fork commit with these fixes. Adds two regression tests in `gtest_compressionCodec.cpp` (run under ASan/LSan in CI): one tampers the `ALGO_INTERP` inner dimensions while keeping `config.num` equal to the trusted size and asserts the block is rejected before any out-of-bounds access; the other truncates a valid inner buffer to many lengths so the parser fails at every stage, proving the scratch buffer is freed (no leak, no crash) on each exception path. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Reviving `SZ3` adds `CompressionMethodByte::SZ3 = 0x9d`, which expands the method-byte space accepted by compressed `Native` frames: the `decompress=1` HTTP input path takes the codec from each frame's method byte, so a compliant `Native` decoder must know that `0x9d` exists in order to handle or reject it. The canonical specification `docs/en/interfaces/specs/NativeFormat.md` previously documented only `0x02` (`NONE`), `0x82` (`LZ4`) and `0x90` (`ZSTD`) in the `Method byte values` section, so it was stale with respect to the on-wire byte set this pull request introduces. Document `0x9d`/`SZ3` and its experimental constraint (a table can be created with `CODEC(SZ3)` only when `allow_experimental_codecs` is set, but the method byte is always accepted on decompression so existing data stays readable). While here, also list the other assigned column-codec method bytes so the specification describes the complete method-byte space a decoder can encounter, and note that `0x99` (`DeflateQpl`) and `0x9b` (`ZSTD_QPL`) are reserved for removed codecs. This addresses the AI code review finding on the pull request: ClickHouse#108788 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`MergeTreeDataPartWriterOnDisk::setVectorDimensionsIfNeeded` scans the whole column to feed the array/vector dimension to codecs that need it upfront (only `SZ3` so far). It was invoked from the per-granule write path in both part writers - inside `MergeTreeDataPartWriterWide::writeSingleGranule` and inside the compact writer's `stream_getter` - so for a block with many marks an `SZ3` write did `O(rows * granules)` `column->get` / `Field` materializations before compression even started, in the insert and merge hot path. The dimension is a property of the whole column being written, and `setAndCheckVectorDimension` accumulates it monotonically (it never resets and collapses to `1` on a mismatch), so computing it once per block is equivalent to rescanning it on every granule. Hoist it out of the granule loop: - Wide writer: run the stream enumeration and dimension setup once at the top of `writeColumn`, before the granule loop, and drop it from `writeSingleGranule`. - Compact writer: run it only while writing the first granule. This removes the quadratic work while producing identical compressed data (each compressed block still stores its own dimensions, so data stays readable). Also drop `tab_compact` alongside `tab_wide` in `03202_sz3_codec.sql` so the stateless test does not leak schema state into later tests. This addresses the AI code review findings on the pull request: ClickHouse#108788 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Revive SZ3 compression codec
`SZ3::LinearQuantizer::quantize_and_overwrite` cast `fabs(data - pred) * error_bound_reciprocal` straight to `int64_t`. For NaN or infinite input (or a finite value out of int64 range) that cast is undefined behavior, reported by UBSan in stress tests as `LinearQuantizer.hpp:45:49: runtime error: nan is outside the range of representable values of type 'long'`. Such values can never be quantized - the error-bound recheck sends them to the unpredictable (lossless) path anyway - so the fix routes them there before the cast, in the `ClickHouse/SZ3` fork (commit dda0caee243719d1dad10a9f05bc18eeedc2ab6b on `ClickHouse/v3.3.2`). Behavior for in-range values is unchanged. The new test `04603_sz3_codec_non_finite` checks that NaN and infinities round-trip exactly through `SZ3` (they are stored losslessly), both on insert and after a merge, and would trigger the UBSan report without the fix. Seen in: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110430&sha=2f139250fec65930580e67de7ebd07b87392fd16&name_0=PR&name_1=Stress%20test%20%28amd_asan_ubsan%29 On PR: ClickHouse#110430 Caused by: ClickHouse#108788 Co-Authored-By: Claude Fable 5 <[email protected]>
Closes: #84345
Related: #84358
Related: #83088
Revives the
SZ3lossy floating-point compression codec, which was added in #83088 and then removed in #84358 because of fuzzer crashes (#84345).This brings the codec back, adapts it to the current
master, and fixes the decompression robustness problems that caused the original revert.SZ3is an experimental, error-bounded lossy codec forFloat32,Float64,Array(Float32)andArray(Float64)columns; it requiresSET allow_experimental_codecs = 1.What changed compared to the reverted code:
0x9cto0x9d, because0x9cis now used by theALPcodec.SZ3was never part of a stable release, so no persisted data depends on the old byte.doDecompressDatanow returnsUInt32(the base-class signature changed) and codec registration was moved to the sharedregisterCompressionCodecs.h.flake.nixand theaspelldictionary entries are not restored — both were removed frommasterin the meantime.SZ3is intentionally not re-added to the BuzzHouse codec fuzzer: its codec generator is now type-aware and emits only lossless codecs, whileSZ3is lossy and would cause false oracle mismatches.Decompression hardening (the reason for the original revert):
The trusted
uncompressed_sizeis now enforced. Previously it was ignored, soSZ3would writeconfig.num(taken from the untrusted compressed data) elements into adestbuffer sized foruncompressed_size— a heap buffer overflow. The decompressed element count is validated againstuncompressed_sizebefore decompression.The float width is validated and
uncompressed_sizemust be a multiple of it.The serialized
SZ3::Configis parsed from a zero-padded copy of the data after validating the dimension count and bit width (to avoid out-of-bounds reads), andconfig.size_est()is checked against the compressed size to prevent the payload-size underflow insideSZ_decompress.The lossless (zstd) layer's output allocation is bounded by the trusted size on every decompression path. The
ALGO_LOSSLESSbranch passes the output-buffer capacity (config.numelements); the generic lossy path (ALGO_INTERP/ALGO_LORENZO_REG/ALGO_INTERP_LORENZO) bounds its inner buffer bySZ_compress_size_bound(4096 + config.size_est() + ZSTD_compressBound(config.num * sizeof(T))), which is an upper bound for any legitimately stored block, so a corrupted block can not force an arbitrarymallocduring decompression before the size is validated.The interpolation decompressor (
ALGO_INTERP) stores its own dimensions array inside the compressed payload, separately from the trustedconfig.dims. A crafted block could keepconfig.numequal to the trusted output size while declaring larger interpolation dimensions, making the decompressor iterate past the end of the output buffer and the decoded quantization vector. The contrib fork now rejects a block whose stored dimensions do not match the trusted configuration before using them.The generic decompressor's internal scratch buffer is now exception-safe: it was allocated with a raw
mallocand freed only on the success path, so the parsing steps that run on untrusted data (decomposition.load,encoder.load, the quantization-index count read,encoder.decode) leaked it on a corrupted block. It is now owned with RAII, and the lossless layer frees a buffer it allocated itself when zstd decompression fails (it also now requires zstd to produce exactly the declared number of bytes).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Revive the experimental
SZ3error-bounded lossy compression codec forFloat32/Float64(and arrays of them) columns. It requiresallow_experimental_codecs.Documentation entry for user-facing changes
Version info
26.7.1.888(included in26.7and later)