Skip to content

Fix GCD codec behavior on signed values - #113798

Merged
rienath merged 8 commits into
ClickHouse:masterfrom
kshcherbatov:kshch/gh78190_gcd_codec_on_negative_integers
Aug 22, 2026
Merged

rienath merged 8 commits into
ClickHouse:masterfrom
kshcherbatov:kshch/gh78190_gcd_codec_on_negative_integers

Conversation

@kshcherbatov

@kshcherbatov kshcherbatov commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #78190

Changelog category (leave one):

  • Improvement

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

Fixed GCD codec handling of signed fixed-width values with negative numbers. Previously it computed the divisor from signed values directly, which could miss the common divisor and significantly reduce compression efficiency for signed integer and decimal columns. It now computes the divisor from magnitudes for signed types while preserving existing behavior for unsigned types and decompression.

Description

GCD pre-processing was using signed values directly when discovering the common divisor. For signed fixed-width storage types, negative values could therefore spoil divisor discovery and make CODEC(GCD) compress much worse than expected, even though the data still had a large common divisor in magnitude.

The fix makes CompressionCodecGCD compute the divisor on unsigned magnitudes for signed types, and threads signedness from the column type into codec instantiation so Int* and signed Decimal* columns use the correct path. This also handles the signed-minimum edge case safely by avoiding signed negation overflow. Unsigned behavior is unchanged.

The type-agnostic fallback is kept deliberately unchanged: unlike T64, GCD still does not throw when type information is unavailable and falls back to the 1-byte unsigned path. That preserves correctness for cases such as default_compression_codec or CODEC(Default) resolution without a concrete column type, but signed data on that path may still compress less efficiently because signedness is unknown.


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

Version info

  • Merged into: 26.8.1.1915 (included in 26.8 and later)

GCD pre-processing was using signed values directly, so negative inputs
could degrade divisor discovery and perform worse than expected on signed
integer-backed data. The fix computes the divisor on absolute values for
signed types and threads signedness from the column type into codec
instantiation, while keeping unsigned behavior unchanged.

Also document the type-agnostic default path: unlike `T64`, `registerCodecGCD`
intentionally does not throw when type information is missing and falls back
to unsigned behavior. This preserves correctness but may reduce compression
efficiency for signed data, and can surface via type-agnostic
`default_compression_codec` / `CODEC(Default)` resolution.

The stateless test covers signed/unsigned integers and decimals, and is
stabilized for randomized settings by forcing wide parts and comparing
ratios where equality is valid.

Closes ClickHouse#78190
@CLAassistant

CLAassistant commented Aug 7, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [344251a]

Summary: ✅


AI Review

Summary

This PR fixes the signed-value arithmetic inside CODEC(GCD) and adds useful regressions for negative inputs and the signed/unsigned Compact-part collision. The signedness half is fixed, but the patch still misses one hash dimension that MergeTreeDataPartWriterCompact relies on for stream sharing, and one previously-discussed CODEC(Default) path still bypasses the signed-aware builder.

Findings

⚠️ Majors

  • [src/Compression/CompressionCodecGCD.cpp:80-83, src/Storages/MergeTree/MergeTreeDataPartWriterCompact.cpp:103-123] CompressionCodecGCD::updateHash still omits gcd_bytes_size. MergeTreeDataPartWriterCompact reuses one CompressedStream per codec hash, so UInt32 CODEC(GCD) and UInt64 CODEC(GCD) in the same Compact part still collide and one column gets compressed with the other's width-specific codec state. That keeps the pre-existing mixed-width compression bug alive even though the PR discussion claimed both width and signedness were covered. Suggested fix: hash gcd_bytes_size here and extend the Compact-part regression to mix widths (or add a focused hash-level test) so the width collision cannot regress again.
  • [dismissed by author -- https://github.com/Fix GCD codec behavior on signed values #113798#discussion_r3740668299] [src/Compression/CompressionFactory.cpp:100-103, src/Storages/MergeTree/MergeTreeData.cpp:10114-10116, src/Storages/MergeTree/MergeTreeDataPartWriterCompact.cpp:97-98] The PR body only exempts type-unknown fallback resolution, but explicit CODEC(Default) on a signed column still resolves the prebuilt type-agnostic default codec even when the writer already knows the concrete subtype. If default_compression_codec resolves to GCD, those signed columns still take the old unsigned path and keep the poor divisor discovery this PR claims to fix. Suggested fix: when resolving Default with a known column_type, rebuild the default codec from its AST against that type instead of returning current_default unchanged.
Final Verdict

Changes requested. The signed-magnitude arithmetic itself looks correct, but the fix is still incomplete on the mixed-width Compact-stream hash path, and the explicitly-dismissed CODEC(Default) path remains unfixed.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 73/80 (91.25%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 7, 2026

private:
const UInt8 gcd_bytes_size;
const bool is_signed_type;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This new is_signed_type state needs to participate in updateHash. MergeTreeDataPartWriterCompact shares one CompressedStream per codec hash, and CompressionCodecMultiple propagates the same GCD hash into CODEC(GCD, ZSTD) chains. After this patch, Int64 CODEC(GCD) and UInt64 CODEC(GCD) of the same width are no longer interchangeable, but they still hash identically because updateHash only covers the AST. In a compact part, the second stream can therefore reuse the first stream's codec object and take the wrong signed/unsigned path, which silently brings back poor compression for one of the columns. Please include at least is_signed_type in the hash here (and ideally gcd_bytes_size as well, for the same stream-sharing reason).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

src/Compression/CompressionCodecGCD.cpp:80-83 still only hashes the AST plus is_signed_type; gcd_bytes_size is no longer part of getHash(). src/Storages/MergeTree/MergeTreeDataPartWriterCompact.cpp:103-123 still keys streams_by_codec only by that hash, so UInt32 CODEC(GCD) and UInt64 CODEC(GCD) in the same Compact part can still reuse one CompressedStream and compress one column with the other width. The broader fix mentioned in the top-level discussion is not in this base yet either: #114189 is still open, so the width-collision half of the original issue is still present in the current code.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-checked the current revision: src/Compression/CompressionCodecGCD.cpp:80-83 still hashes only the AST plus is_signed_type; gcd_bytes_size is still missing from getHash(). Because src/Storages/MergeTree/MergeTreeDataPartWriterCompact.cpp:103-123 still reuses one CompressedStream per codec hash, mixed-width CODEC(GCD) columns such as UInt32 + UInt64 in the same Compact part can still collide and compress one column with the other's width-specific codec state.

@rienath rienath self-assigned this Aug 7, 2026

@rienath rienath left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi! I've left a few comments. Could you please also take a look at bot's review? It's usually very useful. Feel free to reply to it if you disagree for some reason

Comment thread src/Compression/CompressionCodecGCD.cpp Resolved
Comment thread src/Compression/CompressionCodecGCD.cpp Resolved
1. Remove redundant `static` on `toMagnitude` in anonymous namespace.
   Clang-tidy raises readability-static-definition-in-anonymous-namespace
   as a warning-as-error. The function is replaced by a local lambda inside
   `compressDataForType`, which removes the warning and keeps the logic
   co-located with its only use.

2. Halve template instantiations of `compressDataForType`.
   The previous commit introduced six signed specializations
   (Int8/16/32/64/128/256) alongside the six unsigned ones, doubling
   compile-time and binary size. Because two's-complement arithmetic makes
   unsigned modular operations equivalent to signed ones, we can work
   entirely in the unsigned domain: magnitude extraction and sign restoration
   are controlled by a runtime `bool is_signed` parameter, keeping the
   instantiation count at six.

3. Fix `CompressionCodecGCD::updateHash` to include `gcd_bytes_size` and
   `is_signed_type`.
   `MergeTreeDataPartWriterCompact` keys `CompressedStream` reuse on
   `codec->getHash()`. Without hashing these fields, an `Int64 CODEC(GCD)`
   column and a `UInt64 CODEC(GCD)` column in the same compact part could
   share one stream and silently use the wrong signed/unsigned path,
   undoing the fix from the parent commit.
Covers the third fix in f789550: CompressionCodecGCD::updateHash
must include gcd_bytes_size and is_signed_type, because
MergeTreeDataPartWriterCompact keys CompressedStream reuse on
codec->getHash(). Without those fields, an Int64 CODEC(GCD) column
and a UInt64 CODEC(GCD) column written into the same Compact part
hash-collide and share one CompressedStream, so one column silently
adopts the other's sign convention.

The test writes both column types into one Compact part and compares
the total compressed size against the sum of each column compressed
alone in separate tables: with the hash fix, this is (near) additive;
a stream collision inflates the combined size well above the sum.
Per-column stats (system.columns) aren't populated for Compact parts,
so the test asserts on whole-part sizes instead.

Verified the test actually detects the regression: reverting the
hash.update(gcd_bytes_size)/hash.update(is_signed_type) calls and
rebuilding flips the assertion from 1 to 0; restoring the fix flips
it back to 1, reproducibly across runs.

Note: a signedness hash collision alone does not corrupt data -
quotient * gcd == val (mod 2^N) holds regardless of sign convention,
verified exhaustively for 8-bit width - it only degrades the
compression ratio, which is what this test measures.
@kshcherbatov

kshcherbatov commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

@rienath The bug in updateHash #113798 (comment) found by @clickhouse-gh was a real thing, but interestingly there was a pre-existing part of it (not hashing gcd_bytes_size). Now Both gcd_bytes_size and the new is_signed_type are used in updateHash.

That made me wonder if other codecs have the same class of gap, and I probably found one more — logged a separate "potential bug" ticket #113940 for it.

UPD: The other Al's complaint about the
"Default" codec behavior is already documented both in the code comment and in the commit body; I intentionally didn't change that. I've replied in that AI comment thread, but l'Il repeat it here so it doesn't get lost.
UPD2: Though I've created a separate issue for that #114202 It is a defect that affects more than one GCD domain, so it is a larger-scope issue.

04813_gcd_codec_hash_signedness only mixed Int64/UInt64 (same
gcd_bytes_size, different is_signed_type), so it stayed green even if
hash.update(gcd_bytes_size) were dropped from CompressionCodecGCD::updateHash
again. Add a second scenario mixing UInt32/UInt64 (same is_signed_type,
different gcd_bytes_size) to isolate that field. Verified by temporarily
reverting the hash fix and rebuilding: the width-mismatch scenario's
combined part size was ~11.3% larger than the sum of its parts (broken)
vs. ~0.02% (fixed), well outside the existing 5% margin.

4062_gcd_codec_on_negative_integers Case 2 only compared min/max across
the inserted rows, so a regression mangling the middle row would pass
unnoticed since the extrema are unaffected. Compare the full ordered row
set instead.
Comment thread src/Compression/CompressionCodecGCD.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 344251a80 with master bddae8d72 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.40 MiB 701.36 MiB -3.05 MiB (-0.43%)

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 units

8 translation units recompiled, 18 s compile time in total, 8 of them have a recent master baseline.

Job report

@rienath rienath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thank you for creating the issue! Quite nice we also have a fix so fast. Good progress on this PR, I've left more comments

Comment thread src/Compression/CompressionCodecGCD.cpp Resolved
Comment thread src/Compression/CompressionCodecGCD.cpp Resolved
Comment thread src/Compression/CompressionCodecGCD.cpp Resolved
Comment thread src/Compression/CompressionCodecGCD.cpp Resolved
Comment thread src/Compression/CompressionCodecGCD.cpp Resolved
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]>
@kshcherbatov
kshcherbatov requested a review from rienath August 17, 2026 21:27
@kshcherbatov

Copy link
Copy Markdown
Collaborator Author

@rienath not sure whether you get notifications for “request review”, so I’m duplicating it as a comment. Will you please take a look?

@rienath rienath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

A few more comments. Btw, I recommend switching to Opus or higher. Sonnet is too weak for ClickHouse

- Explain why T must be unsigned in compressDataForType even for signed
  columns: the arithmetic needs modulo-2^N semantics, and the magnitude
  of the most negative value does not fit in the signed type.
- Replace rand64 with intHash64(number) in both tests so the data is
  deterministic and any failure is reproducible; compute the modulo on
  the unsigned hash so the value range is symmetric in [-1000, 1000],
  matching the comment.
- Explain why wide parts are forced in the test: Compact parts track
  only the whole-part size, so system.columns would report zero
  per-column bytes.
- Unify variable naming between the two division branches in
  compressDataForType (mag -> magnitude).

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

kshcherbatov commented Aug 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

Hello @rienath, thank you for your comments. I believe they’ve been addressed now.

UPD: I've also made sure that modified tests STILL count as regression markers. I reverted the fix, and ran the tests - they failed, as expected.

@kshcherbatov
kshcherbatov requested a review from rienath August 19, 2026 18:51
The testcase used ordinary negative values for Int128/Int256, so the
separate non-libdivide division branch in compressDataForType was never
exercised at the signed-min overflow edge. Use the literal (-2^127 and
-2^255) so every signed width hits the exact boundary that motivated
the unsigned-magnitude rewrite.

@rienath rienath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nice, thank you!

@rienath
rienath added this pull request to the merge queue Aug 22, 2026
Merged via the queue into ClickHouse:master with commit 900627a Aug 22, 2026
176 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 22, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 22, 2026
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.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 22, 2026
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.
@clickgapai

Copy link
Copy Markdown
Contributor

@kshcherbatov @rienath — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@kshcherbatov

Copy link
Copy Markdown
Collaborator Author

@clickgapai A separate pool request #114189 for #113940 should have resolved this issue by now; it has already been merged, just next to #113798.

@kshcherbatov
kshcherbatov deleted the kshch/gh78190_gcd_codec_on_negative_integers branch August 23, 2026 06:49
@clickgapai

Copy link
Copy Markdown
Contributor

@kshcherbatov #114189 is still open (mergedAt: null), so #115984 still reproduces on master.

  • master tip b1383f4e361a: CompressionCodecGCD::updateHash still hashes only is_signed_type (src/Compression/CompressionCodecGCD.cpp:79-83); ALP/FPC updateHash unchanged. Fix GCD codec behavior on signed values #113798 did merge, which is probably what looked like Hash the type-derived parameter in the ALP, FPC and GCD codecs #114189 landing.
  • Repro on that build — one compact part, UInt32 CODEC(GCD, ZSTD) + UInt64 CODEC(GCD, ZSTD), 200k rows each: mixed table data_compressed_bytes 1 624 123 vs 353 655 + 695 958 when stored separately, i.e. 1.55x the additive baseline. The two codecs hash-collide at MergeTreeDataPartWriterCompact.cpp:103, share one stream, and the UInt64 column ends up compressed by the gcd_bytes_size=4 instance.
  • Hash the type-derived parameter in the ALP, FPC and GCD codecs #114189's + hash.update(gcd_bytes_size) (plus float_width for ALP/FPC) and its 04861_codec_hash_type_derived_params test cover the mixed-width case — nothing extra needed from my side.

Adding Closes: https://github.com/ClickHouse/ClickHouse/issues/115984 to #114189's description would close the issue on merge; otherwise it can be closed manually afterwards.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GCD codec doesn't handle various a case when values can be positive of negative

6 participants