Skip to content

Revive SZ3 compression codec - #108788

Merged
alexey-milovidov merged 31 commits into
masterfrom
revive-sz3-codec
Jul 14, 2026
Merged

alexey-milovidov merged 31 commits into
masterfrom
revive-sz3-codec

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Closes: #84345
Related: #84358
Related: #83088

Revives the SZ3 lossy 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.

SZ3 is an experimental, error-bounded lossy codec for Float32, Float64, Array(Float32) and Array(Float64) columns; it requires SET allow_experimental_codecs = 1.

What changed compared to the reverted code:

  • The compression method byte moved from 0x9c to 0x9d, because 0x9c is now used by the ALP codec. 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 codec registration was moved to the shared registerCompressionCodecs.h.
  • The vector-dimension and lossy-offset handling was re-integrated into the refactored compact/wide/on-disk part writers.
  • flake.nix and the aspell dictionary entries are not restored — 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 emits only lossless codecs, while SZ3 is lossy and would cause false oracle mismatches.

Decompression hardening (the reason for the original revert):

  • The trusted uncompressed_size is now enforced. Previously it was ignored, so SZ3 would write config.num (taken from the untrusted compressed data) elements into a dest buffer sized for uncompressed_size — a heap buffer overflow. The decompressed element count is 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.

  • The lossless (zstd) layer's output allocation is bounded by the trusted size on every decompression path. The ALGO_LOSSLESS branch passes the output-buffer capacity (config.num elements); the generic lossy path (ALGO_INTERP/ALGO_LORENZO_REG/ALGO_INTERP_LORENZO) bounds its inner buffer by SZ_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 arbitrary malloc during decompression before the size is validated.

  • The interpolation decompressor (ALGO_INTERP) stores its own dimensions array inside the compressed payload, separately from the trusted config.dims. A crafted block could keep config.num equal 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 malloc and 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):

  • Experimental Feature

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

Revive the experimental SZ3 error-bounded lossy compression codec for Float32/Float64 (and arrays of them) columns. It requires allow_experimental_codecs.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

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

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

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fa1b53f]

Summary: ✅


AI Review

Summary

This PR revives the experimental SZ3 codec, updates the vendored library, hardens decompression, wires the codec through MergeTree writers, and adds broad stateless / gtest coverage. Most of the earlier memory-safety and writer-state issues are addressed, but the new null-type lossy-codec guard still mishandles part default codecs, so I would not approve this head yet.

Findings

❌ Blockers

  • [src/Compression/CompressionFactory.cpp:101] default_compression_codec is not actually an opaque untyped consumer: MergeTreeData::getCompressionCodecForPart carries a descriptor, and IMergeTreeDataPartWriter::getCodecDescOrDefault plus MergeTreeDataPartWriter{Wide,Compact}::addStreams rebind that AST against each concrete substream type. This new !column_type && isLossyCompression() guard therefore rejects valid all-float tables at DDL/runtime. On ATTACH it is worse: IMergeTreeDataPart::loadDefaultCompressionCodec falls back to detectDefaultCompressionCodec(), which only reconstructs the family byte, so a stored CODEC(SZ3('ALGO_INTERP', 'ABS', 0.001)) is downgraded to plain SZ3 before mutations reuse source_part->default_codec.
    Suggested fix: keep the null-type rejection for truly untyped byte streams like marks / primary-key files, but preserve and validate part default codec ASTs against the actual inheriting columns instead of instantiating them via get(..., nullptr).

  • [dismissed by author -- https://github.com/Revive SZ3 compression codec #108788#discussion_r3537730850] TTL ... RECOMPRESS CODEC(SZ3) is still being treated as if it compressed an opaque whole-part blob. The current writer path does not work that way: getCodecDescOrDefault applies the selected TTL codec as the part's default AST and then rebinds it per column, so all-float tables are a valid surface. The current load-then-BAD_ARGUMENTS behavior is therefore an avoidable regression, not the only safe outcome.
    Suggested fix: validate the TTL codec against the columns that would inherit it and preserve the AST on attach instead of forcing the null-type lossy path.

Tests
  • ⚠️ Add a focused regression for default_compression_codec = 'SZ3(...)' on an all-float table, including DETACH / ATTACH and a mutation or merge rewrite, so the stored descriptor and its parameters survive metadata load.
  • ⚠️ If TTL ... RECOMPRESS CODEC(SZ3(...)) remains supported on all-float tables, add a case that actually forces the recompression rewrite instead of only testing metadata load.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Fix the part-default codec path so SZ3 descriptors are preserved without null-type instantiation, including default_compression_codec.txt load on ATTACH.
  2. Make default_compression_codec and TTL ... RECOMPRESS CODEC(SZ3) validate against the actual inheriting columns instead of failing generically on column_type == nullptr.

@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature submodule changed At least one submodule changed in this PR. labels Jun 29, 2026
Comment thread src/Compression/CompressionCodecSZ3.cpp Resolved
Comment thread src/Compression/CompressionCodecSZ3.cpp Resolved
Comment thread src/Compression/CompressionCodecSZ3.cpp Resolved
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the review feedback and the failing style check in feed8023983 (built locally and verified with round-trips for the new cases):

  • Style check — replaced std::vector with std::array (compression dims) and the memory-tracked PODArray (decompression scratch buffer).
  • getMaxCompressedDataSize too small — now reserves a conservative upper bound matching SZ3's SZ_compress_size_bound (4096 + size_est + ZSTD_compressBound(...)), so the lossless-fallback path can't overflow the destination.
  • config.num-only validation — decompression now also validates the product of config.dims against the expected element count (with an overflow check), since some SZ3 algorithms drive output sizing from the dimensions.
  • Shared codec in compact parts — codecs that need the vector dimension upfront (SZ3) now get a per-stream key in streams_by_codec, so two Array(Float*) CODEC(SZ3) columns with different cardinalities no longer share one codec and reject each other. Verified: two such columns with lengths 2 and 3 now round-trip in a compact part.
  • ABS_AND_REL / ABS_OR_REL modes — these are documented/accepted at parse but previously hit the default branch and failed on first insert with LOGICAL_ERROR; they are now handled. Verified an ABS_AND_REL round-trip.
  • Also fixed a related root cause: isGenericCompression() now returns false (matching ALP/Gorilla/FPC). SZ3 is float-only, so reporting it as generic let it be selected for structural substreams such as Array sizes; with this fix those streams correctly use a lossless codec. The system.codecs reference is updated.

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

Copy link
Copy Markdown
Member Author

Updated contrib/sz3 to upstream SZ3 v3.3.2 and hardened the decompression path against corrupted input (ac1ed0629da).

Update / patch porting. The previous submodule was a snapshot of upstream's sz3.3_develop branch with two ClickHouse-specific fixes ("fix segfault" in Sample.hpp, "fix ub" in LinearQuantizer.hpp). Both are already present in upstream v3.3.2, so there was nothing left to port — the submodule now tracks the ClickHouse/v3.3.2 branch of ClickHouse/SZ3 (v3.3.2 + the bounds-checking patch below).

Decompression hardening (the residual sz3_decompress_fuzzer risk; upstream SZ3 does not bounds-check decompression):

  • MemoryUtil bounded reads throw instead of assert (a no-op in release).
  • HuffmanEncoder::load/decode bound the node count, tree size and encoded length against the buffer (and guard against malformed trees).
  • SZ_decompress validates the 16-byte header and the payload size against the compressed size.
  • Config::load is bounded against the config-blob size, validates the dimension count/bit width, and checks that the product of the dimensions equals the element count.

Codec wrapper reworked for v3.3.2's new wire format (config moved to the end of the stream; SZ_decompress itself checks the magic number and data version). It lets SZ3 allocate the output buffer so a corrupted element count can't overflow the destination, then validates the count against the trusted uncompressed size. version.hpp regenerated for v3.3.2.

Verified locally (debug build): 03202_sz3_codec and 01222_system_codecs both pass, and the 03202 reference is unchanged (v3.3.2 produces the same lossy output for the test data). The fuzzer hardening will be exercised by CI's NightlyFuzzers.

Comment thread src/Compression/CompressionCodecSZ3.cpp Resolved
Comment thread src/Compression/CompressionCodecSZ3.cpp Resolved
Comment thread src/Compression/CompressionInfo.h Resolved
- 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the review feedback and the failing arm_tidy build in 6dc9d684676 (built and re-ran 03202_sz3_codec + 01222_system_codecs locally; both pass):

  • clang-tidy / arm_tidy — compressed_size in doCompressData is now initialized (cppcoreguidelines-init-variables).
  • Undocumented algorithms — getSZ3Algorithm now accepts only ALGO_LORENZO_REG, ALGO_INTERP_LORENZO, ALGO_INTERP (the documented/tested set) and throws ILLEGAL_CODEC_PARAMETER otherwise; ALGO_BIOMD/ALGO_BIOMDXTC/ALGO_NOPRED/ALGO_LOSSLESS go through different, unhardened paths. Added negative tests.
  • Tuple vector dimension — removed the Tuple branch in setVectorDimensionsIfNeeded. A tuple is serialized as one stream per element (each scalar), so using the tuple arity as the dimension made SZ3 read several values from a single-value stream. Verified a one-row Tuple(Float64, Float64) CODEC(SZ3) now round-trips.
  • Wide writer dimension ordering — the SZ3 vector dimension is now set before serializeBinaryBulkWithMultipleStreams, so a large array elements stream that fills the compressed buffer mid-serialization is compressed with the correct dimension.
  • Compact shared codec (earlier comment) — already handled: codecs that need the vector dimension upfront get a per-stream key in streams_by_codec, so they are not shared between streams.

Two I did not change, with rationale:

  • new T[config.num] before validating config.num — with the bounds-checking patch, config.num is validated by Config::load (it must equal the product of the dimensions, and the config is bounded by the buffer). The allocation itself goes through ClickHouse's memory tracker, so a corrupted count can at most trigger a bounded allocation that fails cleanly (MEMORY_LIMIT_EXCEEDED) and is then rejected — it is not a memory-safety issue. Happy to add an explicit pre-check if preferred.
  • NativeFormat.md and the 0x9d method byte — the spec's method-byte table lists only the codecs used for Native wire framing (0x82 LZ4, 0x90 ZSTD, 0x02 NONE). Per-column codecs are intentionally not enumerated there — ALP (0x9c), Gorilla, Delta, FPC, etc. are all absent — so adding SZ3 would be inconsistent with the established convention. SZ3 is a column codec for on-disk storage and is not produced as a Native block codec.

Comment thread src/Compression/CompressionCodecSZ3.cpp Resolved
- `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]>
Comment thread src/Compression/CompressionCodecSZ3.cpp Resolved
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.
Comment thread src/Compression/CompressionCodecSZ3.cpp Resolved
alexey-milovidov and others added 2 commits June 29, 2026 22:03
- 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
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the two latest review findings and merged with the concurrent work on this branch (6faa7882):

  • CODEC(Delta, SZ3) (and any preceding transformation codec) is now rejected: SZ3 is marked as a floating-point time series codec (like ALP/Gorilla/FPC), so codec-stack validation rejects it. system.codecs now reports is_timeseries_codec = 1 for SZ3; reference updated and a negative test added.
  • Lossless (zstd) decompression path hardened: Lossless_zstd::decompress (the outer layer of every SZ3 block) now validates the size header against the buffer, checks the allocation, and checks ZSTD_isError instead of returning a zstd error code as a size. (contrib/sz3 bumped to the ClickHouse/v3.3.2 fork commit with this fix.)

Both verified locally together with the just-merged Map-rejection and variable-length-array merge fixes (cross-part merge of [..] of different lengths, Map(Float64, Float64) rejection, CODEC(Delta, SZ3) rejection, plain round-trips).

Comment thread src/Compression/CompressionCodecSZ3.cpp Resolved
alexey-milovidov and others added 2 commits June 30, 2026 01:07
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]>
Comment thread src/Compression/CompressionCodecSZ3.cpp Resolved
alexey-milovidov added a commit to ClickHouse/SZ3 that referenced this pull request Jun 30, 2026
…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
alexey-milovidov added a commit to ClickHouse/SZ3 that referenced this pull request Jun 30, 2026
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
Comment thread src/Storages/TTLDescription.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Re the AI review "Request changes" verdict on head 840b945d (single ❌ Blocker on src/Storages/TTLDescription.cpp:355):

The AI correctly traces the code path — a table with TTL … RECOMPRESS CODEC(SZ3) can be loaded via the relaxed ATTACH check (e10d76dd), and a subsequent recompression merge reaches MergeTreeData::getCompressionCodecForPart, which calls CompressionCodecFactory::get(recompression_codec, {}) with a null column type and so throws BAD_ARGUMENTS from the lossy-without-type guard in CompressionFactory.cpp. That is accurate.

I'm keeping the current behavior deliberately, because the suggested alternative is worse and there is no useful third option:

  1. This is not reachable from a normal CREATE. TTL … RECOMPRESS CODEC(SZ3) is rejected up front with serverError BAD_ARGUMENTS (see 03202_sz3_codec.sql). It can only be produced by explicitly setting allow_suspicious_ttl_expressions = 1 — the "I know this is suspicious, do it anyway" escape hatch — or by ATTACH of already-persisted metadata.

  2. The ATTACH relaxation is loadability-only, and that is the whole point. e10d76dd exists so that a table already stored with this TTL does not make the server fail to start after an upgrade, mirroring how column codecs are relaxed on attach. The verdict's primary suggestion — "keep rejecting this metadata up front" — reintroduces exactly that server-won't-start failure. A failing background recompression merge on a table the operator deliberately marked suspicious is a strictly better failure mode than a server that refuses to start.

  3. There is no correct recompression to perform. RECOMPRESS applies a single codec to the whole part, and a lossy float-only codec can never validly compress every column. So the only possible outcomes are: (a) reject at load — server-won't-start risk; (b) load and fail the merge with a clear BAD_ARGUMENTS — current behavior; (c) silently ignore the operator's explicit codec. Of these, (b) is the most honest: it neither breaks startup nor silently discards what the operator asked for.

  4. This is consistent with how suspicious settings work in general. They let you build configurations that can misbehave downstream; the guard rail is the explicit opt-in, not preventing every consequence of it. And because SZ3 never shipped in a stable release, no persisted metadata with this TTL exists in the wild — the relaxation is purely defensive.

So the loud, typed BAD_ARGUMENTS on a deliberately-suspicious table is the intended behavior, not a regression. Resolving this verdict as won't-fix.

# Conflicts:
#	tests/queries/0_stateless/01222_system_codecs.reference
Comment thread src/Compression/CompressionFactory.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.00% 85.80% +5.80%
Functions 92.20% 92.70% +0.50%
Branches 72.00% 78.00% +6.00%

Changed lines: Changed C/C++ lines covered: 393/428 (91.82%) · Uncovered code

Full report · Diff report

}
}

void MergeTreeDataPartWriterOnDisk::setVectorDimensionsIfNeeded(CompressionCodecPtr codec, const IColumn * column)

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.

A little bit inefficient, but what else can we do?
Ok to accept.

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

Reviewed.

@alexey-milovidov alexey-milovidov self-assigned this Jul 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 15 not_sure 244 192 -21.3% <0.0001 This PR only adds the opt-in experimental SZ3 lossy float codec (CODEC(SZ3)); no ClickBench table uses it, so this -21.3% shift is run-to-run variance, not a PR effect.

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: 33c752d7-a901-45c9-8f05-b741db91be88
  • MIRAI run: df0a5be0-bf53-44bd-a816-93459afa9eba
  • PR check IDs:
    • clickbench_466228_1783974515
    • clickbench_466242_1783974515
    • clickbench_466248_1783974515
    • tpch_adapted_1_official_466254_1783974515
    • tpch_adapted_1_official_466261_1783974515
    • tpch_adapted_1_official_466268_1783974515

@alexey-milovidov
alexey-milovidov merged commit a1e9dd9 into master Jul 14, 2026
175 of 176 checks passed
@alexey-milovidov
alexey-milovidov deleted the revive-sz3-codec branch July 14, 2026 02:23
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 14, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @alexey-milovidov — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

pull Bot pushed a commit to Spencerx/ClickHouse that referenced this pull request Jul 18, 2026
`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]>
alexey-milovidov added a commit that referenced this pull request Jul 23, 2026
Query forwarding to external databases (#107740) is based on Denis
Vidiaev's #79652, the GeoJSON output format (#108065) on Mark Needham's
#98124, and SZ3 (#108788) revives Konstantin Vedernikov's #83088.

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`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]>
@rienath rienath linked an issue Sep 23, 2026 that may be closed by this pull request

This branch was successfully deployed

1 active deployment
staging - docs — fa1b53f9 Deployed Jul 13, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-experimental Experimental Feature 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.

Multiple crashes in sz3 Add support for SZ Compression

4 participants