Repository navigation
Do not prune Iceberg data files on inverted manifest bounds - #116604
PedroTadim merged 11 commits into
Conversation
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.
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.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-48:20260826-205700 |
|
Workflow [PR], commit [f39f34f] Summary: ✅
AI ReviewSummaryThis 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
Final Verdict❌ Changes requested. LLVM Coverage ReportMeasured on commit f39f34f.
Changed lines: Changed C/C++ lines covered: 41/47 (87.23%) · Uncovered code |
|
cc @scanhex12 @arsenmuk, could you review this? An Iceberg manifest that declares a lower bound above the upper bound reaches |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes3 object files changed (+17.38 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7 translation units recompiled, 12 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - a19442fEvery 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
Session id: cron:our-pr-ci-monitor:20260827-033000 |
|
Fixing PR for the |
…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.
|
UBSan halts the server there, which is what reaches the client as
#114962 fixes the same overflow, but its diff is against the pre-#115832 decoder and rejects anything wider than |
| /// 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 |
There was a problem hiding this comment.
🕵️ @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.
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
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 If you want that cost back, it is one line: |
|
@scanhex12 we can keep as it is |
|
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.
So a manifest declaring inverted materialized |
|
@zlareb1 Confirmed. Measured at master
One thing to add to your mechanism: the outcome does not actually depend on that lookup missing. What I have not done: I have not yet built a v3 manifest that declares materialized inverted 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 |
|
@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 |
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
…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]>
Backport #116604 to 26.8: Do not prune Iceberg data files on inverted manifest bounds
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]>
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]>
Changelog category (leave one):
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]aboveupper_bounds[c], and nothing checks it.canBePrunedhands both decoded borders tomayBeTrueInRange, which requires a lower border not exceeding the upper one. An inverted pair is an empty range, so the file is dropped asMIN_MAX_INDEX_PRUNED:WHERE id < 500returns 0 where 500 is correct, a barecount()returns 2000. Debug and sanitizer builds abort on thechassertopeningcheckInRange.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:
canBePrunedskips a column with nohyperrectanglesentry, and of the fivemayBeTrueInRangecallers only this one passes distinct borders.The check reads the values as declared: Iceberg rounds
Decimalbounds 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 + 10for aDecimal(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. OnlyDecimal(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;checkInHyperrectangletakes Parquet and Hive statistics equally unchecked; master's newergetMaterializedRowLineageRangereads 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.pyicebergwrites theDecimaltable, since the ClickHouse writer rejects it.(id Int64, s String)well formedidprunes 3,sprunes 3idonlyidprunes 0,sstill prunes 3stoo(id, d Decimal(10, 2), e Decimal(9, 1))well formeddonlydprunes 0,idstill prunes 1ebound at the edge ofInt32eprunes 0,idstill prunes 1Both functions pass at this revision. Earlier: 8 passed in one run including all 6 parametrizations of
test_writes_statistics_by_minmax_pruning.pyat their exact counts, whose tables come from single-row inserts, solower == uppereverywhere 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 thecontinuefails thesarm; deleting the declared re-decode fails thedarm on wrong rows; restoring the uncheckedunscaled_value += scalerfails theearm on thecompareTuplesabort.Release binaries,
WHERE id < 500on 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, itsIcebergLocaldid 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
26.9.1.698(included in26.9and later)26.8.3.104