Skip to content

Estimate the rows for Iceberg from manifest files for join reordering - #123085

Merged
antoniofilipovic merged 13 commits into
masterfrom
afilipovic-stats-for-iceberg
Oct 23, 2026
Merged

antoniofilipovic merged 13 commits into
masterfrom
afilipovic-stats-for-iceberg

Conversation

@antoniofilipovic

@antoniofilipovic antoniofilipovic commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

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~?]):

  • no filter and no live delete files: exact;
  • a filter that dropped at least one data file, or live delete files: imprecise upper bound;
  • a filter that dropped nothing: unknown;
  • a filter that dropped every file: exact 0.

Differences from the issue suggestion

Known limitations

Changelog category (leave one):

  • Improvement

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_count of 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 setting use_iceberg_manifest_statistics (disabled by default).


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

Version info

  • Merged into: 26.11.1.641-master (included in 26.11 and later)

@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a317f14]

Summary: ✅


AI Review

Summary

Reviewed PR head a317f145a1e2e368db25605750dda59b6ee1d5a1. The PR adds opt-in Iceberg manifest row estimates for join reordering through use_iceberg_manifest_statistics. Two previously reported issues remain in the current code: cancellation does not reach active manifest work, and skipping an obsolete manifest can incorrectly turn an unknown filtered cardinality into a known estimate.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build is available. The current targeted CI report exposes no individual results for 05292, 05293, or 05296; execution results for those tests would close this validation gap.
Findings

⚠️ Majors

  • IcebergMetadata.cpp:1509–1528: Planning must honor cancellation during manifest work. The new checkTimeLimit runs only after a complete manifest has decoded. getManifestFileEntriesHandle still creates ManifestFileIterator without its stop flag and drains it without cancellation checks. decodeManifestsInOrder waits for the first result before invoking the check and waits for the other active futures during unwinding. The subsequent per-file pruning loop also has no check. Consequently, KILL QUERY or an execution timeout can leave substantial metadata decoding/pruning running and retain query resources until that work completes. Propagate cancellation into decoding, check it during scheduling and per-file processing, and stop outstanding work before waiting for it. This remains covered by the existing thread and follow-up; no duplicate reply was posted.

  • IcebergMetadata.cpp:1493–1495: A filter that prunes no live data must retain unknown cardinality. This branch sets pruned_data_files even when the skipped manifest contains only deleted entries (live_files_count == 0). For example, skipping such an obsolete partition manifest while keeping every live file sets the flag without reducing the live-row sum. RelationStatisticsEstimator then reports no_stats~N instead of the promised no_stats~?, allowing a filter with unknown selectivity to affect join ordering through the full-table count. Set the flag only when a live data file was excluded; use a positive live-file count or verify the entries when that count is unavailable. The existing inline finding remains applicable.

Tests
  • ⚠️ Add focused coverage showing that pruning a manifest containing only deleted entries leaves a nonempty filtered read's estimate unknown when no live file is pruned.
  • ⚠️ Validate cancellation while a manifest is actively decoded or its files are pruned; the current tests do not exercise this boundary.
Final Verdict

⚠️ Request changes. Complete cancellation propagation and require evidence of live-file pruning before setting pruned_data_files, with focused validation of both cases. Both findings already have inline threads; there are no new findings to submit in another review.

@antoniofilipovic antoniofilipovic linked an issue Sep 30, 2026 that may be closed by this pull request
@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 30, 2026
@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-stats-for-iceberg branch from a0ada79 to 022296e Compare October 2, 2026 08:34
Comment on lines -524 to -598
if (DB::WhichDataType(DB::removeNullable(column_type)).isDecimal())
{
declared_left = deserializeFieldFromBinaryRepr(
left_str, column_type, true, /*compensate_rounding=*/false);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Extracted to the method

@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-stats-for-iceberg branch from 022296e to 6c2cab2 Compare October 5, 2026 10:55
@antoniofilipovic antoniofilipovic changed the title Use Iceberg manifest statistics for join reordering Estimate the rows for Iceberg from manifest files for join reordering Oct 5, 2026
@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 5, 2026
Comment thread src/Core/Settings.cpp Resolved

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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-gh PREWHERE thread does not reproduce on this head. optimizePrimaryKeyConditionAndLimit adds the row policy and the PREWHERE to the step filter before applyFilters(), and it runs before optimizeJoinLogical in optimizeTreeSecondPass. On the 05293 fixture, SELECT count() FROM p JOIN mt AS m ON m.x = p.v PREWHERE p.r = 'us' gives p[no_stats~15], the same as the WHERE form, and the read step shows Prewhere filter column: r = 'us'. Adding that arm to 05293 T1 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,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Suggested change
.estimated_rows = *estimate->rows,
.estimated_rows = estimate->rows,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Applied: .estimated_rows = estimate->rows.

context,
/* require_ready_sets */ true);

for (const auto & manifest_list_entry : data_snapshot->manifest_list_entries)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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))

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit a317f145a1e2e368db25605750dda59b6ee1d5a1 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "LowCardinality(String)" …).

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();

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.

  1. why it differs from ReadFromMergeTree ?
  2. IMO ReadFromMergeTree can share a lot with ReadFromObjectStorageStep, if it's the case it might be worthwhile to extract common code, or dispatch the if-cast

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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`.

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.

Why not filter the corrected data in advance

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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;

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.

is it better to preserve various original rows, so that the Estimator can estimate based on filter selectivity ?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-stats-for-iceberg branch from b981acb to fc59aa7 Compare October 8, 2026 11:00
@hanfei1991 hanfei1991 self-assigned this Oct 8, 2026
Comment on lines +252 to +254
/// 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;

@antoniofilipovic antoniofilipovic Oct 8, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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:

/// If any conditions are pushed down to storage but not used in the index,

DB::ThreadName::ICEBERG_ITERATOR,
[this, &context, &table_state_snapshot](const ManifestFileCacheKey & manifest_list_entry)
{
return getManifestFileEntriesHandle(

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.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in e1aadfa.

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 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@hanfei1991 hanfei1991 left a comment

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.

LGTM

return true;
});
if (has_negative_record_count)
{

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.

We can log something when record_count is negative

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done

@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-stats-for-iceberg branch from 4087a61 to a317f14 Compare October 22, 2026 15:00
@antoniofilipovic
antoniofilipovic added this pull request to the merge queue Oct 23, 2026
Merged via the queue into master with commit 1225017 Oct 23, 2026
179 checks passed
@antoniofilipovic
antoniofilipovic deleted the afilipovic-stats-for-iceberg branch October 23, 2026 08:31
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 23, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 23, 2026
…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]>
@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

comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Expose Iceberg manifest statistics to the query optimizer

5 participants