Repository navigation
Estimate the rows for Iceberg from manifest files for join reordering - #123085
Conversation
|
Workflow [PR], commit [a317f14] Summary: ✅
AI ReviewSummaryReviewed PR head Missing context / blind spots
Findings
Tests
Final Verdict
|
a0ada79 to
022296e
Compare
| if (DB::WhichDataType(DB::removeNullable(column_type)).isDecimal()) | ||
| { | ||
| declared_left = deserializeFieldFromBinaryRepr( | ||
| left_str, column_type, true, /*compensate_rounding=*/false); |
There was a problem hiding this comment.
Extracted to the method
022296e to
6c2cab2
Compare
groeneai
left a comment
There was a problem hiding this comment.
I read the diff against the read path and built it merged into current master (debug). estimateRead prunes with the same pruners, file schema and manifest partition key as IcebergIterator, so I only have the two inline points and:
- The
clickhouse-ghPREWHERE thread does not reproduce on this head.optimizePrimaryKeyConditionAndLimitadds the row policy and thePREWHEREto the step filter beforeapplyFilters(), and it runs beforeoptimizeJoinLogicalinoptimizeTreeSecondPass. On the05293fixture,SELECT count() FROM p JOIN mt AS m ON m.x = p.v PREWHERE p.r = 'us'givesp[no_stats~15], the same as theWHEREform, and the read step showsPrewhere filter column: r = 'us'. Adding that arm to05293T1 would pin it if you want to close the thread with a test. - The changelog entry is still
....
|
|
||
| const bool exact = *estimate->rows == 0 || (!has_filter && !estimate->has_delete_files); | ||
| return RelationStats{ | ||
| .estimated_rows = *estimate->rows, |
There was a problem hiding this comment.
This is the only error failing Build (arm_tidy) on a0ac442f (bugprone-optional-value-conversion), and that job drops all the others, so none of the new tests has run in CI yet. The job ran ninja -k0 all and tidied every TU this diff touches, so this should be the complete set.
| .estimated_rows = *estimate->rows, | |
| .estimated_rows = estimate->rows, |
There was a problem hiding this comment.
Applied: .estimated_rows = estimate->rows.
| context, | ||
| /* require_ready_sets */ true); | ||
|
|
||
| for (const auto & manifest_list_entry : data_snapshot->manifest_list_entries) |
There was a problem hiding this comment.
Without a pruning filter, this walk opens every manifest only to sum what the snapshot summary already holds. data_snapshot->total_rows is total-records (rows of the live data files, deleted rows included, the same quantity summed here), and total_position_delete_rows / total_equality_delete_rows give has_delete_files. totalRows() already reads it through getTotalRows(), with the walk as the fallback when the optional field is absent.
Measured on a 300-manifest IcebergLocal table: EXPLAIN of an unfiltered join with mt opens 306 files with the setting on vs 4 with it off (FileOpen, clickhouse local, cold metadata cache), and the printed estimate, b[3000], equals the summary's total-records.
Where the walk is needed, Iceberg::decodeManifestsInOrder (what totalRows() uses below; ParallelManifestDecode.h is already included here) would also lift the serial-decode limitation listed in the description.
There was a problem hiding this comment.
Thanks. I kept the walk as the only path: the follow-ups need the per-file entries anyway (column statistics in #123553, deleted rows in the next PR), and summary totals can be off where the per-file sum is not (OPTIMIZE inflates total-records, #109288). The decode is now parallel with decodeManifestsInOrder, as suggested (8efefad); I'll drop the serial-decode limitation from the description.
| for (const auto & manifest_list_entry : data_snapshot->manifest_list_entries) | ||
| { | ||
| if (manifest_list_entry.content_type == ManifestFileContentType::DATA && manifest_list_pruner | ||
| && manifest_list_pruner->canBePruned(manifest_list_entry.partition_spec_id, manifest_list_entry.partition_summaries)) |
There was a problem hiding this comment.
pruned_data_files is what flips a filtered Iceberg read from unknown to no_stats~N, but this branch sets it before we know whether the skipped manifest contributes any live data at all.
ManifestFileCacheKey already carries live_files_count, and the read path uses that same field when it counts manifest-list pruning in IcebergIterator.cpp. So if the filter only skips a DATA manifest whose live_files_count == 0 (for example a manifest that now contains only deleted entries), the remaining live-row sum is unchanged, yet the estimator still reports a row estimate instead of the promised unknown.
Please gate this on manifest_list_entry.live_files_count > 0 (or an equivalent live-row check) before setting estimate.pruned_data_files = true.
There was a problem hiding this comment.
Kept as is: skipping a manifest without live files leaves the rows of the remaining files unchanged, and they are still an upper bound of the filtered read, which is what no_stats~N stands for.
Build profile diff (arm_release)Commit See the job log for details. |
| return unknown; | ||
|
|
||
| /// The step's filter also holds the `PREWHERE` and the row policy, so a read without it returns every row. | ||
| const bool has_filter = filter || reading->getFilterActionsDAG() || reading->getPrewhereInfo() || reading->getRowLevelFilter(); |
There was a problem hiding this comment.
- why it differs from
ReadFromMergeTree? - IMO
ReadFromMergeTreecan share a lot withReadFromObjectStorageStep, if it's the case it might be worthwhile to extract common code, or dispatch theif-cast
There was a problem hiding this comment.
For this part unfortunately I could not reuse much although it looks similar. For the part that can be common is actually used later. In the part where we collect statistics for columns I used the common method of ConditionSelectivityEstimator which is next PR (#123553).
MergeTree has range analysis and the index stats walk, while the part for iceberg has its own settings, estimateReadFromDataLakeMetadata and delete files so it is that common.
| } | ||
| } | ||
|
|
||
| /// A negative count comes from a corrupted manifest, as in `totalRows`. |
There was a problem hiding this comment.
Why not filter the corrected data in advance
There was a problem hiding this comment.
If the questions is why do we not go through all the files before pruning to check if there is a file with negative record count, the perf test I did showed filtering files is not bottleneck. The only problem is loading files if the cache for manifest entries is full, so doing it in parallel helps and later steps are cheap, few milliseconds.
| struct DataLakeReadEstimate | ||
| { | ||
| /// Rows of the live data files left after pruning, deleted rows included; std::nullopt if the metadata is malformed. | ||
| std::optional<UInt64> rows; |
There was a problem hiding this comment.
is it better to preserve various original rows, so that the Estimator can estimate based on filter selectivity ?
There was a problem hiding this comment.
Sorry could you explain what do you mean a bit more, I am not sure which various original rows should be preserved? Generally I implemented the estimate based on filter selectivity, that is PR 4/4 in this stack #124448 and there is one more with collecting stats for columns #123553, so we collect different data and build on top of ConditionSelectivityEstimator for per-file rows, min/max etc
b981acb to
fc59aa7
Compare
| /// As for MergeTree without column statistics, a filter that pruned nothing gives no estimate. | ||
| if (has_filter && !estimate->pruned_data_files && *estimate->rows != 0) | ||
| return unknown; |
There was a problem hiding this comment.
I am not confident in this one, I would rather return upper bound if we have filter but did not prune, than keep it in sync with MergeTree. The idea is if we have filter but we did not prune, we return unknown. I understand where the idea comes from for MergeTree, but for regular stats pruning this should be rather an upper bound with rows survived:
fc59aa7 to
9ff7916
Compare
| DB::ThreadName::ICEBERG_ITERATOR, | ||
| [this, &context, &table_state_snapshot](const ManifestFileCacheKey & manifest_list_entry) | ||
| { | ||
| return getManifestFileEntriesHandle( |
There was a problem hiding this comment.
[P2] Check cancellation during the planning manifest walk
With use_iceberg_manifest_statistics = 1, planning an unfiltered join or EXPLAIN now walks every manifest. However, getManifestFileEntriesHandle drains ManifestFileIterator without a stop flag, and neither callback here nor decodeManifestsInOrder checks the query status. Cancelling the query while this runs therefore still lets the estimator schedule and decode the remaining manifests; on a large table it can retain the query slot and continue metadata I/O long after KILL QUERY.
Please check the process-list cancellation/time limit while scheduling and consuming manifests, and let active decoders observe cancellation as well. The analogous planning-time part analysis in MergeTreeDataSelectExecutor already checks QueryStatus::checkTimeLimit per part.
There was a problem hiding this comment.
The consumer check in e1aadfa helps between manifests, but the in-flight part of this finding remains at 4087a61: IcebergMetadata.cpp:1476 still calls getManifestFileEntriesHandle, whose loop in StatelessMetadataFileGetter.cpp:198 drains the iterator without a stop flag or a query-status check. decodeManifestsInOrder reaches the new check only after pending.get, and its scope guard waits for the other decoder futures when that check throws. Consequently, cancellation during a large manifest decode still waits for the full active decodes to finish. The per-file pruning loop at IcebergMetadata.cpp:1493 also has no cancellation check. Please propagate cancellation into that work as well.
There was a problem hiding this comment.
The remaining wait is bounded by iceberg_manifest_decode_concurrency: once the check throws, no new decode starts, and the scope guard waits only for the decodes already running. On a table with 3000 manifests and a cold cache, KILL QUERY 0.2 s after the start now ends the query at 0.45 s instead of 2.43 s. Stopping inside getManifestFileEntriesHandle would change the manifest reader the read path shares, so I would leave that to a separate change.
| return true; | ||
| }); | ||
| if (has_negative_record_count) | ||
| { |
There was a problem hiding this comment.
We can log something when record_count is negative
4087a61 to
a317f14
Compare
…lace-build-mutex Conflicts resolved: - ReadFromMergeTree.cpp, MergeTreeData.cpp: keep master's `skip_analysis_` (no longer tied to `use_skip_indexes`, ClickHouse#123403), the PK factory without `relaxRangeAtomsOverNaNHidingTupleColumns`, and the vector similarity factory capturing `index_helper`; add the factories' `require_ready_sets` argument on top. - MergeTreeIndexText.cpp: master's `params.enable_positions` plus `require_ready_sets`. - ManifestFilesPruning.cpp: take master's version (ClickHouse#123085 made `require_ready_sets` a constructor parameter); pass `true` at the decode thread caller `ManifestFileIterator::getOrCreatePruner`, as this branch did inside the pruner before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #120440
Related: #123553
Related: #124395
Related: #124857
Iceberg tables now get the estimate of row count for their reads which are then used for join reordering. This PR prepares terrain for the #123553, which tracks statistics per column for Iceberg reads (min,max, NDV).
The current PR takes into account filter pruning and mimics MergeTree behavior on presenting estimates of row counts estimates (precise vs imprecise, unknown vs known) for the join ordering.
Precision follows MergeTree without column statistics, with the same labels in
EXPLAIN(t[N],t[no_stats~N],t[no_stats~?]):Differences from the issue suggestion
estimateReadreturnsDataLakeReadEstimate(rows,pruned_data_files,has_delete_files): the estimator needs the two flags for the precision. Include the column statistics of Iceberg reads from manifest files for join reordering #123553 replacesrowswith aRelationProfilethat also carries the column statistics.Known limitations
record_countis trusted as written. ClickHouse 26.4 and older wrote the row count of the whole commit into every data file of the commit (fixed in Fix iceberg stats with partitioned table #104329), so for tables written by those versions the estimate overstates the rows. The same manifests makecount()wrong on its manifest path(Fix Iceberg count() on tables whose manifest files over-report row counts #118942).
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Join reordering can now estimate the rows of an Iceberg table from the
record_countof its data files in the manifest files, after partition and min/max pruning by the query filter, without reading data. Enable it with the new settinguse_iceberg_manifest_statistics(disabled by default).Workflow [PR]
Sync PR [sync-upstream/pr/123085]
Version info
26.11.1.641-master(included in26.11and later)