Repository navigation
Do not prune Iceberg data files on inverted row lineage bounds - #118299
PedroTadim merged 4 commits into
Conversation
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
…ling guard The comment added with the guard restated, almost word for word, the paragraph already standing at the guard for ordinary columns twenty lines below. Duplicating it says nothing new and leaves two paragraphs to keep in step. It now refers to that reasoning instead, and spends its lines on what is specific to this site and stated nowhere else: returning no range here lands on the caller's fallback, which bounds every value the file can hold.
The two arms added for the inverted-pair and wrapped-block cases both expect the conservative fallback range, so both of them also pass in a build where `getMaterializedRowLineageRange` stops handing back a range at all. Neither arm, and no other test in the file, would notice a fix that simply gave up on materialized bounds: the four recorded mutants prove each guard is needed for its own arm, which is a different property. `test_materialized_row_ids_are_not_pruned_away` already builds the only fixture in the suite that reaches the materialized branch. Its copy-on-write rewrite holds row ids 0..3 while its manifest entry advertises the fresh block 4..7, and Spark declares a truthful pair plus a zero null count for the reserved id, so those bounds really are read. Asserting the exact skipped-file count for `WHERE _row_id >= 4` closes the missing direction, because 1 is reachable only by using the declared pair: the fallback range `[0, 7]` overlaps that filter and gives 0, and so would pruning on the advertised block. Measured with the tail `return` of that function replaced by `std::nullopt`: the new assertion fails `0 == 1` while both arms stay green.
Internal second-model reviewAn independent model reviewed this branch cold across two rounds and I adjudicated its findings against the code. The second round came back clean. ❌ Fixed: both test arms were also green in a build where 💡 Noted, not changed: an unrepresentable row id block also suppresses the 💡 Noted, not changed: the avro rewrite helper in the test is a private copy. Five modules in this package already carry one, and the nearest existing copy works through the container rather than on the filesystem Spark writes to, so it is not reusable here. |
|
Workflow [PR], commit [c329532] Summary: ✅
AI ReviewSummaryThis PR hardens Iceberg row-lineage pruning against two malformed-manifest cases: inverted materialized bounds for Findings❌ Blockers
Final Verdict❌ Changes requested. I would not merge until the short-bound decoder hole on the row-lineage path is closed as well. LLVM Coverage ReportMeasured on commit c329532.
Changed lines: Changed C/C++ lines covered: 31/32 (96.88%) · Uncovered code |
|
cc @scanhex12 @arsenmuk, could you review this? It is the row lineage half of the inverted-bounds guard in #116604: a manifest that declares an inverted pair for the reserved |
| /// An inverted pair is dropped rather than repaired, for the reason spelled out at the guard for | ||
| /// ordinary columns below. Returning nothing here leaves the caller's fallback range, which | ||
| /// bounds every value the file can hold, a materialized one from an earlier write included. | ||
| if (accurateLess(*right, *left)) |
There was a problem hiding this comment.
getMaterializedRowLineageRange now drops inverted pairs, but the malformed-input hole immediately above it is still open: left_str / right_str can be any byte length, and for DataTypeUInt64 deserializeFieldFromBinaryRepr goes through ColumnUInt64::insertData, which ignores length and unconditionally unalignedLoad<UInt64>(pos). A manifest that encodes _row_id or _last_updated_sequence_number bounds in 1..7 bytes therefore makes pruning depend on bytes past the serialized Avro value, and MSan will flag it. Please reject any non-8-byte row-lineage bound before calling the generic decoder, or harden deserializeFieldFromBinaryRepr for fixed-width numerics so short values return std::nullopt.
There was a problem hiding this comment.
Confirmed, and real, but pre-existing and one function wider than this change, so I am not folding it in here.
Mechanism checked rather than taken on the reading. ColumnVector<T>::insertData(const char * pos, size_t) leaves the length parameter unnamed and does unalignedLoad<T>(pos) (src/Columns/ColumnVector.h:85-88), which is memcpy(&res, address, sizeof(res)) (base/base/unaligned.h:9-14). The bound arrives as a String that Field::operator=(std::string_view) builds from a pointer and a length (src/Core/Field.h:829-838) inside union storage that is deliberately left un-zeroed (:563), so for a bound shorter than the column width the trailing bytes of the short-string buffer are never written. Running that exact chain against this tree's own libc++ and clang, a 3-byte bound decoded to 100 on one run and to 3348558689547059300 on the next, so the value is indeterminate. I have not run an MSan build, but that is the shape MSan reports. The read stays inside the string object in both representations (short capacity is 22, a long string is at least 23 bytes), so this is an uninitialized value and not an out-of-bounds access.
Three reasons it belongs in its own change:
deserializeFieldFromBinaryRepris untouched here and has six call sites: the two row lineage ones plus:664,:665,:688and:690. Guarding only the row lineage pair leaves the identical hole one function away for everyint,long,float,double,date,time,timestampanduuidbound.- Release presence differs.
getMaterializedRowLineageRangeis absent fromv26.9.1.1-new,v26.8.2.7-lts,v26.7.6.57-stable,v26.6.4.55-stableandv26.3.30.9-lts, which is why this pull request isNot for changelog.insertData(str.data(), str.length())is present at all five, so the decoder fix is a stable-release bug fix and a backport candidate. One pull request cannot file both categories honestly. - Rejecting every bound whose length is not the column width would regress reads. All five of those tags still write 8 bytes for 4-byte
int,DateandDate32bounds (dumpValue(field.safeGet<Int32>())is present at each, and absent only on master, since the writer fix Fix the byte width of Iceberg manifest bounds forintanddatecolumns #117571 landed after every active tag), and Iceberg: manifest bounds forintanddatecolumns are written as 8 bytes (spec: 4) — every filtered pyiceberg scan of a ClickHouse-written table fails #117072 was closed on the stated basis that over-long bounds keep decoding on the reader. So the guard has to reject a bound that is too short and keep tolerating one that is too long.
Tracked as its own change with that asymmetry. If you would rather have it in this pull request, say so and I will add it here instead.
There was a problem hiding this comment.
I would rather fold it into this PR. The new row-lineage hardening still routes _row_id / _last_updated_sequence_number bounds through the same fixed-width decoder, so a manifest with a 1..7-byte bound can still make this exact pruning path depend on indeterminate bytes. A wider cleanup for the other decoder call sites can still follow, but I do not think this row-lineage fix is complete while that malformed-input case remains live here.
There was a problem hiding this comment.
The fix for that exact path is already open as its own change, #118364, created after the earlier reply in this thread, which is why that reply named no pull request. It guards inside deserializeFieldFromBinaryRepr rather than at a call site:
if (column->isFixedAndContiguous() && str.length() < column->sizeOfValueIfFixed())
return std::nullopt;That sits above both row-lineage decodes (:171, :172) and the four ordinary-column ones (:673, :674, :697, :699), so with it in place a 1..7-byte _row_id or _last_updated_sequence_number bound no longer reaches insertData on this path, without any further change here. It also covers the ColumnFixedString zero-fill arm, which a row-lineage-only length check would leave open.
What folding it in would cost is the release fix. Re-measured today at the five active tags (v26.9.1.1-new, v26.8.2.7-lts, v26.7.6.57-stable, v26.6.4.55-stable, v26.3.30.9-lts): insertData(str.data(), str.length()) is present at all five, getMaterializedRowLineageRange at none of them. So the decoder bug is user-visible in official stable releases and a backport candidate, while the guard in this pull request is master-only and correctly not for changelog. As one change the two cannot be backported as a unit, because the row-lineage guard has no function to guard on any release branch.
I would therefore keep the split: #118364 owns the malformed-input case, and this pull request stays on declared pairs that are inverted or unrepresentable. If the assigned reviewer would rather have it here, I will move it here and close #118364.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 61 s compile time in total, 8 of them have a recent master baseline. |
| const UInt64 last_inherited_row_id = *entry.first_row_id + static_cast<UInt64>(parsed_entry.record_count) - 1; | ||
| /// `first_row_id` and `record_count` are both writer-declared, so the block of row ids they span | ||
| /// need not be representable, and a wrapped last row id would sit below the block's own first one. | ||
| UInt64 last_inherited_row_id = 0; |
There was a problem hiding this comment.
🕵️
On the case listed as not addressed — a negative first_row_id that does not wrap. I think it deserves its own issue rather than a line in the description, because the outcome is the same wrong results this PR fixes, not just absurd bounds.
first_row_id reaches addRowLineageHyperrectangles as std::optional<UInt64> (ManifestFileIterator.h:95, :153), so a declared -100 is already 18446744073709551516 by then. With record_count = 5 the sum does not overflow, addOverflow returns false, and the installed range is [2^64-100, 2^64-96]. A filter like _row_id = 5 does not intersect it, so the file is pruned and every row it holds is silently lost — which is the shape of the bug the declared-pair guard closes, reached without an overflow.
Grouping it with the untruthful-but-consistent class from #116604 reads right for a manifest that lies self-consistently, but this one is different in that the invalid input is detectable: the spec makes first_row_id non-negative, so a negative declared value is refusable on sight. It just is not refusable here, because the signedness is erased upstream where the field is parsed. So the fix is a validity check at that parse site, which is fairly clearly out of scope for this PR.
Nothing to change here — both guards fail open correctly and the test discrimination on [100, 50] versus swapping is good. Just worth a tracked issue so it does not disappear with this description.
There was a problem hiding this comment.
The arithmetic holds: -100 arrives as 18446744073709551516, record_count = 5 leaves addOverflow false, and the installed range is [2^64-100, 2^64-96].
The row loss is the part I cannot confirm. The reported _row_id is derived from the same field the range is built from: IcebergDataObjectInfo.cpp:74 takes first_row_id off the same ProcessedManifestFileEntry that addRowLineageHyperrectangles reads, and VirtualColumnUtils.cpp:615 computes each row as *first_row_id + row_positions[row] in UInt64 (the column is Nullable(UInt64), VirtualColumnUtils.cpp:215). Those five rows therefore report 18446744073709551516 through 18446744073709551520, which is exactly the range installed for them. _row_id = 5 matches no row of that file with pruning disabled either, so skipping the file returns the same rows as reading it. The ids are absurd, but the filter and the data agree, which is why I grouped this case with the untruthful-but-consistent one rather than with the guard.
The two only diverge once the block wraps, and that is the case the addOverflow guard closes: test_unrepresentable_row_id_block_does_not_prune declares first_row_id = -1 over ten rows, and position 6 there reports _row_id 5 while the block itself is unrepresentable.
So I have not opened an issue for it. Your point that the value is refusable on sight stands independently of the consequence, so if you would like the parse site to reject a negative first_row_id as spec hygiene, say so and I will do that. The signedness is erased in two places, AvroForIcebergDeserializer.cpp:199-206 for the per-data-file field and StatelessMetadataFileGetter.cpp:245-250 for the manifest-list one, so both would need the check.
This is a reading of those sites plus the existing test, not a run of the non-wrapping arm.
…verted-row-lineage-bounds
…column An Iceberg lower_bounds/upper_bounds payload is decoded by deserializeFieldFromBinaryRepr with column->insertData(str.data(), str.length()). For every fixed-width mapping that column is a ColumnVector or a ColumnDecimal, and both ignore the length: ColumnVector::insertData is data.emplace_back(unalignedLoad<T>(pos)) with the length parameter unnamed, and unalignedLoad is memcpy(&res, address, sizeof(res)). A bound declared in fewer bytes than the column's value is therefore read as sizeof(value) bytes, and the surplus bytes were never part of the serialized payload, so the range built from it is not the range the manifest declares. KeyCondition then prunes data files on it and rows go missing. Measured on a four-file IcebergLocal table of Int32 values above 100000, with field 1's bounds re-declared in two bytes: SELECT ... WHERE n > 50000 returned 0 of its 400 matching rows, 20 runs out of 20, because each truncated bound orders below 50000 and all four files were pruned. With this change the query returns 400 rows and prunes nothing. The check rejects only bounds that are too short, and deliberately keeps accepting bounds that are too long. Every currently released ClickHouse writes eight-byte bounds for four-byte columns, and ClickHouse#117072 was closed on the stated basis that ColumnVector::insertData ignores the buffer length so those bounds still decode. A symmetric length != width check would stop pruning for every table those releases wrote; the regression test pins that with an eight-byte bound on an Int32 column that must keep pruning. The predicate is asked of the column rather than the type on purpose. DataTypeUUID does not override isValueRepresentedByNumber, so a type-level gate would miss UUID although its column is a ColumnVector<UUID>; and DataTypeArray reports isValueUnambiguouslyRepresentedInFixedSizeContiguousMemoryRegion while leaving getSizeOfValueInMemory to throw, so a type-level width lookup could turn a manifest read into an exception. isFixedAndContiguous is true for exactly ColumnVector, ColumnDecimal and ColumnFixedString. FixedString is excluded because ColumnFixedString::insertData honours the length and zero-pads, so no byte outside the payload is read there. This leaves the two branches of the function asymmetric, which is intended. Iceberg serializes decimals as minimum-length two's-complement big-endian, so a short decimal payload is the normal encoding: measured, ClickHouse itself writes one- and two-byte bounds for a Decimal64(2) column. The decimal branch therefore rejects the opposite direction, str.size() > sizeof(NativeType). Fixed-width encodings reject too short; the variable-length minimal encoding rejects too long. Fixed at the decode rather than at the call sites, so all six callers inherit it, including the row lineage path that decodes with DataTypeUInt64. On nullopt every caller already falls back conservatively, so the guard can only ever reduce pruning. Related: ClickHouse#118299 Co-Authored-By: Claude Opus 5 <[email protected]>
The width guard in the previous commit exempted `FixedString`, on the grounds that `ColumnFixedString::insertData` honours the declared length and therefore reads nothing outside the payload. That is true and it is not sufficient, so the exemption is removed here. `ColumnFixedString::insertData` copies `length` bytes and then `memset`s the remaining `n - length` to zero. A bound declared in fewer bytes than the column still decodes to a value the writer never stored, and to a smaller one: on a `fixed[2]` column a one-byte upper bound `0x01` becomes `0x0100` while the file's true maximum can be `0x01ff`. The pair stays ordered, so the inversion check does not reach it, `KeyCondition` receives a range that ends below rows the file holds, and `mayBeTrueInRange` prunes a data file containing matching rows. Same wrong result as a numeric bound read past its payload, reached by zero filling instead. Dropping the clause makes the condition the general predicate rather than a special case. Every column `isFixedAndContiguous` admits ignores the declared length in one way or the other: `ColumnVector` and `ColumnDecimal` by reading `sizeof(value)` bytes past the payload, `ColumnFixedString` by zero filling the rest. All three are unusable when the bound is narrower than the value, and the one-sided comparison is unchanged, so a wider bound still decodes to the value the writer stored. `getIcebergType` rejects `FixedString`, so ClickHouse cannot write such a table and the regression test writes it with `pyiceberg` on the S3 backend, as the decimal test in the same file already does for the same reason. With field 1's `fixed[3]` bounds re-declared in two bytes, `SELECT f, n FROM icebergS3(...) WHERE f > '190'` read six of its seven matching rows before this change and reads seven after it. An over-long `fixed[N]` bound is left alone: `ColumnFixedString::insertData` throws `TOO_LARGE_STRING_SIZE` for it, which is pre-existing, fails loudly, and is a different question from pruning on an untrustworthy range. Related: ClickHouse#118299 Co-Authored-By: Claude Opus 5 <[email protected]>
The comment added with the guard claimed that "a wider bound still decodes to the value the writer stored". That is true for `ColumnVector` and `ColumnDecimal`, which read `sizeof(value)` bytes regardless of the declared length, and false for `ColumnFixedString`, the class the sentence before it introduces: `ColumnFixedString::insertData` opens with `if (length > n) throw Exception(ErrorCodes::TOO_LARGE_STRING_SIZE, ...)`, so an over-long `fixed[N]` bound does not decode at all. The last paragraph of the previous commit message says exactly that, so the comment contradicted it. The opening clause was imprecise for the same class for the opposite reason: `ColumnFixedString` does not ignore the declared length, it `memcpy`s `length` bytes and `memset`s the remaining `n - length` to zero. The replacement states only the non-obvious domain property the guard rests on, which holds for all three classes `isFixedAndContiguous` admits: a bound narrower than the column decodes to a value the writer never stored. Why the comparison is one-sided is backward compatibility with the widths released writers emit, which belongs in a commit message and is already stated at length in the previous one. Comment-only. With `///` lines stripped the file is byte-identical to the previous commit, so no behaviour, no generated code and no test result changes. Related: ClickHouse#118299 Co-Authored-By: Claude Opus 5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Row lineage pruning no longer trusts a manifest that declares an inverted
_row_idrange or a negativefirst_row_id. Master only, not present in any released version.Description
Related: #116499
Related: #116604
A filter on
_row_idor_last_updated_sequence_numberover a format-version 3 table is answered from the manifest, andKeyConditionrequires the range handed to it not to begin above where it ends. Two writer-declared inputs could break that:getMaterializedRowLineageRangebuiltDB::Rangestraight from thevalue_boundspair declared for the reserved field id, so a lower bound declared above the upper bound produced an empty range.first_row_id + record_count - 1in uncheckedUInt64arithmetic, whilefirst_row_idis parsed as a signed long, so a declared-1wrapped the sum and left the block ending below its own start.An empty range prunes the data file, so a filtered read silently loses every row it holds; debug and sanitizer builds abort on the
chassertopeningcheckInRange.Both cases now drop the untrustworthy bounds rather than swapping or clamping them, which would prune on a range the manifest never asserted, the reasoning of the guard for ordinary columns further down. The declared-pair case returns no range and lands on the existing conservative fallback
[0, last inherited row id], sound because a materialized value always comes from an earlier write. The wrapped-block case cannot use that fallback, because the wrapped value is that fallback's own upper bound, so it installs no row lineage range at all.Not for changelog: both changed functions are absent at the newest tag of every active release line, so no released version can exhibit this. #118181 carries the position-delete site of the same defect class. Reported by @ zlareb1 on #116604.Not addressed: a negative
first_row_idthat does not wrap gives well-ordered but absurd bounds, the untruthful-but-consistent class #116604 also left alone.deserializeFieldFromBinaryReprignoring a bound's declared length is fixed in #118364.Validation
Two integration arms patch a Spark-written v3 table's avro metadata before it is uploaded, then count skipped files through
check_validity_and_get_prunned_files_general, which also asserts both runs return the same rows. Each arm reddens only when its own guard is removed:WHERE _row_id = 25WHERE _row_id = 5The arms must run in separate invocations: the cluster fixture is package-scoped, so an abort in one is reported against the other as well.
The inverted arm declares
[100, 50]for_row_idon the file holding row id 25, chosen so the remedy is discriminated: dropping the bounds keeps the file readable and 4 files skipped, while swapping them would exclude 25, skip the file holding the matching row and make it 5. A pair drawn from the file's own block would not distinguish the two.A third assertion pins the opposite direction, on a copy-on-write table whose manifest declares a truthful
[0, 3]for_row_id:WHERE _row_id >= 4skips exactly one file. A build where the function stops returning a range at all falls back to[0, 7], which overlaps that filter, and the count becomes 0, so declining to use well formed declared bounds is caught too.Reddening is by the
chassertabort, because the build is debug. The wrong-results shape in a release build is not claimed as observed: it follows fromchassertexpanding to(void)sizeof(!(x)), which does not evaluate its argument.Workflow [PR]
Sync PR [sync-upstream/pr/118299]
Version info
26.9.1.1059(included in26.9and later)