Repository navigation
Hash the type-derived parameter in the ALP, FPC and GCD codecs - #114189
Conversation
MergeTreeDataPartWriterCompact keys compressed-stream reuse on the codec hash and has no key-equality fallback, so a hash collision is an object identity collision. ALP and FPC resolve float_width per column from the column type, it never enters the codec description AST, and updateHash hashed only that AST. A Float32 and a Float64 column under the same codec therefore shared one codec object in a Compact part and the loser of the race was compressed with the other column's width. The reported symptom was a worse compression ratio, but the defect also rejects valid inserts: with Float64 declared first the shared codec carries float_width = 8, the Float32 granule is not a multiple of 8, and the encoders throw CANNOT_COMPRESS. A mixed-width Tuple(Float64, Float32) reaches the same throw, since the codec is resolved per substream. Wide parts are immune, using one stream per column by construction. FPC has the identical defect and is not behind allow_experimental_codecs, so it affects default settings; it ceil-divides instead of throwing, so its half is ratio-only (measured +10.0%). Adding the field to the hash makes both codecs consistent with SZ3, DoubleDelta, Gorilla and T64, which already hash their type-derived width. The change only ever splits cache keys that were wrongly merged. Codec hashes also gate can_substitute_codec_arguments, so a mixed-width tuple now keeps its codec unresolved: Tuple(Float32, Float64) CODEC(FPC) reports CODEC(FPC) rather than CODEC(FPC(12)). That matches what Delta and Gorilla have always done for mixed-width tuples. No format change: both codecs already write float_width into their own block header and decompression reads it from the data, so existing parts stay readable in both directions. Closes: ClickHouse#113940
…terministic The test compares sum(data_compressed_bytes) for exact equality between a mixed-width table (12 B/row) and two single-column tables (4 and 8 B/row). In a Compact part that sum is the size of one data.bin, and the writer emits one compressed block per column per granule, so the granule count scales per-block framing overhead into the total. computeIndexGranularity derives that count from bytes_uncompressed / index_granularity_bytes capped by index_granularity, and both of those settings are randomized by clickhouse-test, so a draw that splits the mixed table into a different granule sequence than the two singles made the assertions print 0 on a correct build. Measured over the randomizer's own domains: 0.0492% of slow-build draws and 0.3475% of release-range draws, i.e. about a 9.4% chance of a red on this PR's own 200-iteration flaky check, recurring on every later run. Witness values (index_granularity 38947, index_granularity_bytes 103887) reproduce it and are fixed by this commit, verified on one fixed binary in both directions. The two pinned values are the product defaults, so the reference is unchanged; naming them is only what defeats the injection in ClientBase::addMergeTreeSettings, which skips any setting the table's own SETTINGS already lists. Pinning the two implicated settings per table is narrower than a no-random-merge-tree-settings tag, and the exact-equality oracle still reddens on unpatched master. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model reviewTwo review rounds, each an independent cold read of the resulting code followed by Round 0 — blocker, fixed. The three byte-equality assertions compare exact
This round — no blockers, no majors. Verified independently before reading Two notes accepted but not blocking:
One future interaction, not a defect here: #113824 would replace Session id: cron:clickhouse-review-slot-10:20260810-153300 |
Pre-PR validation gate
Build id |
|
cc @rienath @Algunenano, could you review this? The Compact-part writer keys compressed-stream reuse on the codec hash with no key-equality fallback, and ALP and FPC left the per-column float width out of that hash, so a Float32 and a Float64 column under the same codec shared one codec object carrying the wrong width, which rejects valid inserts with CANNOT_COMPRESS and otherwise compresses one column worse. |
|
Workflow [PR], commit [366fe60] Summary: ✅
AI ReviewSummaryThis PR fixes Final Verdict✅ No new findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 7/7 (100.00%) · Uncovered code |
|
@groeneai @rienath My two cents on this: it's unclear whether or when #113798 will be merged. To fix the atomicity/isolation logic, I suggest also fixing the GCD gcd_bytes_size right here. Therefore, my pull request will only apply the change to the brand new 'is_signed_type' field on top of these changes. This means that if one of them has to be reverted, we can update all the related code at once. |
|
I would rather leave the GCD hash where it is, for two reasons. It is already in #113798. Your On atomicity, the three codecs are already independently revertable, which is stronger than bundling. The fixes share no code: separate files, separate On timing, #113798 reads as mergeable rather than stuck: the 08-07 review comments are answered and you re-requested review on 08-08, so a re-review is the only thing outstanding. If it does get abandoned, ping me and I will take the GCD hash on its own. |
CI finish ledger - 4fe4918Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Not PR-caused: this branch changes two compression codecs and one stateless test. The new test Both rows resolve to the same holder defect rather than to two independent failures. The leak Four merged candidates were checked and deliberately not linked, because each is already an
Session id: cron:our-pr-ci-monitor:20260810-230000 |
rienath
left a comment
There was a problem hiding this comment.
Looks good! @kshcherbatov is right, let's move the GCD fix to this PR and add a test. From atomicity and revert standpoint, it's better to have it here. We will go forward with the #113798 in any case
A Compact part shares one CompressedStream between columns whose codec hashes are equal (MergeTreeDataPartWriterCompact::addStreams). CompressionCodecGCD hashed only its codec description, which carries no arguments, so two GCD columns of different width mapped to the same stream and the column that lost the race was compressed with the other one's divisor width. The result was a worse compression ratio that also depended on the declaration order. Data round-trips either way, because the divisor width is stored in the GCD block header. Requested by rienath on ClickHouse#114189 to keep the whole updateHash class of fixes in one PR, so a revert stays atomic. The GCD arm of 04861_codec_hash_type_derived_params fails without this change and passes with it; the test is renamed because it no longer covers only float width. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Done in f390f66: Test coverage is in the same file, renamed to Title, changelog and description now enumerate all three codecs. One note on #113798: its I did not change the changelog category. It is currently |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units10 translation units recompiled, 24 s compile time in total, 10 of them have a recent master baseline. |
Polish comments explaining the codec's intent (why GCD is computed over magnitudes for signed types, why `compressDataForType`'s template parameter `T` is always unsigned) and trim the two regression tests to focus on the negative-value/signedness bug this branch actually fixes, dropping coverage that duplicated other tests or was out of scope. Also revert the `hash.update(gcd_bytes_size);` line added to `CompressionCodecGCD::updateHash` in f789550. That line worked around a larger-scope issue: `updateHash` for several codecs does not account for type-resolved parameters, so structurally identical `CODEC(...)` columns of different types can share a `CompressedStream` and silently borrow each other's decoding parameters. This class of bug is tracked and fixed for all affected codecs by ClickHouse#113940 / PR ClickHouse#114189, which will merge before this branch, so the one-off fix here is removed to avoid scope creep and duplicated logic. The corresponding `04813_gcd_codec_hash_signedness` width-collision scenario is dropped for the same reason. Separately, a codec instance can be cached and reused keyed off its textual `CODEC(...)` description, which can serve a suboptimal cached codec for a superficially identical declaration on a different column type. This is a distinct, larger-scope issue tracked as ClickHouse#114202 and is not addressed here. Co-Authored-By: Claude Sonnet 5 <[email protected]>
CI finish ledger - f390f66Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Not PR-caused: this PR's diff is the three codec files plus its own test, and it greps 0 for every Session id: cron:our-pr-ci-monitor:20260818-010000 |
|
Sync, wake up... |
|
@groeneai merge master or make an empty commit. The sync was not created because of github outage |
The sync PR for ClickHouse#114189 was never created because of a GitHub outage, so the already-approved PR could not progress. Requested by rienath on the PR. Co-Authored-By: Claude Fable 5 <[email protected]>
|
@rienath Pushed an empty commit, head is now |
CI finish ledger - 6e309ffEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260820-220000 |
|
@groeneai fix was merged. Resolve conflicts and merge master |
Resolve the CompressionCodecGCD::updateHash conflict as a union of both sides. Master's ClickHouse#113798 added is_signed_type to the hash; this branch added gcd_bytes_size. GCD takes no AST arguments (setCodecDescription("GCD", {})), so both values are derived from the column type and neither reaches updateTreeHash. Keeping only one still lets two CODEC(GCD) columns that differ in the other value share a CompressedStream in Compact parts.
Master's ClickHouse#113798 added <Common/SipHash.h> to this file, so the copy this branch added is now redundant. The ALP and FPC siblings carry one each.
|
Merged master, head is now One conflict, in Also dropped the duplicate |
Reproducer-- clickhouse local (or a server); Compact part, two columns of different
-- value width under the same codec name.
-- 1) ALP: valid INSERT is rejected (26.3+)
SET allow_experimental_codecs = 1;
CREATE TABLE alp_reject (n UInt64, f64 Float64 CODEC(ALP), f32 Float32 CODEC(ALP))
ENGINE = MergeTree ORDER BY n
SETTINGS min_rows_for_wide_part = 1000000000, min_bytes_for_wide_part = 1000000000;
INSERT INTO alp_reject SELECT number, sin(number) * 1000, sin(number) * 1000 FROM numbers(101);
-- Code: 270. DB::Exception: Cannot compress with ALP codec, data size 404 is not aligned to 8. (CANNOT_COMPRESS)
-- 2) FPC: no error, just ~10% worse compression (all branches)
CREATE TABLE fpc_mix (f32 Float32 CODEC(FPC), f64 Float64 CODEC(FPC)) ENGINE = MergeTree ORDER BY tuple()
SETTINGS min_rows_for_wide_part = 1000000000, min_bytes_for_wide_part = 1000000000;
CREATE TABLE fpc_32 (f32 Float32 CODEC(FPC)) ENGINE = MergeTree ORDER BY tuple()
SETTINGS min_rows_for_wide_part = 1000000000, min_bytes_for_wide_part = 1000000000;
CREATE TABLE fpc_64 (f64 Float64 CODEC(FPC)) ENGINE = MergeTree ORDER BY tuple()
SETTINGS min_rows_for_wide_part = 1000000000, min_bytes_for_wide_part = 1000000000;
INSERT INTO fpc_mix SELECT sin(number) * 1000, sin(number) * 1000 FROM numbers(20000);
INSERT INTO fpc_32 SELECT sin(number) * 1000 FROM numbers(20000);
INSERT INTO fpc_64 SELECT sin(number) * 1000 FROM numbers(20000);
SELECT (SELECT sum(data_compressed_bytes) FROM system.parts WHERE table = 'fpc_mix' AND active)
= (SELECT sum(data_compressed_bytes) FROM system.parts WHERE table IN ('fpc_32','fpc_64') AND active);
-- observed 0 (238887 vs 217185 bytes); expected 1Results:
CC component owner: @alexey-milovidov @Algunenano Analysis metadata
Introducing change: not identified
|
Backport request:
|
| build | ALP mixed-width insert | FPC compressed bytes, shared vs separate |
|---|---|---|
master 97a238df (26.8.1.1940) |
ok, 101 rows | 217185 == 217185 |
| 26.7.6.9 | Code: 270 ... data size 404 is not aligned to 8 |
238887 vs 217185 |
| 26.6.4.13 | same | 238887 vs 217185 |
| 26.5.8.14 | same | 238887 vs 217185 |
| 26.3.22.4 | same | 238887 vs 217185 |
| 25.8.33.4 | Code: 432 Unknown codec family: ALP |
238887 vs 217185 |
The master row is attributable to this fix, since 58d7129b is an ancestor of 97a238df. The
21702-byte gap is the compression lost to the shared stream, 10.0% on 20k rows.
All five branches conflict, so the robot will open cherry-pick PRs rather than take the
resolved-tree fast path. Two things will bite whoever resolves them:
is_signed_typecomes from Fix GCD codec behavior on signed values #113798, which is on master but is not an ancestor of any release
branch (0 occurrences inCompressionCodecGCD.cppthere). The conflict block offers both
hash.update(gcd_bytes_size)andhash.update(is_signed_type), and taking it verbatim will not
compile. Keeping onlygcd_bytes_sizepreserves this fix: the GCD case in04861isUInt16
vsUInt64, so it differs in width and not in signedness.- On the release branches
ICompressionCodec.honly forward-declaresSipHashand
CompressionCodecGCD.cppcarries no<Common/SipHash.h>include, so that include has to
survive the resolution orhash.updatefails on an incomplete type. The 26.x ALP conflict is in
the include block as well, not at the fix site.
CompressionCodecFPC.cpp auto-merges cleanly on all five. CompressionCodecALP.cpp does not exist
on 25.8, so that branch gets the FPC and GCD halves only.
|
No need backport. ALP is experimental. Improved ratios of FPC and GCD are nice, but we don't backport improvements |
|
Understood, no backport. Withdrawing the label request above. |
|
Hi — this looks like a backport candidate for |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
ALP,FPCandGCDomitting their type-derived parameter from the codec hash. In a Compact part the writer shares one compressed stream per distinct codec hash, so two columns of different value width under the same codec collided and shared one codec object carrying the wrong width. This rejected valid inserts withCANNOT_COMPRESSwhen the widths disagreed, and otherwise compressed one of the columns worse than it should have.Description
Closes: #113940
Related: #113798
MergeTreeDataPartWriterCompact::addStreamskeys compressed-stream reuse oncodec->getHash()with no key-equality fallback, so a hash collision is an object-identity collision. Three codecs resolve a parameter from the column type, keep it out of the codec description AST, and hash only that AST, so two columns of different width shared one codec object and the loser of the race got the other's width:ALPandFPCderivefloat_width. WithFloat64declared first the shared codec carriesfloat_width = 8, aFloat32granule is not a multiple of 8, andALPthrowsCode: 270 ... data size 404 is not aligned to 8 (CANNOT_COMPRESS). A mixed-widthTuple(Float64, Float32) CODEC(ALP)reaches the same throw, since the codec is resolved per substream.FPCceil-divides instead of throwing, so its half is ratio-only: measured +10.0%.GCDderivesgcd_bytes_size, so the divisor width depended on declaration order and the ratio suffered. Data round-trips either way, because the width is in the GCD block header. Added on review request so the class stays revertable as one change; Fix GCD codec behavior on signed values #113798 fixes the sameupdateHashfor its ownis_signed_typeand goes forward independently.The fix adds the missing field to each hash, matching
SZ3,DoubleDelta,Gorilla,T64andDelta, which already hash their type-derived width. Wide parts were never affected: one stream per column.Two consequences worth noting. Codec hashes also gate
can_substitute_codec_arguments, a whole-codec flag, soTuple(Float32, Float64) CODEC(FPC, LZ4)now shows asCODEC(FPC, LZ4)rather thanCODEC(FPC(12), LZ4);DeltaandGorillaalready behave this way, same-width tuples still resolve, and a bareCODEC(FPC)still means level 12. No format change: each codec records the parameter in its own block header, so existing parts stay readable both ways.Validation
Debug build, base
f9dd35fa7f57bbd8ec97be53c15acd82848a98f1.ALP/FPC (build id
a0327326e75c88c307e5efda56857c3df38552c7):INSERT, default table, f64 then f32, 101 rowsCode: 270 ... 404 is not aligned to 8Tuple(Float64, Float32) CODEC(ALP), default tableCode: 270 ... 12012 is not aligned to 8GCD (build id
bb612f0c6681bdde02436c553770393ff66f63fe, pre-fix control0a3b06892a5a9cafc8bc2c68a19d5fe9dff3f312):UInt16+UInt64mixed vs two single-column tablesu16, u64vsu64, u16)04861_codec_hash_type_derived_params(renamed, since it no longer covers only float width) fails on the parent commit and passes with the fix; the two new GCD assertions were verified to redden independently, 5/5 runs failing before and 10/10 passing after under randomized settings, and 4-way self-parallel runs pass.A control build patching only
ALPleft theFPCnumbers at exactly 238887, confirming theFPCmeasurement is not leaking from theALPchange.Workflow [PR]
Sync PR [sync-upstream/pr/114189]
Version info
26.8.1.1938(included in26.8and later)