Skip to content

Do not prune Iceberg data files on inverted manifest bounds - #116604

Merged
PedroTadim merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai-iceberg-inverted-manifest-bounds
Sep 4, 2026
Merged

PedroTadim merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai-iceberg-inverted-manifest-bounds

Conversation

@groeneai

@groeneai groeneai commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a query over an Iceberg table returning fewer rows than the table holds when a manifest declares a lower bound above the upper bound for a filtered column. Such a pair describes an empty range, so min/max pruning dropped the data file holding the matching rows; those bounds are now ignored instead. Closes #116499.

Description

Closes: #116499
Related: #114962

A manifest can declare lower_bounds[c] above upper_bounds[c], and nothing checks it. canBePruned hands both decoded borders to mayBeTrueInRange, which requires a lower border not exceeding the upper one. An inverted pair is an empty range, so the file is dropped as MIN_MAX_INDEX_PRUNED: WHERE id < 500 returns 0 where 500 is correct, a bare count() returns 2000. Debug and sanitizer builds abort on the chassert opening checkInRange.

This checks the pair where it is decoded and, when inverted, drops that column's bounds instead of pruning on an impossible range, warning unless the shift already made a bound unreadable. Other columns and the partition path are untouched: canBePruned skips a column with no hyperrectangles entry, and of the five mayBeTrueInRange callers only this one passes distinct borders.

The check reads the values as declared: Iceberg rounds Decimal bounds to the integral part and the decoder moves each side one integral unit outwards, hiding an inversion narrower than two integral units.

The shift can also leave the type: the bound is never checked against the declared precision, and since #115832 the sum is computed in the decimal's native type. 2147483642 + 10 for a Decimal(9, 1) bound is signed integer overflow: it halts a UBSan build, and wraps to an inverted pair without one. Such a bound is now rejected, so the existing decode-failure path drops the column's condition and logs it at debug level. Only Decimal(38, 38) lacks the headroom for a conforming bound, above roughly 0.7, and loses pruning where it overflows today.

Not addressed: a bound shorter than its fixed-width type is an out-of-bounds read in insertData; checkInHyperrectangle takes Parquet and Hive statistics equally unchecked; master's newer getMaterializedRowLineageRange reads these bounds unchecked too.

Validation

The test is integration rather than stateless because it rewrites an Avro manifest out of band. Each arm corrupts one column, leaving a well-formed one whose pruning must survive, and counts through check_validity_and_get_prunned_files_general, which also asserts both runs return the same rows. pyiceberg writes the Decimal table, since the ClickHouse writer rejects it.

table, state assertions why this arm
(id Int64, s String) well formed id prunes 3, s prunes 3 control: not pruning at all would satisfy the rest
invert id only id prunes 0, s still prunes 3 pins the fallback as per column
invert s too both prune 0 the reported shape
(id, d Decimal(10, 2), e Decimal(9, 1)) well formed each prunes 1 control; pins the typed literals as armed
invert d only d prunes 0, id still prunes 1 inversion the shift hides
e bound at the edge of Int32 e prunes 0, id still prunes 1 bound with no shifted form

Both functions pass at this revision. Earlier: 8 passed in one run including all 6 parametrizations of test_writes_statistics_by_minmax_pruning.py at their exact counts, whose tables come from single-row inserts, so lower == upper everywhere and the check does not fire on equality; 40 passed over 20 consecutive runs. Three mutants, each failing one arm while the other function passes: hyperrectangles.clear(); break; for the continue fails the s arm; deleting the declared re-decode fails the d arm on wrong rows; restoring the unchecked unscaled_value += scaler fails the e arm on the compareTuples abort.

Release binaries, WHERE id < 500 on a 2000-row table whose answer is 500: 26.8.1.2012, 26.7.6.17, 26.6.4.26, 26.5.8.25 and 26.3.23.7 each return 500 well formed, 0 inverted. 25.8 is unmeasured, its IcebergLocal did not create the fixture. The abort half is narrower: the assertion arrived in 26.8.


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

Version info

  • Merged into: 26.9.1.698 (included in 26.9 and later)
  • Backported to: 26.8.3.104

An Iceberg manifest can declare `lower_bounds[c]` above `upper_bounds[c]` for a
column, and nothing on the read side checked it.
`ManifestFileIterator::processRow` built a `DB::Range` straight from the decoded
pair, and `ManifestFilesPruner::canBePruned` passed both borders to
`mayBeTrueInRange` (`ManifestFilesPruning.cpp:186`), whose dense `checkInRange`
overload requires a lower border that does not exceed the upper one and asserts
it (`KeyCondition.cpp:5033`). An inverted pair describes an empty range, so every
atom evaluated false and the data file was dropped as `MIN_MAX_INDEX_PRUNED`: a
2000-row table returned 0 rows for `WHERE id < 500` where 500 is correct, while a
bare `count()` on the same table still returned 2000. Debug and sanitizer builds
aborted on the assertion instead. Reproduced on the 26.3, 26.5, 26.6, 26.7 and
26.8 release binaries.

The ordering is the caller's obligation, so the check goes where this caller
builds the range: on an inverted pair the column's bounds are dropped with a
warning instead of being pruned on. That is a state the consumer already handles,
since `hyperrectangles` is keyed by column id and `canBePruned` skips a column
with no entry (`ManifestFilesPruning.cpp:178-180`), so every other column's
min/max pruning and the separate partition-key path are untouched. Not fixed
inside `checkInRange`, because `KeyCondition` is not meant to be aware of
direction.

`accurateLess` rather than `Field::operator<`, since it is the predicate the
assertion itself applies through `KeyOrder::compareTuples`. The two agree on
every input reaching this line anyway: both bounds decode through
`deserializeFieldFromBinaryRepr` with the same type, so they always carry the
same type tag, and the reachable Iceberg column types are a closed, all-scalar
set.

Of the five `mayBeTrueInRange` call sites, the other four pass one pointer as
both borders, so the compared fields are identical and the precondition cannot be
violated there.

The regression test is an integration test because it has to rewrite an Avro
manifest out of band. It measures one four-data-file table twice through the same
query: 3 of 4 files pruned while the bounds are well formed, 0 pruned after
inverting them.

Closes ClickHouse#116499
For a Decimal column with a non-zero scale the decoder does not return the
bound as the manifest declares it. Iceberg stores decimal bounds rounded to
the integral part, so the decoder moves the lower bound one integral unit
down and the upper bound one integral unit up to keep the range a superset
of the file's contents.

The ordering check therefore has to run before that compensation. On the
compensated pair it only fires when the declared bounds are inverted by more
than two integral units, so a swapped Decimal(10, 2) pair with a spread of,
say, 1.50 came back as the ordered range [lower - 1, upper + 1] and still
pruned a file holding matching rows. That loss was silent in every build,
because the compensated pair satisfies the assertion in checkInRange.

The compensation itself is sound in isolation: on an ordered pair it only
ever widens the range, so it cannot over-prune. It turns unsound only on an
inverted pair, which is what this check now rejects. Re-decoding without it
costs two extra decodes for Decimal columns and none for any other type.

The regression test inverts one column at a time instead of exchanging the
whole bound maps, so a column that is still well formed in the same manifest
entry pins the fallback as per column rather than a manifest-wide loss of
min/max pruning.
The re-decode that reads Decimal bounds as the manifest declares them was
unpinned: deleting the whole isDecimal() block at the call site left every
assertion in the test green, so nothing would catch a later change that went
back to checking the compensated pair.

The new case is the one the compensation hides. Two data files, each with a
Decimal(10, 2) range spanning 1.50, which is less than the two integral units
the outward shift adds, so exchanging the declared bounds still yields an
ordered pair once shifted. With the block removed both files are pruned on
those manufactured ranges and the read returns no rows where one is correct;
with it in place nothing is pruned and the row comes back. A well-formed
control returns the same single row and prunes one file on either build, so the
check does not decline a sound pair, and the still well formed id column keeps
pruning after d is inverted, which pins the fallback as per column here too.

pyiceberg writes the table: getIcebergType has no Decimal case, so the
ClickHouse writer cannot create the column, and the compensation exists for
exactly these externally written bounds. The REST catalog rejects a file://
location, so the table lives in MinIO, and the manifest rewrite reaches it
through the MinIO client instead of the node's filesystem. That is the only
reason _swap_bounds_in_manifests now takes the metadata directory as an object
with list, get and put rather than a node and a path.

The literal in the filter is typed. A bare 0.25 is a Float64 and leaves a
Decimal column without a usable min/max condition, so nothing prunes at all and
every assertion holds whatever the bounds say.
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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex), 5 passes over 4 rounds, 9 findings. The last pass over the shipped tree and this description returned 0.

# Sev Finding Verdict Evidence / action
1 ❌ Decimal bounds are compared only after the outward shift, so an inversion narrower than two integral units is missed AGREE, fixed @ b1a8d60 Bounds are now decoded a second time without the shift and both pairs are tested. A swapped Decimal(10, 2) pair spread 1.50 apart is the carrier
2 ⚠️ The test cannot tell a per column fallback from losing manifest min/max pruning wholesale AGREE, fixed @ b1a8d60 Each arm now inverts one column and asserts a well formed sibling still prunes. Mutant hyperrectangles.clear(); break; fails that arm
3 ⚠️ The test never exercises the Decimal path that fixed finding 1 AGREE, fixed @ 3afe9bc Added a pyiceberg written Decimal table, since the ClickHouse writer rejects Decimal. Mutant deleting the re-decode fails it on wrong rows
4 💡 The visible closing relationship used a short reference, not a full URL AGREE, fixed @ 3afe9bc Visible Closes: line now carries the full URL
5 ❌ The shift can also invert a pair that is ordered as declared, and that pair is the one used AGREE, fixed @ a19442f Added || accurateLess(*right, *left). A Decimal(9, 1) bound outside its declared precision leaves Int32 at the closing cast. Mutant deleting only that clause fails the new arm on the compareTuples assertion
6 💡 The null check on the re-decode is unreachable AGREE, fixed @ a19442f Deleted. Both nullopt returns depend only on the type, so the existing check above already covers them
7 ❌ For a Decimal64 bound near INT64_MAX the shift overflows before either pair is checked, which is fatal under UBSan DISAGREE Conceded as reachable and as undefined behaviour, but it is not this change. unscaled_value += scaler and the call reaching it are byte identical to master, and the two calls added here pass compensate_rounding=false, which skips that statement outright, so nothing here creates or widens it. The suggested remedies were to duplicate #114962 in the same hunk, to block on it, or to add a regression that aborts UBSan both before and after this fix. Disclosed in the description instead
8 💡 The warning blames declared ordering even when only the shifted pair is inverted AGREE, noted, not blocking Correct, and my own new arm is that case. Log text only, no behaviour change, so I did not spend a round on it. Happy to reword on request
9 💡 No visible relationship line for the related PR AGREE, fixed Added Related: with the full URL, since the two changes share one edited line and the merge order matters

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-48:20260826-205700

@clickhouse-gh clickhouse-gh Bot closed this Aug 26, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f39f34f]

Summary: ✅


AI Review

Summary

This PR hardens Iceberg min/max pruning against inverted or unreadable manifest bounds and adds focused local and S3 regressions for the ordinary column path. The main bug is fixed there, but the merged tree still has one unprotected sibling path for materialized row-lineage statistics, so the malformed-manifest contract is not yet satisfied end to end.

Findings

❌ Blockers

  • [src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp:555-570] The new drop-on-inverted-bounds logic only covers the ordinary per-column loop. In the merged tree, materialized _row_id / _last_updated_sequence_number bounds still go through getMaterializedRowLineageRange and build Range(*left, *right) with no ordering check before mayBeTrueInRange, so a manifest that inverts field ids 2147483540 or 2147483539 can still over-prune or hit the same assertion this PR is fixing here.
    Suggested fix: route the row-lineage bounds through the same accurateLess and drop-with-warning handling, and add a focused regression under test_row_lineage_pruning.py that corrupts those materialized bounds.
Final Verdict

❌ Changes requested.

LLVM Coverage Report

Measured on commit f39f34f.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 41/47 (87.23%) · 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 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @arsenmuk, could you review this? An Iceberg manifest that declares a lower bound above the upper bound reaches mayBeTrueInRange as an empty range, so min/max pruning drops the data file that holds the matching rows. For Decimal the outward rounding compensation can both hide and create such an inversion, so the check tests the pair as declared and the compensated pair that is actually used.

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f39f34f60 with master e903c5a56 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

3 object files changed (+17.38 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp.o 325.00 KiB 342.38 KiB +17.38 KiB (+5.35%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a19442f

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be posted here when it opens.

GitHub dispatched two PR workflow runs for this single commit. Run 33019110286 passed all 174 jobs; both reds below come from run 33019120752. Same tree, opposite verdicts. My diff is ManifestFileIterator.cpp plus one integration test, and touches nothing under src/Parsers/ or src/Storages/MergeTree/Streaming/.

Check / test Reason Owner / fixing PR
Stress test (arm_debug) / Inconsistent AST formatting (STID 1941-26fa) trunk regression: for CREATE TABLE ... AS <table function> a table-level PRIMARY KEY tuple(col) is emitted in a position the parser cannot read back. 17 distinct PRs carry it since #114171 merged at 21:00:05Z; across the preceding 45 days the only 3 rows sit on that PR's own branch, and none on this one a fix task is created (investigating at full effort, fixing PR link to follow on this PR)
Stress test (arm_asan_ubsan, s3) / The metadata stream of AlignStreams ended before all data stream rows were matched (STID 0250-329b) trunk regression from merged #116128: read limits on a streaming query break stream alignment. 5 distinct PRs in 45 days, 0 rows on master, onset 2026-08-26 15:59:30Z #116531 (external, open)

Session id: cron:our-pr-ci-monitor:20260827-033000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_debug) Inconsistent AST formatting red (STID 1941-26fa) in my CI finish ledger above: #116645

@PedroTadim PedroTadim self-assigned this Aug 27, 2026
PedroTadim and others added 2 commits August 28, 2026 11:10
…verted-manifest-bounds

# Conflicts:
#	src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp
Iceberg stores decimal min/max bounds rounded to the integral part, so the reader
moves them one integral unit outwards before pruning on them. The bound arrives as
raw bytes and is never checked against the column's declared precision, so that
shift can leave the type: for a `Decimal(9, 1)` column the upper bound `0x7ffffffa`
is 2147483642, and 2147483642 + 10 is not representable in `Int32`.

Since ClickHouse#115832 the accumulation happens in the decimal's own native type, so the
shift is signed integer overflow and UBSan halts the server:

  ManifestFileIterator.cpp:99:28: runtime error: signed integer overflow:
  2147483642 + 10 cannot be represented in type 'NativeType' (aka 'int')

A build without UBSan wraps to -2147483644 instead, which inverts the pair that
reaches `mayBeTrueInRange` and trips its
`key_order.compareTuples(left_keys, right_keys, used_key_size) <= 0` assertion.
Reject the bound instead: `processRow` already skips min/max pruning for a column
whose bounds do not decode, which is the conservative answer.

A conforming value has the headroom at three of the four widths: the unscaled value
is capped at 10^P - 1 and the scaler is 10^S, and their sum stays inside `Int32`,
`Int64` and `Int256`. `Decimal(38, 38)` is the exception, since the shift there needs
about 2 * 10^38 while `Int128` holds 1.7 * 10^38, so a bound above roughly 0.7 is
rejected whether it conforms or not. That costs min/max pruning for such a column,
where the same input overflows today.

The ordering check now runs on the values as declared only. Before ClickHouse#115832 the
accumulation was `Int64` and the value was narrowed with a cast, so the shift
wrapped rather than overflowed and the wrapped pair could come back inverted. With
the shift rejected on overflow, a declared lower bound at or below the upper one
can no longer invert once shifted, so the second comparison had no carrier left.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Integration tests (amd_asan_ubsan, flaky) on 0288a37e was not flaky. The job runs pytest -n 3 --dist=each, and the decimal function failed on all three workers while the sibling function passed on all three. Each worker's node1 stderr.log holds exactly one report:

ManifestFileIterator.cpp:99:28: runtime error: signed integer overflow:
2147483642 + 10 cannot be represented in type 'NativeType' (aka 'int')

UBSan halts the server there, which is what reaches the client as ATTEMPT_TO_READ_AFTER_EOF. Line 99 is the outward shift in deserializeDecimalBound, reached from the pre-existing decode in processRow. The same test passed at a19442f0 on this build flavour (8 CIDB rows, 0 failures); #115832 then moved the accumulation from int64_t plus a closing cast to the decimal's own native type, so a shift that wrapped became overflow. 2147483642 is the upper bound the e arm writes.

67821f6b rejects a bound that cannot be widened inside its type, so the column takes the decode-failure path the caller already has and nothing prunes on it. The comparison against the shifted pair went with it: with the overflow rejected, a declared lower bound at or below the upper one can no longer come back inverted. On a debug build both functions pass, and restoring the unchecked unscaled_value += scaler alone fails the decimal arm on Logical error: 'key_order.compareTuples(left_keys, right_keys, used_key_size) <= 0' while the sibling still passes.

#114962 fixes the same overflow, but its diff is against the pre-#115832 decoder and rejects anything wider than Decimal64, which #115832 just added bound support for.

/// To handle this issue we subtract 1 from the integral part for lower_bound and add 1 to integral
/// part of upper_bound. This produces: 17.22 -> [16.0, 18.0]. So this is more rough boundary,
/// but at least it doesn't lead to incorrect results.
/// `compensate_rounding` widens the bound as described above; pass false to read the value exactly

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.

🕵️ @groeneai

The compensate_rounding parameter is load-bearing, but the comment above the check doesn't say why, and as written it argues for the opposite.

The widening is monotone outwards, so it can never invert a valid pair — but it can un-invert an inverted one. At scale = 1:

declared:  lower = 15 (1.5), upper = 14 (1.4)      -> inverted
widened:   lower = 15-10 = 5 (0.5), upper = 14+10 = 24 (2.4)  -> not inverted

So any inverted pair whose gap is under 2 * 10^scale is masked, and testing left/right would miss exactly the corruption this PR exists to catch. That's the reason for the second read with compensate_rounding = false.

But the comment says the check is needed because "mayBeTrueInRange requires a lower bound that does not exceed the upper one" and "an inverted pair describes an empty range". In the masked case the widened pair satisfies that precondition fine — Range(0.5, true, 2.4, true) is well-formed and non-empty — so on its own terms the comment doesn't explain why the declared values are the ones being tested. The actual reason is that an inverted declared pair means the manifest's statistics are untrustworthy, so any range derived from them is unsafe to prune on, which is also why continue is right rather than swapping or clamping. Could you reword it that way? As it stands someone could reasonably "simplify" this later by dropping the second deserialization, and reintroduce the masking.

Two smaller things:

The arithmetic alternative (widened_right < widened_left + 2 * 10^scale) would avoid the second parse, but I'd keep what you have — it needs scale-aware arithmetic at the comparison site with its own overflow exposure, which is what the new addOverflow guard is there to avoid.

The new overflow guard means a bound that can't be widened returns nullopt and gets dropped by the earlier if (!left || !right) continue; without a warning, while an inverted bound logs one. Both indicate a malformed manifest; worth logging the overflow case too so it isn't silently indistinguishable from an absent bound.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reworded both comments, and the overflow drop is logged now.

1. You are right that the mayBeTrueInRange precondition argues for testing the widened pair. Rewritten in two places, since the second deserialization is what a later reader would drop: at the re-read, the outward shift un-inverts any declared pair no more than 2 * 10^scale apart, so only the declared values expose the inversion; at the check, an inversion there means the manifest's statistics are untrustworthy, so no range derived from them is safe to prune on, which is why it drops the bounds rather than swapping or clamping. e69e317

The masking is pinned by a test too, not only by the comment: deleting the second deserialization fails test_iceberg_inverted_decimal_manifest_bounds on the results-equality assertion at helpers/iceberg_utils.py:618, since its d column inverts by 1.50 at scale 2 and the widened pair then prunes the file holding the matching rows. The non-decimal sibling still passes.

2. Agreed, left as is.

3. Added, but at debug level, and one correction to the premise: the two cases are not both malformed manifests. Iceberg stores a decimal bound rounded to the integral part, so a Decimal(38, 38) file whose maximum rounds to 1 stores unscaled 10^38, and the shift takes that past Int128. Such a column is conforming, and every filtered query over it reaches the branch once per data file, so a warning would be both wrong and repeated. Debug keeps it out of the warning log and still visible to anyone chasing lost pruning. On the regression test the new line appears 4 times at <Debug>, only for the out-of-precision column, while the inverted pair stays at <Warning> for the two swapped columns. 595b41a

That narrows one promise in the description: an inverted Decimal(38, 38) pair whose upper bound also overflows returns nothing at the earlier decode, so it reaches the debug branch before the ordering check and is not warned. Checking declared ordering first would reorder this loop, which I kept out. The description now says a warning follows unless the shift already made a bound unreadable.

Also dropped a stale docstring line claiming the ClickHouse writer rejects Decimal. f39f34f

The branch is at 11 commits; the in-tree rule is to add commits rather than rewrite, so I have not squashed. Say the word if you want them collapsed.

…trustworthy

The ordering check ran on the values as declared, but its comment justified that by
mayBeTrueInRange needing a lower bound at or below the upper one. The widened pair meets
that precondition even when the declared pair is inverted, so the comment did not say why
the declared values are the ones tested, and read as an argument for testing the widened
pair instead.

Both comments now state the reasons. Undoing Iceberg's rounding moves each bound one
integral unit outwards at a non-zero scale, so it un-inverts any declared pair no more
than 2 * 10^scale apart: at scale 1, declared 15 and 14 widen to 5 and 24. Only the
declared values expose such an inversion, which is why they are read again. An inversion
there means the manifest's statistics are untrustworthy, so dropping the column's bounds
is right where swapping or clamping them would prune on a value nothing vouches for.

Comments only, no behaviour change. Dropping the second deserialization already fails
test_iceberg_inverted_decimal_manifest_bounds on the results-equality assertion, since
its d column inverts by 1.50 at scale 2 and the widened pair prunes the file holding the
matching rows.
… type

A decimal bound whose declared bytes have no value in the column's type returns nullopt
and the caller drops that column's min/max condition, so far without a word in the log,
while an inverted bound already warned. That made a malformed manifest indistinguishable
from a data file that simply carries no statistics for the column.

Warn there too, naming the manifest, the column id and the data file as the inverted-bound
warning does. Both paths lose min/max pruning for the column and nothing else changes.
…t is malformed

The previous commit called every rejected bound a malformed manifest. That is wrong for
one type: a Decimal(38, 38) value above roughly 0.7014 conforms to the declared precision,
yet the one-integral-unit outward shift leaves Int128, so a conforming bound is rejected
too. Of all 3002 legal (precision, scale) decimal pairs it is the only one where that can
happen; for the other 3001 an overflow does prove the declared value is outside the
column's own precision.

The comment and the warning now say the bound cannot be read as a usable range border,
which holds for all three ways the read returns nothing: bytes wider than the native type,
empty bytes, and no widened form inside the type. Wording only.
Iceberg stores a decimal bound rounded to the integral part, so a Decimal(38, 38) file
whose maximum rounds to 1 stores unscaled 10^38, and the one-integral-unit outward shift
takes that to 2 * 10^38, past the Int128 limit. Such a column is conforming, and every
filtered query over it reaches this branch once per data file, so a warning there would be
both wrong and repeated.

Debug level keeps the drop out of the warning log while leaving it visible to anyone
looking into lost pruning. An inverted pair is a malformed manifest whatever the type, so
that one stays a warning.
The docstring said pyiceberg writes the fixture because the ClickHouse Iceberg writer
rejects Decimal. It does not: Utils.cpp maps all four Decimal widths to an Iceberg decimal
type, and test_storage_iceberg_with_spark/test_writes.py already writes Decimal columns
and prunes on their statistics. The docstring now states only what the fixture does.

Whether a ClickHouse-written local table could replace the pyiceberg and MinIO machinery
here is a separate question; nothing about the two columns or the assertions changes.
/// A pair inverted as declared means the manifest's statistics are untrustworthy, so no
/// range derived from them is safe to prune on. Dropping the column's bounds is therefore
/// right where swapping or clamping them would prune on a value nothing vouches for.
if (accurateLess(*declared_right, *declared_left))

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.

The new accurateLess guard only protects the ordinary per-column loop. In the merged tree, materialized row-lineage statistics (_row_id / _last_updated_sequence_number) still read the same manifest lower_bounds / upper_bounds through getMaterializedRowLineageRange and build Range(*left, *right) without checking that the declared lower bound does not exceed the upper one before mayBeTrueInRange sees it.

That means a corrupted v3 manifest that swaps field id 2147483540 or 2147483539 can still over-prune or trip the same compareTuples assertion this PR is fixing here. Please apply the same drop-with-warning handling to the row-lineage path and add a focused regression in test_row_lineage_pruning.py that corrupts those materialized bounds.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Correct, including the test file name, and it is master's code rather than this branch's.

Measured on origin/master: getMaterializedRowLineageRange (ManifestFileIterator.cpp:143) returns DB::Range(*left, true, *right, true) at :165 with no ordering check, :205 puts it into hyperrectangles, and ManifestFilesPruning.cpp:286 hands it to mayBeTrueInRange, whose body is one call to checkInRange, whose first statement is the chassert(key_order.compareTuples(...) <= 0) at KeyCondition.cpp:5033. Nothing filters it on the way: the reserved ids skip the schema lookup through row_lineage_columns (:80-84, :161) and has_no_nulls stays true for them (:262, :266). WHERE _row_id < N is supported, so the inverted bound is the only adversarial ingredient. Same severity as the defect this PR closes.

Where the guard lands is the disagreement. This branch forked at fd57f120feb37ae (2026-08-28T09:58Z) and row lineage landed on master with #115603 at 20:26Z the same day, so neither that function nor test_row_lineage_pruning.py exists here and the branch is 2972 commits behind. Nor can the existing guard be pushed down to cover it: an inversion is a property of the pair, so it cannot live in deserializeFieldFromBinaryRepr, which sees one border at a time. Both call sites need a shared pair-level helper, and that only compiles on a tree that has both.

Master has no ordering check in that file today and I found no open pull request adding one, so this is not already covered.

I have recorded it in the description as a residual rather than merge 2972 commits into a p0 that is under review. If a reviewer would rather have it in this pull request, say so and I will do that instead.

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed, and the scope is bounded. The added work is at manifest-read time, once per data file entry per column that declares both bounds, not per row. For a decimal column the bound decode count goes from 2 to 4, because the declared pair is read again with compensate_rounding=false; those two extra reads take the cheaper path, skipping the scaler loop and the addOverflow check. Every other bounded column pays two Field copies and one accurateLess, no extra decode. I have not benchmarked it.

If you want that cost back, it is one line: deserializeFieldFromBinaryRepr calls non_nullable_type->createColumn() before the type branch, and only the non-decimal branch touches the result, so on the decimal path it is a new ColumnDecimal per call, constructed and discarded. Moving the construction into the branch that uses it takes the decimal path from 2 column allocations before this change, and 4 after, to 0. Say the word and I will do that here with a test run; otherwise I will leave the pull request as it stands, since it is approved.

@PedroTadim

Copy link
Copy Markdown
Member

@scanhex12 we can keep as it is

@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 4, 2026
Merged via the queue into ClickHouse:master with commit 35a0d6f Sep 4, 2026
175 checks passed
@zlareb1

zlareb1 commented Sep 4, 2026

Copy link
Copy Markdown
Member

TL;DR: The new inverted-bounds check has a third sibling site in the same file that it does not cover: the row-lineage reserved-field ranges.

getMaterializedRowLineageRange (ManifestFileIterator.cpp:152-175) builds Range(*left, true, *right, true) for _row_id / _last_updated_sequence_number directly from the stored value_bounds with no inversion check, and addRowLineageHyperrectangles injects those into the same hyperrectangles map consumed by ManifestFilesPruner::canBePruned. The main loop's new guards never see these entries because the reserved field ids fail the schema lookup and continue before the checks.

So a manifest declaring inverted materialized _row_id bounds (e.g. [100, 50]) makes mayBeTrueInRange false for every point inside the true range, and a query filtering on _row_id silently loses the file — the same untrustworthy-statistics shape this PR fixed for schema columns. The unreadable-bound case is already safe here (nullopt falls through to the conservative inherited range); only the inverted case slips through.

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

@zlareb1 Confirmed. Measured at master 323d4264:

  • getMaterializedRowLineageRange returns Range(*left, true, *right, true) at ManifestFileIterator.cpp:175, and there is no ordering check anywhere in the body.
  • addRowLineageHyperrectangles puts it into hyperrectangles at :215, which is the map canBePruned consumes at :692. In ManifestFilesPruning.cpp the reserved ids take their name and type from row_lineage_columns at :264-267 and has_no_nulls keeps its initial true from :262, so the range reaches mayBeTrueInRange at :286 unfiltered. An inverted pair therefore trips the same checkInRange assertion as Iceberg: a manifest whose lower_bounds exceed its upper_bounds trips a chassert in KeyCondition (aborts debug builds; silently drops rows on release) #116499 in a debug build, and over-prunes in release.
  • The merged guard sits at :673, inside the loop over value_bounds, which continues at :625 when the schema lookup misses.

One thing to add to your mechanism: the outcome does not actually depend on that lookup missing. hyperrectangles is filled with emplace, which does not overwrite an existing key, so on the branch where the lookup resolves and the guard drops the column at :682, the key is still free and :215 installs the unchecked range anyway. The check has to live where the row-lineage range is built rather than in the main loop, which is also why the merged guard could not simply be widened.

What I have not done: I have not yet built a v3 manifest that declares materialized inverted _row_id bounds, so the consequence above is read out of the source and not observed. The follow-up carries that arm, extending the manifest-rewriting harness the merged test already uses.

The merged pull request cannot be edited, so the fix goes in a separate one. I will open it and link it here.

On scope, this is a third and distinct site. #118113 is the position-delete file_path bounds in IcebergIterator.cpp and I am already working on that one. I will keep the two separate unless a reviewer would rather have one change covering every site.

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

@zlareb1 Opened as #118299, as promised.

The arm I said I had not built exists now, so that hedge is discharged: on a Spark-written format-version 3 table whose manifest declares [100, 50] for reserved id 2147483540, removing the guard aborts on the checkInRange assertion. The release over-pruning is still a deduction from chassert compiling to (void)sizeof(!(x)), not something I ran.

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Sep 9, 2026
A filter on `_row_id` or `_last_updated_sequence_number` over a format-version 3
table is answered from the manifest, by handing `KeyCondition` the range of row
lineage values a data file can hold. Two writer-declared inputs can make that
range start above where it ends, and neither was checked:

- `getMaterializedRowLineageRange` built `DB::Range` straight from the
  `value_bounds` pair declared for the reserved field id, so a manifest that
  declares a lower bound above the upper bound produced an empty range.
- `addRowLineageHyperrectangles` derived a file's inherited block as
  `first_row_id + record_count - 1`. `first_row_id` is a signed long on the wire
  and unsigned in the reader, so a negative value made the sum wrap and the
  block end below its own start.

An empty range prunes the data file away, so a filtered read silently loses
every row it holds, and the `chassert` in `KeyCondition::checkInRange` aborts the
server in debug and sanitizer builds.

Both cases now drop the untrustworthy bounds. A pair inverted as declared means
the manifest's statistics do not describe the file, so no range derived from them
may be pruned on; swapping or clamping the pair would instead prune on a range
the manifest never asserted, which is the same reasoning the guard for ordinary
columns already uses. The declared-pair case returns no range and lands on the
existing conservative fallback, `[0, last inherited row id]`, which holds for
both reserved ids: a materialized value always comes from an earlier write, so it
is below this file's own block. The wrapped-block case cannot use that fallback,
because the wrapped value IS the fallback's upper bound, so it installs no row
lineage range at all.

Re-reading the bounds with rounding compensation, as the ordinary-column path
does, is not needed here: the type is `DataTypeUInt64`, which takes the
non-decimal branch of `deserializeFieldFromBinaryRepr` where that flag is unused,
so the deserialized values are the declared ones.

Tested by two integration arms that patch a Spark-written v3 table's avro
metadata: one declares an inverted `_row_id` pair, the other a negative
`first_row_id`. Each arm reddens when its own check is removed.

Reported by @ zlareb1 on pull request ClickHouse#116604, which fixed the same defect class
for ordinary columns, and again on ClickHouse#118181, which fixes it for position delete
file paths.

Related: ClickHouse#116499
Related: ClickHouse#116604
scanhex12 added a commit that referenced this pull request Sep 11, 2026
…it is

An Iceberg partition field summary keeps its bounds in the single-value
serialization of the partition field's own type, and for the `day`, `month`,
`year` and `hour` transforms that type is a signed `int` counting units from
1970. ClickHouse models those transforms in the partition key with
`toRelativeDayNum`, `toMonthNumSinceEpoch`, `toYearNumSinceEpoch` and
`toRelativeHourNum`, whose result types are unsigned, so
`ManifestListPruner::canBePruned` read a bound from before 1970 as a huge
unsigned number. For a manifest that spans 1969 and 2024 the lower bound then
came out above the upper bound, and `KeyCondition::checkInRange` hit
`chassert(key_order.compareTuples(left_keys, right_keys, used_key_size) <= 0)`,
which aborts a build with assertions.

That is why
`test_storage_iceberg_with_spark/test_partition_pruning_with_functions.py::test_partition_pruning_with_functions_before_epoch`
started failing on master in `Integration tests (amd_tsan, 3/6)` and
`Integration tests (amd_msan, 8/8)`: the `toDate32` monotonicity that
#118606 gave a `Nullable` column
made the filter of that test reach the pruner.

A bound of an unsigned key column is now read as the signed number Iceberg
wrote, and a negative one leaves the whole field unknown: the ClickHouse
functions that stand for those transforms cannot return a negative number -
they map every point before 1970 to zero - so nothing about the key's value
space follows from such a bound and no range of it may be pruned on.

A pair of bounds that comes out inverted now drops the field with a warning
instead of being pruned on, the same as `ManifestFileIterator` already does
for the min/max bounds of a data file.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=290309210c5b2f0e01c13fd0fbae6577fb5cb9cd&name_0=MasterCI&name_1=Integration%20tests%20%28amd_tsan%2C%203%2F6%29

Related: #118606
Related: #116499
Related: #116604

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@robot-ch-test-poll3 robot-ch-test-poll3 added pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Sep 13, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 13, 2026
Backport #116604 to 26.8: Do not prune Iceberg data files on inverted manifest bounds
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Sep 28, 2026
Iceberg stores a decimal min/max bound rounded to the integral part, so the reader moves each
bound one integral unit outwards before pruning on it. At scale 38 that unit is `10^38` and the
bound lives in an `Int128`, which holds `1.7 * 10^38`, so the shift leaves the type for every
bound of magnitude above roughly 0.70141. `Decimal(38, 38)` is the only width where that happens
to a bound the column can hold: at the other three the largest value the precision allows plus
`10^scale` still fits.

Until ClickHouse#116604 the shift wrapped, which inverted the pair reaching
`KeyCondition::mayBeTrueInRange`, pruned the data file holding the matching rows and lost them
silently. That pull request rejects such a bound instead, which is correct but gives the column
no min/max condition at all - and for a `Decimal(38, 38)` column that is every bound of
magnitude above 0.7, so those tables lost min/max pruning altogether.

A bound only has to stay on the outer side of every value in the file, and the largest magnitude
the precision of the type allows is outside all of them, so it stands in for a widened bound that
no longer fits. A bound that is itself outside that magnitude is one the column cannot hold:
nothing vouches for the values in the file, so there is no stand-in for it and it stays unusable,
which is the case `test_iceberg_inverted_decimal_manifest_bounds` pins for a `Decimal32` bound.

The new test reads a `Decimal(38, 38)` column whose two data files hold `0.99` and `-0.99`: every
filter on the column returns its rows, and a probe outside one of the two shifted bounds prunes
that file and only it. A second table holds `0.1` and `-0.1`, where the shift stays inside
`Int128` whatever the reader does with an overflow, so the two arms together say the pruning is
lost to the overflow rather than to the shape of the test.

Closes: ClickHouse#116999
Related: ClickHouse#116604
Related: ClickHouse#115832

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
ringerc pushed a commit to ringerc/ClickHouse-patches that referenced this pull request Nov 9, 2026
Iceberg float lower_bounds/upper_bounds exclude NaN by spec, and NaN
presence is recorded only in the optional nan_value_counts (field 137).
ClickHouse never read that field, and the manifest pruner evaluated a
plain KeyCondition over the bounds as if they covered every value. A
hidden NaN satisfies no ordering comparison, so it makes a negated atom
true (`!=`, `NOT (x < 10)`, `NOT IN`) and a monotonic chain can map it
anywhere (`round(x) != 3`): such predicates pruned a data file holding
the NaN and its rows were lost. Reproduced on 26.3.42.3, 26.8.18.2,
26.9.16.11 and master with a pyiceberg-written file `x = [3, NaN, 3]`:
`WHERE x != 3` returned 0 with pruning on and 1 with it off.

Parse nan_value_counts into ColumnInfo. For a column whose type may hide
a NaN, the pruner also builds a copy of the min/max condition relaxed by
KeyCondition::relaxAtomsOverNaNHidingColumns, the mechanism MergeTree
minmax, skip indexes and the statistics pruner already use for
NaN-excluding bounds, and uses it unless the data file's
nan_value_counts for the column is 0 (Iceberg Java's mayContainNaN).
Positive comparisons keep pruning.

The inverted-bounds check from ClickHouse#116604 orders NaN last, so `(NaN, 5)` is
already dropped as inverted, but an upper NaN bound (`(5, NaN)`,
`(NaN, NaN)`, which Iceberg Java's ORC metrics report when a file's
first value is NaN) passed and pruned on `x = 3`. Drop a column's bounds
when either endpoint is NaN.

OPTIMIZE TABLE ... MANIFEST copies the source entries' statistics
verbatim; carry nan_value_counts over as well, otherwise compaction would
demote every column of a table written by Iceberg Java to the relaxed
condition.

Closes ClickHouse#118112

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Iceberg: a manifest whose lower_bounds exceed its upper_bounds trips a chassert in KeyCondition (aborts debug builds; silently drops rows on release)

7 participants