Skip to content

Count deleted rows count for single files in iceberg join ordering - #124395

Merged
antoniofilipovic merged 8 commits into
masterfrom
afilipovic-iceberg-deleted-rows
Nov 3, 2026
Merged

antoniofilipovic merged 8 commits into
masterfrom
afilipovic-iceberg-deleted-rows

Conversation

@antoniofilipovic

@antoniofilipovic antoniofilipovic commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

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_count of 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 extracted defineDeletesSpan to ManifestFile so the manifest walk can share it.

ManifestColumnStatistics::subtractDeletedRows takes the counted rows off the row count before finalize sets 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: k 0..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 = 1 of 5 values gives 300).

What is subtracted

  • Deletion vectors (format v3): each names one data file, and its record_count is the number of rows it deletes. As in the read, a deletion vector replaces the position delete files of its data file.
  • Position delete files scoped to one data file (format v2): the lower and upper bounds of their file_path column name the same data file.
  • Only delete files that apply to a remaining data file count, so a filter that prunes a data file also drops its deletes. Each data file loses at most its own record_count.

Not subtracted:

  • Position delete files whose bounds cover several data files: how many rows each data file loses is not in the metadata. The new ProfileEvent IcebergRowEstimateSkippedPositionDeleteFiles counts them.
  • Equality deletes: which rows they remove is known only from the data.

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 negative record_count makes the rows unknown and logs a warning, as a data file with a negative record_count does in #123085.

Known limitations

  • ClickHouse's own DELETE writes one position delete file per partition and statement, covering every data file it touches. So on tables written by ClickHouse, a DELETE over more than one data file is not subtracted. Writing one delete file per data file, as Spark does with write.delete.granularity = file, would make them countable in this case.
  • Min/max and NULL counts still include the deleted rows: the delete files give no values.

Changelog category (leave one):

  • Improvement

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

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

Comment on lines -118 to -184
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};
}

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 function

@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Oct 7, 2026
@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-iceberg-deleted-rows branch 2 times, most recently from 64634df to e552b36 Compare October 7, 2026 15:29
@antoniofilipovic antoniofilipovic changed the title Estimate deleted rows count for iceberg join ordering Include deleted rows count for single files in iceberg join ordering Oct 8, 2026
@antoniofilipovic antoniofilipovic changed the title Include deleted rows count for single files in iceberg join ordering Count deleted rows count for single files in iceberg join ordering Oct 8, 2026
<=> std::tie(*rhs->common_partition_specification, rhs->normalized_partition_key_value, rhs->sequence_number);
}

std::span<const ProcessedManifestFileEntryPtr> defineDeletesSpan(

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.

Same function, just moved

@antoniofilipovic
antoniofilipovic marked this pull request as ready for review October 8, 2026 07:22
@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [828c749]

Summary: ✅


AI Review

Summary

This PR subtracts metadata-countable position deletes and deletion vectors from Iceberg row estimates used for join reordering. ⚠️ Request changes: live-row estimates can still carry impossible distinct-value counts, planning retains all surviving file metadata, and deletion-vector behavior lacks automated regression coverage. Reviewed PR head 828c7497f2cb31105302e3c47cb5c0f688487506 and all existing discussion; these are retained findings from existing inline threads.

Missing context / blind spots
  • ⚠️ No ClickHouse binary or configured build is available locally. The counterexample below follows the current source; running the focused cases on the PR build would provide execution evidence.
Findings

⚠️ Majors

  1. Distinct-value counts can exceed the live population. ManifestColumnStatistics.cpp:269–300, existing thread. subtractDeletedRows changes only the relation row count; each merged ColumnStatistics retains its original rows. When estimateDistinctValues returns std::nullopt (an unpartitioned String key or a sparse integer range), the default NDV remains 10% of those original rows. Thus 1,000 rows minus 990 counted deletes gives a 10-row relation with NDV 100. The unfiltered ConditionSelectivityEstimator::estimateRelationProfile and estimateReadRowsCount pass that NDV through, and joinOrderCommon.h uses it directly as reliable equality selectivity, distorting join costs. Cap guessed NDVs to the live population without marking the guess as a measured cardinality, or omit those column statistics.

  2. Planning memory grows with all surviving data-file metadata. IcebergMetadata.cpp:1769, existing thread. Every surviving ProcessedManifestFileEntry is retained until the complete snapshot has been walked, including tables with no deletes. Previously, each manifest handle released its processed entries before advancing. The retained entries also own parsed bounds and per-column metrics, preventing their release when caching is disabled or cache entries are evicted. The bounded ManifestFilesPrefetcher therefore no longer bounds this memory, and a large-table join can exhaust its query memory during planning. Process delete manifests first and count while consuming each data manifest, or retain only compact matching information; avoid retaining data entries when no countable deletes exist.

  3. The deletion-vector contract has no automated regression coverage. 05325_iceberg_manifest_stats_deletes.sh:52–69. [dismissed by author -- https://github.com/Count deleted rows count for single files in iceberg join ordering #124395#discussion_r4327453434] The author reports successful manual Spark checks and chose not to commit fixtures; the concern remains because every created table uses format v2 and the copied fixture contains position/equality deletes, so removing the deletion-vector replacement branch would leave this test unchanged. Add a small v3 fixture asserting subtraction, replacement of applicable older position deletes, and exclusion when its referenced data file is pruned.

Tests
  • ⚠️ Add an unfiltered estimate case with a heavily deleted String or sparse integer join key; verify that the reported NDV cannot exceed the remaining rows.
  • ⚠️ Add the focused deletion-vector fixture described above.
  • ⚠️ Verify planning peak memory across increasing manifest counts, including a table without deletes and disabled metadata caching, after fixing retention.
Final Verdict

⚠️ Request changes. Bound guessed NDVs by the live rows, restore bounded manifest-processing memory, and add deletion-vector regression coverage. All three findings already have inline threads; no duplicate inline comments were posted.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 8, 2026
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,

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.

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.

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.

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.

@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-iceberg-deleted-rows branch 2 times, most recently from 05e80d2 to dca73bf Compare October 13, 2026 10:51
@hanfei1991

Copy link
Copy Markdown
Member

Why do we make deleted_rows a part of DataLakeReadEstimate? I think we can simply

rows = rows - deleted_rows

and reduce distinct values proportionally

@antoniofilipovic

Copy link
Copy Markdown
Member Author

Why do we make deleted_rows a part of DataLakeReadEstimate? I think we can simply

rows = rows - deleted_rows

and reduce distinct values proportionally

done: deleted_rows are no longer in DataLakeReadEstimate. ManifestColumnStatistics subtracts the deleted rows from its row count before it builds the profile, so the profile's rows are the live rows, and the numbers of distinct values are clamped to them.


/// 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(

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.

Comments said

std::nullopt if such a delete file has a negative `record_count`.

But I didn't see the logic

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 check is inside the loop over the delete files matched to a data file: if (entry.record_count < 0) return std::nullopt; in countDeletedRows
(

). "Such a delete file" in the comment means one of those matched files, and a delete file that matches no remaining data file is not looked at.

@antoniofilipovic
antoniofilipovic removed this pull request from stack #124571 October 20, 2026 15:57
@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-iceberg-deleted-rows branch 3 times, most recently from be86f37 to d9e0a95 Compare October 29, 2026 12:30
Base automatically changed from afilipovic-iceberg-column-stats to master November 1, 2026 13:26
@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-iceberg-deleted-rows branch from d9e0a95 to 194a22c Compare November 1, 2026 13:26
antoniofilipovic and others added 5 commits November 2, 2026 10:14
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]>
@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-iceberg-deleted-rows branch from 194a22c to c5c3a87 Compare November 2, 2026 11:04
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)

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

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

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.

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.

@antoniofilipovic antoniofilipovic Nov 3, 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.

Done

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)

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.

Please log something in this case

@antoniofilipovic antoniofilipovic Nov 3, 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.

Done

return std::clamp<UInt64>(num_distinct_values, 1, std::max<UInt64>(non_null_rows, 1));
}

void ManifestColumnStatistics::subtractDeletedRows(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.

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?

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 sure, but makes sense to simplify it 👍

@antoniofilipovic antoniofilipovic Nov 3, 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.

done

if (entry.record_count < 0)
return std::nullopt;
if (entry.isDeletionVector())
deletion_vector_rows = entry.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.

I am a little confused here: why do we not sum the count of deletion vector? Shall we add a simple comment here?

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.

Per iceberg spec, data file holds at most one deletion vector file. Adding a comment

antoniofilipovic and others added 2 commits November 3, 2026 10:47
…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);

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.

I don't think a profile event is worthy here. I think log will suffice.

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.

Fixed

…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]>
@antoniofilipovic
antoniofilipovic enabled stacked auto-merge November 3, 2026 12:50
@antoniofilipovic
antoniofilipovic added this pull request to the merge queue Nov 3, 2026
Merged via the queue into master with commit 56edfa7 Nov 3, 2026
185 checks passed
@antoniofilipovic
antoniofilipovic deleted the afilipovic-iceberg-deleted-rows branch November 3, 2026 20:04
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 3, 2026
@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.

3 participants