Repository navigation
Count deleted rows count for single files in iceberg join ordering - #124395
Conversation
| std::span<const ProcessedManifestFileEntryPtr> defineDeletesSpan( | ||
| ProcessedManifestFileEntryPtr data_object_, | ||
| const std::vector<ProcessedManifestFileEntryPtr> & deletes_objects, | ||
| bool is_equality_delete, | ||
| LoggerPtr logger) | ||
| { | ||
| if (deletes_objects.empty()) | ||
| { | ||
| return {}; | ||
| } | ||
| /// Objects in deletes_objects are sorted by common_partition_specification, partition_key_value and added_sequence_number. | ||
| /// It is done to have an invariant that position deletes objects which corresponds | ||
| /// to the data object form a subsegment in a deletes_objects vector. | ||
| /// We need to take all position deletes objects which has the same partition schema and value and has added_sequence_number | ||
| /// greater than or equal to the data object added_sequence_number (https://iceberg.apache.org/spec/#scan-planning) | ||
| /// ManifestFileEntry has comparator by default which helps to do that. | ||
| auto beg_it = is_equality_delete ? | ||
| std::upper_bound(deletes_objects.begin(), deletes_objects.end(), data_object_) | ||
| : std::lower_bound(deletes_objects.begin(), deletes_objects.end(), data_object_); | ||
| auto end_it = std::upper_bound( | ||
| deletes_objects.begin(), | ||
| deletes_objects.end(), | ||
| data_object_, | ||
| [](const ProcessedManifestFileEntryPtr & lhs, const ProcessedManifestFileEntryPtr & rhs) | ||
| { | ||
| return std::tie(*lhs->common_partition_specification, lhs->normalized_partition_key_value) | ||
| < std::tie(*rhs->common_partition_specification, rhs->normalized_partition_key_value); | ||
| }); | ||
| if (beg_it - deletes_objects.begin() > end_it - deletes_objects.begin()) | ||
| { | ||
| throw DB::Exception( | ||
| DB::ErrorCodes::LOGICAL_ERROR, | ||
| "{} deletes objects are not sorted by common_partition_specification and partition_key_value, " | ||
| "beginning: {}, end: {}, position_deletes_objects size: {}", | ||
| is_equality_delete ? "Equality" : "Position", | ||
| beg_it - deletes_objects.begin(), | ||
| end_it - deletes_objects.begin(), | ||
| deletes_objects.size()); | ||
| } | ||
| if (beg_it != end_it) | ||
| { | ||
| auto previous_it = std::prev(end_it); | ||
| chassert(*beg_it); | ||
| chassert(*previous_it); | ||
| LOG_DEBUG( | ||
| logger, | ||
| "Preliminary check got {} {} delete elements for data file {}, taken data file object info: {}, first taken delete object info is " | ||
| "{}, last taken " | ||
| "delete object info is {}", | ||
| std::distance(beg_it, end_it), | ||
| is_equality_delete ? "equality" : "position", | ||
| data_object_->parsed_entry->file_path_key, | ||
| data_object_->dumpDeletesMatchingInfo(), | ||
| (*beg_it)->dumpDeletesMatchingInfo(), | ||
| (*previous_it)->dumpDeletesMatchingInfo()); | ||
| } | ||
| else | ||
| { | ||
| LOG_DEBUG( | ||
| logger, | ||
| "No {} delete elements for data file {}, taken data file object info: {}", | ||
| is_equality_delete ? "equality" : "position", | ||
| data_object_->parsed_entry->file_path_key, | ||
| data_object_->dumpDeletesMatchingInfo()); | ||
| } | ||
| return {beg_it, end_it}; | ||
| } |
There was a problem hiding this comment.
Extracted function
64634df to
e552b36
Compare
| <=> std::tie(*rhs->common_partition_specification, rhs->normalized_partition_key_value, rhs->sequence_number); | ||
| } | ||
|
|
||
| std::span<const ProcessedManifestFileEntryPtr> defineDeletesSpan( |
There was a problem hiding this comment.
Same function, just moved
|
Workflow [PR], commit [828c749] Summary: ✅
AI ReviewSummaryThis PR subtracts metadata-countable position deletes and deletion vectors from Iceberg row estimates used for join reordering. Missing context / blind spots
Findings
Tests
Final Verdict |
| const bool exact = *estimate->rows == 0 || (!has_filter && !estimate->has_delete_files); | ||
| RelationStats stats{ | ||
| .estimated_rows = estimate->rows, | ||
| .estimated_rows = *estimate->rows - estimate->deleted_rows, |
There was a problem hiding this comment.
Reducing only estimated_rows here makes the leaf relation internally inconsistent: the column_stats populated right below still come from estimate->num_distinct_values, which ManifestColumnStatistics::finalize computed against the pre-delete population. joinOrderCommon.h reads those NDVs from QueryGraph::relation_stats unchanged when it computes equality selectivity, so an Iceberg table that deleted many distinct join keys can still look much more selective than its live rows really are and get reordered incorrectly.
Please either recompute/cap the NDVs from the same live-row population, or drop the column stats entirely whenever deleted_rows != 0.
There was a problem hiding this comment.
There is still an uncapped path at src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestColumnStatistics.cpp:310–311: setCardinality is skipped when estimateDistinctValues returns std::nullopt. An unpartitioned String key with a NULL-count metric takes this path because it has neither a countable range nor a fixed width. Its underlying ColumnStatistics::rows is still the pre-delete population, so 1,000 original rows followed by 990 counted deletes produce a 10-row relation with the default NDV of 100. The unfiltered ConditionSelectivityEstimator::estimateRelationProfile returns that NDV without a clamp, and the join estimator copies it unchanged.
Please also cap the fallback cardinality to the live-row population, and cover a heavily deleted String join key; the integer-range case in T5 only exercises the explicit override.
e552b36 to
407ddbd
Compare
05e80d2 to
dca73bf
Compare
|
Why do we make and reduce |
dca73bf to
72671f0
Compare
done: |
|
|
||
| /// Counts the rows of `data_files` removed by deletion vectors and by position delete files scoped to one data file, | ||
| /// matched as `IcebergIterator::next` matches them; std::nullopt if such a delete file has a negative `record_count`. | ||
| std::optional<UInt64> countDeletedRows( |
There was a problem hiding this comment.
Comments said
std::nullopt if such a delete file has a negative `record_count`.
But I didn't see the logic
There was a problem hiding this comment.
The check is inside the loop over the delete files matched to a data file: if (entry.record_count < 0) return std::nullopt; in countDeletedRows
(
be86f37 to
d9e0a95
Compare
d9e0a95 to
194a22c
Compare
…ceberg row estimate
The filter of a read is estimated on the rows left after the deleted rows the metadata counts: 2000 rows, 500 deleted by a file-scoped delete, `v = 1` with 5 values gives 300. This case was in the test of #124448, which moved into the PR below without it.
Since the parent PR passes only counted numbers of distinct values, a range above the rows left after the deletes gives no number and the estimator keeps its guess, 10% of the rows. Co-Authored-By: Claude Opus 5.5 <[email protected]>
194a22c to
c5c3a87
Compare
| for (const auto & position_delete : position_deletes) | ||
| { | ||
| const auto & lower = position_delete->parsed_entry->lower_reference_data_file_path; | ||
| if (lower.has_value() && lower == position_delete->parsed_entry->upper_reference_data_file_path) |
There was a problem hiding this comment.
Why do we only count the delete files which lower == upper? AFAIU the delete files can be used if (delete's [lower, upper] falls in datafile's [lower, upper])
There was a problem hiding this comment.
The problem with doing so are pruned files. In case we prune 1 file and we have delete file which spans its deletes across many files including one of those pruned ones, we cannot figure out in the end what number we should subtract.
So, I decided not to include those files. The second reason is that deletion vectors are always bound to one file, and that spark actually produces 1 delete file per file. Only problem is clickhouse engine here, but with @\scanhex12's work on compaction, we are also producing one bigger file and compacting these delete files, so I am not too worried of that case.
| void ManifestColumnStatistics::subtractDeletedRows(UInt64 rows) | ||
| { | ||
| chassert(rows <= total_rows); | ||
| total_rows -= rows; |
There was a problem hiding this comment.
Both total_rows and rows are UInt64, if rows > total_rows, the total_rows will be a very huge number and chassert will not fail in release build. Please set it zero in this case.
| for (const auto & position_delete : defineDeletesSpan(data_file, it->second, /* is_equality_delete */ false, log)) | ||
| { | ||
| const auto & entry = *position_delete->parsed_entry; | ||
| if (entry.record_count < 0) |
There was a problem hiding this comment.
Please log something in this case
| return std::clamp<UInt64>(num_distinct_values, 1, std::max<UInt64>(non_null_rows, 1)); | ||
| } | ||
|
|
||
| void ManifestColumnStatistics::subtractDeletedRows(UInt64 rows) |
There was a problem hiding this comment.
I think with this Logic, stats.imprecise_estimate = rows != 0 && estimate->has_delete_files; should change to stats.imprecise_estimate = estimate->has_delete_files; because it's possible to substract the total_rows to zero. right?
There was a problem hiding this comment.
I am not sure, but makes sense to simplify it 👍
| if (entry.record_count < 0) | ||
| return std::nullopt; | ||
| if (entry.isDeletionVector()) | ||
| deletion_vector_rows = entry.record_count; |
There was a problem hiding this comment.
I am a little confused here: why do we not sum the count of deletion vector? Shall we add a simple comment here?
There was a problem hiding this comment.
Per iceberg spec, data file holds at most one deletion vector file. Adding a comment
…hes 0 The subtracted deletes can reach 0 rows, which was then reported as an exact 0, although overlapping position deletes or the per-file cap can leave rows. 05325 T7 deletes every row of a one-file table: `t[0]` before, `t[no_stats~0]` after. #124395 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…letion vector count A delete file with a negative `record_count` now logs a warning before the read loses its row estimate; `subtractDeletedRows` saturates at 0 in release builds; a comment says why a deletion vector is taken, not summed. #124395 (comment) #124395 (comment) #124395 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
| if (lower.has_value() && lower == position_delete->parsed_entry->upper_reference_data_file_path) | ||
| deletes_by_data_file[*lower].push_back(position_delete); | ||
| else | ||
| ProfileEvents::increment(ProfileEvents::IcebergRowEstimateSkippedPositionDeleteFiles); |
There was a problem hiding this comment.
I don't think a profile event is worthy here. I think log will suffice.
…ofile event The number of position delete files the row estimate does not subtract goes to one debug log line per estimate; `IcebergRowEstimateSkippedPositionDeleteFiles` and its check in 05325 are removed. #124395 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #120440
Related: #123085
Related: #123553
Related: #124857
The third PR for #120440, after #123553 (merged). The row estimate of an Iceberg read from #123085 is the sum of
record_countof the remaining data files, deleted rows included. This PR subtracts the deleted rows that the manifests can count, without reading data. The delete files are matched to the remaining data files as the read matches them. I extracteddefineDeletesSpantoManifestFileso the manifest walk can share it.ManifestColumnStatistics::subtractDeletedRowstakes the counted rows off the row count beforefinalizesets the rows of the estimate and gives them to the estimator. So the rows of the estimate are the live rows, a value range of #123553 counts the distinct values only if it fits in them (05325 T5:k0..199 with 180 rows left gets no count), and the conditions of #123553 are estimated as shares of them (05325 T6: 2000 rows, 500 deleted,v = 1of 5 values gives 300).What is subtracted
record_countis the number of rows it deletes. As in the read, a deletion vector replaces the position delete files of its data file.file_pathcolumn name the same data file.record_count.Not subtracted:
IcebergRowEstimateSkippedPositionDeleteFilescounts them.The estimate stays imprecise (
t[no_stats~N]) whenever there are delete files, also when no row is left (05325 T7). A delete file with a negativerecord_countmakes the rows unknown and logs a warning, as a data file with a negativerecord_countdoes in #123085.Known limitations
DELETEwrites one position delete file per partition and statement, covering every data file it touches. So on tables written by ClickHouse, aDELETEover more than one data file is not subtracted. Writing one delete file per data file, as Spark does withwrite.delete.granularity = file, would make them countable in this case.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The Iceberg row estimate for join reordering (
use_iceberg_manifest_statistics) now subtracts the rows removed by deletion vectors and by position delete files that apply to a single data file.Workflow [PR]
Sync PR [sync-upstream/pr/124395]
Version info
26.11.1.1248-master(included in26.11and later)