Skip to content

Fix undefined float-to-int cast on NaN in the SZ3 codec quantizer - #110762

Merged
alexey-milovidov merged 6 commits into
masterfrom
fix/sz3-nan-cast-ubsan
Jul 18, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
fix/sz3-nan-cast-ubsan

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

Related: #110430
Caused by: #108788

Stress tests with UBSan sporadically fail with:

contrib/sz3/include/SZ3/quantizer/LinearQuantizer.hpp:45:49: runtime error: nan is outside the range of representable values of type 'long'

for example on 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 (also seen on master and several unrelated PRs since #108788 revived the SZ3 codec).

SZ3::LinearQuantizer::quantize_and_overwrite casts fabs(data - pred) * error_bound_reciprocal straight to int64_t; for NaN or infinite input the cast is undefined behavior. Such values can never be quantized — the error-bound recheck below the cast sends them to the unpredictable (lossless) storage anyway — so the fix in the ClickHouse/SZ3 fork (commit dda0caee243719d1dad10a9f05bc18eeedc2ab6b on the ClickHouse/v3.3.2 branch) routes them there before the cast. Behavior for finite in-range values is unchanged: scaled_diff >= radius * 2 implies the old quant_index check would have sent them to the unpredictable path as well.

Verified with a standalone reproducer compiled with -fsanitize=undefined,float-cast-overflow -fno-sanitize-recover=all: before the fix it fails exactly like the stress report; after the fix, NaN and infinities round-trip losslessly through all three supported algorithms (ALGO_INTERP, ALGO_INTERP_LORENZO, ALGO_LORENZO_REG) for both Float32 and Float64, including the codec's default REL error-bound mode. The new test 04603_sz3_codec_non_finite covers the same scenario end-to-end and would trigger the UBSan report without the fix.

The submodule bump (to ff760cc on the same branch, ClickHouse/SZ3#2) additionally fixes the remaining_length accounting after a Huffman decode in RegressionPredictor::load and ComposedPredictor::load: the code subtracted the uncompressed index count instead of the bytes the decode consumed, which understated the bound and made a later encoder.load reject valid data. As a result, a column written with CODEC(SZ3('ALGO_LORENZO_REG', ...)) could be inserted but failed every later read with CORRUPTED_DATA ("SZ3 Huffman: encoded length exceeds compressed buffer"). The new test 04604_sz3_codec_lorenzo_reg covers the round trip end-to-end (including after a merge recompresses the data, where the lossy error of each pass compounds), and the new gtest SZ3Test.LorenzoRegSerializesAndDecodesRegressionCoefficients asserts that this data shape really stays on the ALGO_LORENZO_REG path and serializes a non-empty regression-coefficient stream, so the fixed loaders are positively exercised.

Changelog category (leave one):

  • Experimental Feature

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

Fixed reading data compressed with the experimental SZ3('ALGO_LORENZO_REG', ...) codec, which previously failed with CORRUPTED_DATA, and avoided undefined behavior when compressing non-finite floating-point values (NaN and infinities) with the experimental SZ3 codec.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

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

`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: #110430
Caused by: #108788

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f347caf]

Summary: ✅


AI Review

Summary

This PR fixes two experimental SZ3 codec regressions by pulling in the LinearQuantizer non-finite cast guard and the ALGO_LORENZO_REG remaining_length fix from ClickHouse/SZ3, then adding focused SQL and gtest coverage for both behaviors. I re-checked the full PR discussion, the current ClickHouse codec code, and the actual SZ3 delta, and the earlier review concerns are addressed in the current diff; I did not find a remaining unresolved issue.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-ci submodule changed At least one submodule changed in this PR. labels Jul 17, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jul 17, 2026
Advance the `contrib/sz3` submodule from `dda0caee` to `ff760cc`, the current
tip of the `ClickHouse/v3.3.2` branch. In addition to the quantizer NaN cast
fix already pinned, this brings in the fix for `remaining_length` accounting
after Huffman `decode` in `RegressionPredictor`/`ComposedPredictor`
(ClickHouse/SZ3#2), which otherwise made a column compressed with
`CODEC(SZ3('ALGO_LORENZO_REG', ...))` fail to decompress after being written.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread contrib/sz3 Resolved
Cover the `remaining_length` accounting fix pulled in by the submodule bump: a
`Float64` column written with `CODEC(SZ3('ALGO_LORENZO_REG', ...))` is inserted
and read back within the error bound, before and after a merge. Before the fix
the read failed with `CORRUPTED_DATA` ("SZ3 Huffman: encoded length exceeds
compressed buffer") for all but the smallest inputs, so the data was effectively
lost. Verified against the `contrib/sz3` library that the read throws at the
pre-fix pin `dda0caee` and round-trips at the pinned `ff760cc`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only updates the experimental SZ3 compression codec (contrib submodule bump plus regression tests for the ALGO_LORENZO_REG decode path and non-finite handling) — a code path that ClickBench and TPC-H queries never execute. None of the flagged deltas can be attributed to this change. Q4 (-14.0%) and Q15 (-20.2%) were already correctly held at no_change within master's variance band. Q23's ×2.3 faster reading is downgraded to not_sure: the query is off-path for this diff and its source run was noisy, so the delta is run-to-run variance rather than a real improvement.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 23 not_sure 165 72 ×2.3 faster <0.0001 This PR only fixes the experimental SZ3 codec, which Q23 never touches, and the source run was noisy (wide run-to-run spread), so the ×2.3 faster reading is 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: 4151441e-91ce-4181-8f15-5bcf3ae68869
  • MIRAI run: 0f5625cb-2a86-4f17-8dbd-333d34dbeba5
  • PR check IDs:
    • clickbench_171061_1784353040
    • clickbench_171067_1784353040
    • clickbench_171073_1784353040
    • tpch_adapted_1_official_171085_1784353040
    • tpch_adapted_1_official_171095_1784353040
    • tpch_adapted_1_official_171108_1784353040

alexey-milovidov and others added 2 commits July 17, 2026 20:47
The test asserted that after OPTIMIZE TABLE ... FINAL the data still deviates
from the original by at most the codec's ABS error bound. That does not hold: a
merge decompresses and recompresses the column through the lossy SZ3 codec, so
every pass adds up to the bound (0.01) on top of the previous one, and the
observed error after the merge reaches ~0.0197. The check failed as `1 0` in
every stateless CI job. Allow up to three lossy passes (the initial write, a
possible concurrent background merge of the two parts, and the OPTIMIZE FINAL
rewrite), i.e. 0.031.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110762&sha=85d8815db3e8ae735bc733f161af214e000d0228&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
PR: #110762

Co-Authored-By: Claude Fable 5 <[email protected]>
The review noted that the SQL round-trip assertions would also pass if SZ3
silently downgraded a block to the bit-exact `ALGO_LOSSLESS` fallback, or if no
block selected the regression predictor, so a later tuning change could stop
exercising the fixed code while the tests stay green.

- Add the gtest `SZ3Test.LorenzoRegSerializesAndDecodesRegressionCoefficients`:
  it compresses the same data shape as test 04604 with
  `SZ3('ALGO_LORENZO_REG', 'ABS', 0.01)`, asserts that the stored `cmprAlgo`
  stays `ALGO_LORENZO_REG`, that a non-empty regression-coefficient stream is
  serialized (the count is the leading field of the inner buffer), and that
  decompression - which decodes those coefficients through the fixed
  `RegressionPredictor::load` - succeeds, is lossy, and stays within the bound.
- Tests 04603 and 04604: assert that some finite values changed, a positive
  signal that the columns stayed on the lossy path (the lossless fallback
  would reproduce the input bit-exactly). The default-configured columns in
  test 04603 are documented as intentionally lossless: their REL error bound
  is relative to the value range, which is infinite for this data.

PR: #110762

Co-Authored-By: Claude Fable 5 <[email protected]>
… merges

The first `max(abs(orig - val)) <= 0.011` assertion assumed the two inserted
parts were still unmerged (one lossy pass each), but background merges were not
stopped: a merge could fire between the second `INSERT` and the `SELECT`, send
`val` through a second lossy pass, and legitimately exceed the one-pass bound,
making the test flaky.

Stop merges before the inserts so the pre-merge check sees exactly one lossy
pass, and start them again right before `OPTIMIZE TABLE ... FINAL` so the
explicit merge still runs. The post-merge check is then deterministically two
passes (initial write plus the `OPTIMIZE FINAL` merge). The merge control is
table-scoped, so the test stays parallel-safe.

Verified against a build with `contrib/sz3` at `ff760cc`: the test output
matches the reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed both required actions from the AI review:

  • Test determinism (04604_sz3_codec_lorenzo_reg.sql): the first <= 0.011 check no longer races background merges. SYSTEM STOP MERGES now runs before the two inserts, so that assertion sees exactly one lossy pass, and SYSTEM START MERGES runs right before OPTIMIZE TABLE ... FINAL so the explicit merge (two passes total) still happens. The control is table-scoped, so the test stays parallel-safe. Verified against a build with contrib/sz3 at ff760cc; output matches the reference.
  • Changelog: added a user-readable entry. I set the category to Experimental Feature rather than Bug Fix — the "Bug Fix" category is defined as "user-visible misbehavior in an official stable release", but the SZ3 codec is experimental (requires allow_experimental_codecs) and was only revived on master in Revive SZ3 compression codec #108788, so neither the codec nor this CORRUPTED_DATA bug has ever shipped in a stable release. "Experimental Feature" (with the changelog entry) reflects that accurately while still capturing the user-facing fix.

@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature and removed pr-ci labels Jul 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.20% 86.10% +5.90%
Functions 90.80% 91.80% +1.00%
Branches 72.20% 78.20% +6.00%

Changed lines: Changed C/C++ lines covered: 32/32 (100.00%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 18, 2026
Merged via the queue into master with commit e988375 Jul 18, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/sz3-nan-cast-ubsan branch July 18, 2026 16:22
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 18, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The test asserted that after OPTIMIZE TABLE ... FINAL the data still deviates
from the original by at most the codec's ABS error bound. That does not hold: a
merge decompresses and recompresses the column through the lossy SZ3 codec, so
every pass adds up to the bound (0.01) on top of the previous one, and the
observed error after the merge reaches ~0.0197. The check failed as `1 0` in
every stateless CI job. Allow up to three lossy passes (the initial write, a
possible concurrent background merge of the two parts, and the OPTIMIZE FINAL
rewrite), i.e. 0.031.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110762&sha=85d8815db3e8ae735bc733f161af214e000d0228&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
PR: ClickHouse#110762

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The review noted that the SQL round-trip assertions would also pass if SZ3
silently downgraded a block to the bit-exact `ALGO_LOSSLESS` fallback, or if no
block selected the regression predictor, so a later tuning change could stop
exercising the fixed code while the tests stay green.

- Add the gtest `SZ3Test.LorenzoRegSerializesAndDecodesRegressionCoefficients`:
  it compresses the same data shape as test 04604 with
  `SZ3('ALGO_LORENZO_REG', 'ABS', 0.01)`, asserts that the stored `cmprAlgo`
  stays `ALGO_LORENZO_REG`, that a non-empty regression-coefficient stream is
  serialized (the count is the leading field of the inner buffer), and that
  decompression - which decodes those coefficients through the fixed
  `RegressionPredictor::load` - succeeds, is lossy, and stays within the bound.
- Tests 04603 and 04604: assert that some finite values changed, a positive
  signal that the columns stayed on the lossy path (the lossless fallback
  would reproduce the input bit-exactly). The default-configured columns in
  test 04603 are documented as intentionally lossless: their REL error bound
  is relative to the value range, which is infinite for this data.

PR: ClickHouse#110762

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-ubsan

Fix undefined float-to-int cast on NaN in the `SZ3` codec quantizer
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.

2 participants