Skip to content

Check the widening of an Iceberg decimal bound for overflow - #114962

Closed
yussypu wants to merge 9 commits into
ClickHouse:masterfrom
yussypu:iceberg-decimal-bounds-overflow
Closed

yussypu wants to merge 9 commits into
ClickHouse:masterfrom
yussypu:iceberg-decimal-bounds-overflow

Conversation

@yussypu

@yussypu yussypu commented Aug 15, 2026 •

Copy link
Copy Markdown

Related: #115832
Related: #114929

#115832 rewrote the manifest bound decoder to deserialize Decimal32, Decimal64, Decimal128 and Decimal256, which covers the abort reported in #114929. This pull request is rebuilt on top of that work and now carries only the part it does not include.

deserializeDecimalBound still widens the bound by one integral unit without checking the result:

NativeType scaler = lower_bound ? -10 : 10;
for (UInt32 i = 1; i < scale; ++i)
    scaler *= 10;

unscaled_value += scaler;

A bound comes from the manifest and is never checked against the declared precision, so it can occupy the full width of the native type. Adding 10^scale to a full width Int32 or Int64 is signed overflow, which is undefined behaviour and aborts a build with the undefined behaviour sanitizer. The addition is now checked, and a bound that cannot be widened is dropped rather than wrapped, which is what already happens for a bound too wide for its type.

A well formed manifest cannot reach this: the largest value a Decimal(9, 9) can hold is 999999999 unscaled, and adding 10^9 stays inside Int32. Only a malformed manifest gets there, so there is no user visible change and no test that would fail on master. The decimal bound coverage added by #115832 in test_writes_decimal exercises the surrounding path.

Changelog category (leave one):

Not for changelog (changelog entry is not required)


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

Decoding a `Decimal` column bound from an Iceberg manifest ran in
`int64_t` regardless of how wide the bound was. Three steps overflowed:
the big-endian accumulation and the sign extension for a bound of eight
bytes or more, and the `10^scale` scaler for a scale above 18. A
`Decimal(38, 30)` column is enough to reach all three, and any query with
a filter parses the bounds of every column in the manifest entry, so the
filter need not touch the decimal. A build with the undefined behaviour
sanitizer aborts.

Only `Decimal32` and `Decimal64` bounds ever become a `Field`, so decode
just those and reject anything wider up front, which keeps the observable
behaviour. The sign extension is now skipped when the value already fills
all 64 bits, where it used to shift by the width of the type and, on the
usual targets, turn every eight-byte negative bound into -1.

Closes: ClickHouse#114929
@CLAassistant

CLAassistant commented Aug 15, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0e065f0]

Summary: ✅


AI Review

Summary

The PR reduces to one targeted fix in deserializeDecimalBound: widen rounded Iceberg decimal bounds with common::addOverflow and drop the bound on overflow instead of triggering UB. That is the right direction, but on current master the same path now handles Decimal128, and the new nullopt result causes valid Spark Decimal(38,38) statistics to lose all min/max pruning instead of keeping the surviving one-sided bound.

Findings

⚠️ Majors

  • [src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp:99] This overflow path is reachable on valid Decimal(38,38) manifests, not only malformed ones. tests/integration/test_storage_iceberg_with_spark/test_minmax_pruning.py:224-230 already documents that Spark stores decimal file bounds rounded to integral units before we widen them. For a file containing 0.5::Decimal(38,38), the rounded bound arriving here is 10^38: the lower side widens to 0, but the upper side widens to 2 * 10^38 and trips addOverflow. The caller at src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp:520-523 then drops the whole hyperrectangle instead of keeping the usable one-sided range, which disables all min/max pruning for those valid files on this column.
    Suggested fix: preserve the surviving endpoint with Range::createLeftBounded / Range::createRightBounded, or explicitly cover and document the full-range drop if that loss of pruning is intentional.
Tests
  • ⚠️ Add a focused Spark Iceberg regression for Decimal(38,38) values around 0.5 and -0.5 so the widened-bound overflow path is exercised on valid manifests and the intended pruning behavior is pinned down.
Final Verdict

⚠️ Needs changes before merge: the UB fix is good, but it currently discards usable one-sided Decimal128 statistics on valid manifests.

LLVM Coverage Report

Measured on commit 0e065f0.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.80% +0.10%

Changed lines: Changed C/C++ lines covered: 4/5 (80.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 15, 2026
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0e065f003 with master 617af45cc (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 710.07 MiB 707.02 MiB -3.06 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

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

Job report

@PedroTadim

Copy link
Copy Markdown
Member

Hello! Can you refactor the PR description according to the standard format?

@CarlosFelipeOR

Copy link
Copy Markdown

Hi @yussypu , tagging you here to make sure you see Pedro’s comment. Could you please update the PR description to follow the standard format?

The fixture builder was named .py, which clickhouse-test treats as a test
file, so the runner executed it with no arguments and the fast test failed.
Helper scripts use the .python extension.
@yussypu

yussypu commented Aug 28, 2026

Copy link
Copy Markdown
Author

@PedroTadim @CarlosFelipeOR thanks for the ping, and sorry for the delay. The description now follows .github/PULL_REQUEST_TEMPLATE.md: the linked issue, a short description of the change and the motivation, then the changelog category and the changelog entry.

The Fast test failure is also fixed. The fixture builder was named .py, which clickhouse-test treats as a test file (TEST_FILE_EXTENSIONS), so the runner executed it directly with no arguments. It is now 04907_iceberg_decimal_bounds_overflow.python, matching the other helper scripts in the suite, and only the .sh is collected as a test.

@yussypu yussypu closed this Aug 28, 2026
@yussypu yussypu reopened this Aug 28, 2026
@yussypu yussypu closed this Aug 28, 2026
@yussypu yussypu reopened this Aug 28, 2026
@scanhex12 scanhex12 self-assigned this Aug 28, 2026

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.

please write an integration test

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.

We have a lot of staff for big endian encoding, can't we use it here?

The bound decoder accumulated the big endian unscaled value by hand into
`int64_t`, so it overflowed for anything wider than 64 bits and could only
return `Decimal32` and `Decimal64`. It now sign extends the bound into the
column's native type and uses `transformEndianness`, which covers
`Decimal32`, `Decimal64`, `Decimal128` and `Decimal256` with one code path,
and takes the scaler from `DecimalUtils::scaleMultiplier` instead of a loop.

A `decimal(38, 30)` bound is now decoded rather than discarded, so it takes
part in min/max pruning.

The stateless test and its hardcoded fixture are replaced by an integration
test that builds real Iceberg tables with PyIceberg, one column per decimal
width, and checks the values and the pruning they drive.
Master gained decimal bound deserialization for every width in ClickHouse#115832, which
supersedes the decoding this branch carried. What remains is the unchecked
widening of the bound, kept here on top of master's version.
@yussypu yussypu changed the title Fix signed integer overflow reading Iceberg decimal bounds Check the widening of an Iceberg decimal bound for overflow Aug 28, 2026
@clickhouse-gh clickhouse-gh Bot removed the pr-bugfix Pull request with bugfix, not backported by default label Aug 28, 2026
@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 28, 2026
/// A bound is read from the manifest and is never checked against the declared precision,
/// so a full width one can still leave the type when it is widened by an integral unit.
/// That is signed overflow, which aborts a build with the undefined behaviour sanitizer.
if (common::addOverflow(unscaled_value, scaler, unscaled_value))

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 overflow path is reachable on valid Decimal(38,38) manifests, not only malformed ones. tests/integration/test_storage_iceberg_with_spark/test_minmax_pruning.py:224-230 already documents that Spark stores decimal file bounds rounded to integral units before we widen them, so a file containing 0.5::Decimal(38,38) arrives here with unscaled_value = 10^38. The lower side still widens to 0, but the upper side widens to 2 * 10^38, trips addOverflow, and ManifestFileIterator.cpp:520-523 then drops the whole hyperrectangle instead of keeping the usable one-sided range.

That means valid files of this type lose all min/max pruning on this column. Can we preserve the surviving endpoint with Range::createLeftBounded / Range::createRightBounded, or at least add a focused Decimal(38,38) regression if the full-range drop is intentional?

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.

Yes, the max bound should be saturated.

@yussypu

yussypu commented Aug 29, 2026

Copy link
Copy Markdown
Author

@scanhex12 thanks for the review. All three points are addressed, though not in the way you would expect, so the short version first: #115832 merged while I was working on them and already does everything you asked, so this pull request is rebuilt on top of master and now carries only the one piece that #115832 does not include.

Point by point:

What is left is six lines. deserializeDecimalBound still widens the bound with an unchecked unscaled_value += scaler. A bound is read from the manifest and is never checked against the declared precision, so it can occupy the full width of the native type, and adding 10^scale to a full width Int32 or Int64 is signed overflow. The addition is checked now, and a bound that cannot be widened is dropped, which is what already happens for a bound too wide for its type.

A well formed manifest cannot reach it: the largest value a Decimal(9, 9) holds is 999999999 unscaled, and 999999999 + 10^9 still fits Int32. So there is no user visible change and no test that would fail on master, and the category is now Not for changelog. The title and description are updated to match. Happy to close this instead if you would rather not carry the check.

@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 4, 2026
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Sep 4, 2026
A Decimal bound is decoded twice: once as the manifest declares it, and once
moved one integral unit outwards to undo Iceberg's rounding. The previous
commit checked the ordering on the declared pair, because an inversion
narrower than two integral units is still ordered after that shift. But the
pair that reaches Range, and so key_condition.mayBeTrueInRange, is the
compensated one, and the shift can also invert a pair that is ordered as
declared. The compensation widens monotonically only while it stays inside the
target width, and it leaves it at the closing static_cast<Int32> for a
Decimal32, and in unscaled_value += scaler itself for a Decimal64 bound near
INT64_MAX.

Neither pair alone is the right predicate, so the check now tests both. The
union cannot decline a file the declared check kept: a declared-ordered pair
that does not leave its type is compensated-ordered as well.

A conforming value cannot reach this. A Decimal32 has precision at most 9, so
its unscaled value is below 10^9 and adding the scaler keeps it under
INT32_MAX, and a Decimal64 has the same slack. It needs a bound outside the
column's declared precision, and nothing rejects one: the bound bytes are
stored verbatim with no length or magnitude check, and four bytes is a legal
encoding for a Decimal32 column.

The regression arm uses Decimal(9, 1) rather than a Decimal64. Precision 9
makes it a Decimal32, where the value leaves the type through an explicit
static_cast, which is a modular conversion. On a Decimal64 the overflow would
be in unscaled_value += scaler, which is signed overflow, so the arm itself
would abort a build with the undefined behaviour sanitizer both before and
after this change.

ClickHouse#114962 fixes the same overflow where it happens, rejecting an unscaled value
out of range before the cast. The two are complementary: it removes this
reason for the compensated pair to invert, and the check keeps holding for any
other reason.

The null check on the declared decode is dropped, because it cannot run. Both
of the decoder's std::nullopt returns are independent of the compensation and
the encoded bytes are taken by value, so a nullopt declared decode implies a
nullopt compensated decode, which the check above it already handles. That
still holds with ClickHouse#114962 applied: its overflow rejection only fires when the
compensation runs, and it rejects a bound wider than its own type up front, so
a declared value is always already in range for the narrowing check it adds.
@filimonov filimonov mentioned this pull request Sep 7, 2026
2 of 30 tasks
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Dear @scanhex12, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@alexey-milovidov alexey-milovidov self-assigned this Nov 5, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Closing as superseded: master already contains this change, and goes further.

Checked against master at 5fad0b4:

  • Ancestry: 67821f6 ("Reject an Iceberg decimal bound that cannot be widened inside its type") is an ancestor of master. It added the same common::addOverflow check on the widening that this PR adds.
  • Current state: Saturate an Iceberg decimal bound that cannot be widened inside its type #119712 then moved deserializeDecimalBound to src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergFieldParseHelpers.cpp. When widening overflows, the bound is now saturated to 10^P - 1 on the outer side of the range and rejected on the inner side, instead of being dropped. That is the saturation asked for in the review on this PR. No later commit to the file reverts it, and no unchecked unscaled_value += remains in src/Storages/ObjectStorage/.

Merging master into this branch conflicts only because the code moved. The PR's whole diff (an addOverflow check that returns std::nullopt) has nothing left to add.

Thank you @yussypu for the report and the work on this.

@clickhouse-gh clickhouse-gh Bot added comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 22, 2026
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 comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... external Author is not a member of the ClickHouse organization pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants