Repository navigation
Fix DeltaLake trivial count over tables with deletion vectors - #115872
Conversation
A bare SELECT count() over a Delta table with delta.enableDeletionVectors set answered from the numRecords file statistics, which still include the rows a deletion vector removes, so it reported more rows than the table has. Every query that scans returned the correct answer, which made the count disagree with everything else the same table reported. system.tables.total_rows over a DeltaLake engine table over-counted the same way, reading the same IStorage::totalRows seam. TableSnapshot accumulates total_rows at two places, the scan callback and the metadata-only stats visitor, and both summed stats->num_records while holding the file's dv_info handle and ignoring it. delta-kernel documents that statistic as stale under a deletion vector in the same doc comment that names DvInfo::has_vector as the flag to consult, in kernel/src/scan/state.rs. Both sites now drop total_rows when a file carries a deletion vector, so totalRows returns nothing, applyTrivialCountIfPossible declines, and the query takes the ordinary scan path that already applies the vector. total_bytes is left alone, since a deletion vector adds its own file and does not change the size of the data files. An exact subtraction of the vector's cardinality is not available: the field is not exposed by the FFI, and the two accessors that could reach it read the deletion-vector file itself, which is the read this shortcut exists to avoid. Failing closed is what IcebergMetadata::totalRows already does when a table has delete files, and what the count-from-files path already does through hasAttachedDeletes. The existing test_deletion_vector assertions use ORDER BY all, which resolves to the count() aggregate and so makes the planner see it twice and decline the optimization, which is why they never reached this path. They are kept as they are, and arms are added for a bare count(), the absence of the trivial-count plan step, each of the two accumulation sites via its log line, system.tables.total_rows, a version-pinned read, and a table without a deletion vector as a control that the optimization still applies there. Closes: ClickHouse#114933 Co-Authored-By: Claude Opus 5 <[email protected]>
…on-vector test The version-pinned arm asserted delta_lake_snapshot_version = 1, which in this fixture is the overwrite that precedes the DELETE, so it read a snapshot with no deletion vector and stayed green with both guards reverted. Enumerating _delta_log shows version 2 is the DELETE: its add entry carries the deletionVector next to "numRecords":4, while 2 rows survive. Pinning that version returned 4 before this fix and returns 2 now, which is what Spark reports for VERSION AS OF 2 and what a scanning query with the same pin already returned. getTotalRows takes no version branch, so the pinned read goes through the same two accumulations as an unpinned one. The test now appends a row after the DELETE, so the version carrying the vector is an older snapshot rather than also being the newest one, and asserts the newest version too, which is over-counted as well because the vector stays on the surviving file. The pre-delete version keeps its arm and gains a plan-step assertion, giving the cluster parametrization a control that the optimization can still apply. The other statistics site had an arm in one direction only. Which site publishes depends on the order of queries rather than on how the table is named: getSnapshotStats caches, and the scan callback fills that cache only when it is empty, so a table that is counted before it is ever scanned always answers from the metadata-only visitor. The existing control counts first, so nothing asserted that the scan callback still publishes a row count, and a callback that published nothing at all would have passed. A second table over the same vector-free data is now scanned first and then asserted for its log line, an exact count, the plan step, and an exact total_rows. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review — 2 rounds, 4 findings, all agreed and fixed before publicationTwo rounds of an internal cold review plus an independent second-model pass, run before this PR was
On finding 1 the arm now pins the version that carries the vector and asserts the count that version On finding 3 the review's own proposed remedy was wrong. It assumed the control was a table function, Verified sound in both rounds and unchanged: both accumulation sites are the complete set One point noted and not treated as blocking: the assertions that identify which accumulation site ran Fix plans and evidence are internal; the resulting arms are all in this PR's test diff. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260821-212300 |
|
cc @kssenii, could you review this? The DeltaLake trivial count answered from the |
|
Workflow [PR], commit [981c78f] Summary: ✅
AI ReviewSummaryThis PR fixes Missing context / blind spots
Final Verdict✅ No blocking issues found in the current diff. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 12 s compile time in total, 7 of them have a recent master baseline. |
| context->total_data_files += 1; | ||
| context->total_bytes += size; | ||
| if (stats && context->total_rows.has_value()) | ||
| if (stats && !has_deletion_vector && context->total_rows.has_value()) |
There was a problem hiding this comment.
@groeneai don't we have any stat that means "number of deleted rows" to calculate total rows with deletion vectors?
There was a problem hiding this comment.
Yes and no: the statistic exists in the format, but not at the seam this code sits on.
add.deletionVector.cardinality ("number of rows the given DV logically removes") is a required field in the log schema, so the number is in _delta_log. What this callback gets, though, is a SharedDvInfo handle from delta-kernel, and the FFI exposes exactly four entry points on it: dv_info_has_vector, selection_vector_from_dv, row_indexes_from_dv, free_kernel_dv_info. grep -c cardinality over contrib/delta-kernel-rs/ffi/src is 0. The field lives on DeletionVectorDescriptor, and DvInfo::deletion_vector is pub(crate) while delta_kernel_ffi is a separate crate from delta_kernel, so the FFI layer cannot reach it either. Upstream main is the same: has_vector, get_selection_vector, get_row_indexes are the only public accessors.
The two reachable routes both open the DV file (get_selection_vector/get_row_indexes -> DeletionVectorDescriptor::read/row_indexes -> storage.read_files). Doing that during metadata processing gives up the point of the trivial-count shortcut, and the strace in #114933 shows that file is not opened today.
One argument against subtracting even with the number in hand: kernel conditions the numRecords guarantee on the DV being absent ("For any file where the deletion vector is not present ... must be present and accurate"), and says that under deletion vectors the stats "may be somewhat outdated". So numRecords - cardinality rests on an accuracy assumption the library explicitly declines to make.
Falling back to a real scan is also what the symmetric engine already does: IcebergMetadata::totalRows returns {} when a snapshot has live delete files, and hasAttachedDeletes does the same on the count-from-files path.
If you do want the exact subtraction, it is reachable: the repo carries its own delta-kernel-rs fork with local ffi patches (free_engine_builder, the set_builder_option error path), so a dv_info_cardinality export plus a pub fn cardinality() on DvInfo is a small addition there. I would rather do that as a separate PR after this one lands than put a contrib bump inside a bug fix, but it is your call.
There was a problem hiding this comment.
@groeneai let's integrate these stats in our code then, if they exist
There was a problem hiding this comment.
Acknowledged, I will implement it.
The number is still not reachable at this seam. At the pinned commit (88ff5a947478), and on upstream main as well, DvInfo exposes only has_vector, get_selection_vector and get_row_indexes, DvInfo::deletion_vector is pub(crate), and grep -c cardinality ffi/src/scan.rs is 0, while DeletionVectorDescriptor::cardinality itself is a public i64. So the route is a cardinality() accessor on DvInfo plus a dv_info_cardinality export in ClickHouse/delta-kernel-rs, then subtracting it in this callback, keeping the bail-out only for files whose handle carries no usable number.
One sequencing constraint: the submodule pin can only move to a commit that exists in ClickHouse/delta-kernel-rs, and I have read access only there, so the fork change needs a PR of its own merged first. My preference is to keep this PR as the fail-close fix, so the wrong count is corrected in the meantime, and put the subtraction on top once the fork side is in. If you would rather ship both together, say so and I will hold this one until the fork change lands. I will post the links here either way.
There was a problem hiding this comment.
Written and measured, but not opened as a PR, and that last part is what I need your call on.
The accessor is DvInfo::cardinality() -> Option<i64> plus a dv_info_cardinality FFI export: +23/-1 in two files, purely additive, Cargo.lock untouched, against ClickHouse/v0.23.0 (our pin is that branch tip, so the pin bump afterwards is a fast-forward). Diff below.
I did not take numRecords - cardinality on trust, since Stats documents the statistics as possibly outdated under deletion vectors. I built ClickHouse against the patch and compared the metadata count against a full scan of the same snapshot across ten deletion-vector shapes. They agreed every time, including the one I expected to break it: successive DELETEs against a single file, where cardinality turns out to be cumulative rather than the last delta. Removing the subtraction made those comparisons disagree.
What I need: I have no push access on ClickHouse/delta-kernel-rs, and that repository's AI_POLICY.md asks that agents not post there unless maintainers configured it, so I would rather not open a PR there on my own initiative. Either take the diff and push it yourself, or tell me to open it from a fork and I will.
One caveat if you take it as it stands. The doc comment I wrote spells out numRecords minus cardinality as the way to get the surviving count, but Stats only promises accuracy when no vector is present, and DvInfo is shared with the CDF scan path, which has no numRecords at all. So that sentence claims more than the kernel does. Before opening a PR there I would cut it back to describing the field and leave the arithmetic to the caller. The code itself does not change.
Also worth knowing whichever way it lands: that fork's ClickHouse/v0.23.0 tip is already red in its own CI (build, test, coverage, ffi_test, format, msrv), and cargo test -p delta_kernel does not compile there with any feature set. Ten #[cfg(test)] closures still return () where visit_scan_files now wants bool (kernel/src/scan/log_replay.rs:1536,1628, plus 8 sites in kernel/src/parallel/parallel_phase.rs). So the accessor's unit assertions cannot run in that CI until those are repaired. I verified them locally with a throwaway repair and kept it out of the change.
This PR is unaffected either way, and the subtraction lands here once the pin moves. Its fail-close already reports the correct count, only without the shortcut.
Kernel-side diff (+23/-1)
diff --git a/ffi/src/scan.rs b/ffi/src/scan.rs
index c6cb752..baaa0be 100644
--- a/ffi/src/scan.rs
+++ b/ffi/src/scan.rs
@@ -481,6 +481,18 @@ pub unsafe extern "C" fn dv_info_has_vector(dv_info: Handle<SharedDvInfo>) -> bo
dv_info.has_vector
}
+/// Number of rows the deletion vector of the [`SharedDvInfo`] logically removes, or `None` if
+/// there is no deletion vector. [`Stats::num_records`] still counts those rows, so the number of
+/// rows that survive in the file is `num_records` minus this value. No deletion vector is read.
+///
+/// # Safety
+/// Engine is responsible for passing a valid `SharedDvInfo` handle.
+#[no_mangle]
+pub unsafe extern "C" fn dv_info_cardinality(dv_info: Handle<SharedDvInfo>) -> OptionalValue<i64> {
+ let dv_info = unsafe { dv_info.as_ref() };
+ dv_info.info.cardinality().into()
+}
+
/// This callback will be invoked for each valid file that needs to be read for a scan.
///
/// The arguments to the callback are:
diff --git a/kernel/src/scan/state.rs b/kernel/src/scan/state.rs
index d7b8036..26168d3 100644
--- a/kernel/src/scan/state.rs
+++ b/kernel/src/scan/state.rs
@@ -48,6 +48,14 @@ impl DvInfo {
self.deletion_vector.is_some()
}
+ /// Number of rows the Deletion Vector of this file logically removes, or `None` if the file
+ /// has no Deletion Vector. [`Stats::num_records`] still counts those rows, so the number of
+ /// rows that survive in the file is `num_records` minus this value. The count comes from the
+ /// log action and needs no access to the Deletion Vector itself.
+ pub fn cardinality(&self) -> Option<i64> {
+ self.deletion_vector.as_ref().map(|dv| dv.cardinality)
+ }
+
pub(crate) fn get_treemap(
&self,
engine: &dyn Engine,
@@ -234,7 +242,7 @@ impl<T> FilteredRowVisitor for ScanFileVisitor<'_, T> {
#[cfg(test)]
mod tests {
use crate::actions::get_commit_schema;
- use crate::scan::state::ScanFile;
+ use crate::scan::state::{DvInfo, ScanFile};
use crate::scan::test_utils::{add_batch_simple, run_with_validate_callback};
#[derive(Clone)]
@@ -257,6 +265,7 @@ mod tests {
);
assert_eq!(scan_file.partition_values.get("non-existent"), None);
assert!(scan_file.dv_info.deletion_vector.is_some());
+ assert_eq!(scan_file.dv_info.cardinality(), Some(2));
let dv = scan_file.dv_info.deletion_vector.unwrap();
assert_eq!(dv.unique_id(), "uvBn[lx{q8@P<9BNH/isA@1");
assert!(scan_file.transform.is_none());
@@ -275,5 +284,6 @@ mod tests {
context,
validate_visit,
);
+ assert_eq!(DvInfo::default().cardinality(), None);
}
}|
Hi @scanhex12, gentle ping: any update on the |
|
@scanhex12 are you continuing to review this, or should we ask @SmitaRKulkarni for help? |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master now reports NULL `total_rows` and `total_bytes` in `system.tables` for every data-lake table (`StorageSystemTables.cpp`, `isDataLake`), so these arms either pass for that reason or fail on the merged head (`total_bytes > 0` reads `\N`). The remaining `count()` and `EXPLAIN` arms still cover both statistics sites in both directions: forcing the scan-callback site to publish no row count turns the `plain_scanned` trivial-count-step assertion red while every deletion-vector arm passes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the delta-kernel source citation from the hasDeletionVector comment; the PR description carries it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review, round 4 (after the master merge)Subject: ✅ The four dropped 💡 Noted, not blocking: the description's |
|
Dear @scanhex12, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
Closes: #114933
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
SELECT count()returning too many rows for a Delta Lake table whose deletes are stored as deletion vectors: the count came from thenumRecordsfile statistics, which still include the removed rows. Closes #114933.Description
On 26.8.18.2 and 26.9.9.28,
SELECT count()over a Delta table withdelta.enableDeletionVectors = truecounts the deleted rows (310 instead of Spark's 260 on the issue's repro): the trivial-count optimization answers from thenumRecordsstatistics in_delta_logand never consults the file's deletion vector. Any query that scans returns the correct answer.TableSnapshotaccumulatestotal_rowsat two places, and both summedstats->num_recordswhile holding the file'sdv_infohandle and ignoring it. delta-kernel documents that statistic as stale under a deletion vector in the same doc comment that namesDvInfo::has_vectoras the flag to consult (kernel/src/scan/state.rs).Both sites now drop
total_rowswhen a file carries a deletion vector, socount()becomes an ordinary scan, which already applies the vector correctly. That is whatIcebergMetadata::totalRowsalready does under delete files. Subtracting the vector'scardinality, which_delta_logrecords, would keep the optimization, but the pinned delta-kernel does not expose that field through its FFI, so that needs a delta-kernel change first.The
delta_lake_snapshot_versiondisagreement the issue also reports has the same cause and is fixed too, sincegetTotalRowsis version-agnostic. On the test fixture, whose vector removes 2 rows, pinning the version that carries the vector returned 4 before and returns 2 now, matching Spark'sVERSION AS OF. A version pinned before the delete keeps the optimization. The issue's other symptom,system.tables.total_rows, already reports NULL for every data-lake table on master since #117584.Extends
test_deletion_vector, whose existing assertions useORDER BY all, which makes the planner see thecount()aggregate twice and decline the optimization, so they never reached this path. New arms cover a barecount(), both accumulation sites, a pinned read of the version carrying the vector, and two controls that the optimization is still applied where no vector is present.Workflow [PR]
Sync PR [sync-upstream/pr/115872]
Version info
26.11.1.1005-master(included in26.11and later)