Repository navigation
Cherry pick #111617 to 26.3: Fix Iceberg trivial count bug - #118574
Conversation
… summary IcebergMetadata::totalRows() returned the total-records hint from the snapshot summary unconditionally. Writers maintain that hint as parent_total + added, so it silently diverges from the actual data when the table history contains a lossy or corrupted commit, making SELECT count() disagree with a full scan of the same table. Derive the count from the manifest list instead: in format v2+ every entry carries added_rows_count/existing_rows_count, whose sum over data manifests is the exact live row count. Fall back to the summary hint only for v1 manifest lists without counts or when delete manifests are present. Log a warning when the summary disagrees with the manifest list.
…ests - Use UInt64 for the manifest-list row counts (review comment), treating negative values as absent since they violate the spec. - Do not fall back to the summary total-records hint when the snapshot has delete manifests: the hint is maintained incrementally by writers and can be corrupted the same way, so go to the manifest scan, which derives both data and position-delete rows from the actual manifests. - Add a stateless test covering position deletes with a corrupted summary: 5 rows, 2 deleted via merge-on-read, total-records corrupted from 5 to 100; count() must return 3, not 98.
The count-from-files cache is keyed only by the file path and its modification time, but Iceberg position/equality delete files and Delta deletion vectors change the number of rows a file contributes without touching the file itself. Both directions are unsafe: - a count cached before a delete resurfaces the deleted rows: an unfiltered read caches the raw row count, ALTER DELETE adds a delete file (data file unchanged, cache key still valid), and the next count() serves the pre-delete number while skipping the delete transformers entirely (04538 returned 10 instead of 8); - a count cached after a delete goes stale in the other direction: the first count() after a delete scans correctly but caches the post-delete count, and after further deletes the next count() serves it again (interoperability test returned 80 instead of 70). This was masked for Iceberg count() queries while totalRows() answered them from metadata; making totalRows() bail out to a real scan for snapshots with delete files exposed it. Files with attached row-level deletes now neither use nor populate the cache. Also add 04614: a fixture with a malformed (negative) added_rows_count in a v2 manifest list on top of a corrupted snapshot summary, proving that malformed manifest-list row counts fall back to the manifest-file scan instead of throwing, trusting the summary, or misreading counts. Co-authored-by: Cursor <[email protected]>
A corrupted manifest file may carry a negative record_count (the field is parsed as a raw Int64), and summing it would make totalRows() return a wrong -- or, after the conversion to size_t, absurdly huge -- count. getRowsCountInAllFilesExcludingDeleted() now reports such counts as unavailable, and totalRows() falls back to a real scan, consistent with how malformed manifest-list row counts are handled: a malformed value disables the count shortcut but never makes the table unreadable and never produces a wrong count. Add 04615: a fixture with both metadata row-count sources malformed (added_rows_count = -1 in the manifest list, record_count = -1 in the manifest file) on top of a corrupted snapshot summary, asserting that count() matches a real scan and the optimization is not applied. Co-authored-by: Cursor <[email protected]>
The test previously only asserted post-delete counts, so a regression in the attached-deletes guard of the count-from-files cache would stay green: no stale cache entry ever existed. Now the cache is primed with the raw per-file row count (5) before the ALTER DELETE, and the post-delete counts run with the cache explicitly enabled. The delete adds a position-delete file without touching the data file (the cache key is only path + mtime), so reusing the pre-delete cached count returns 5 instead of 3 and fails the test. Co-authored-by: Cursor <[email protected]>
needOnlyCount() makes the input format emit synthetic chunks filled with default values. An equality-delete FilterTransform evaluates its predicate against those defaults instead of the real row values, so count() with optimize_count_from_files = 1 returned the raw file row count (or dropped whole files whose default key happened to match a delete predicate -- the source of the 04613 flakiness under randomized settings, where the 1000-row file's default id = 0 was in the deleted set and count() returned 10). Position deletes and deletion vectors filter by row index, which synthetic chunks preserve, but they would still build the synthetic chunks only to drop rows from them. createReader() now demotes need_only_count to a real read for objects with attached deletes, which also subsumes the count-from-cache guard on the read side (the write-side guard in generate() stays: unfiltered non-count reads must not cache post-transform counts either). 04613 pins optimize_count_from_files = 1 on the count queries (a regression there returns 1010 instead of 881) and drops the cache warm-up query, which was a workaround for exactly this flake. Co-authored-by: Cursor <[email protected]>
ClickHouse's Iceberg compaction rewrote the manifest lists of the history through the generateManifestList branch that stamps the snapshot summary's added-records into EVERY entry, with zero existing rows. After OPTIMIZE, a table whose current snapshot references N manifests claimed N times its row count in the manifest list -- the compacted test_optimize table (90 live rows in 2 manifests) claimed 90 + 90 = 180. This was invisible while count() trusted the summary hint and became a correctness bug once count() started using the manifest-list counts. The compaction now records the actual file/row counts of each rewritten manifest and passes them to generateManifestList through the same existing-counts mechanism the manifest consolidation path already uses (the rewritten manifests reference pre-existing data, so the counts are reported as existing). This also fixes min_sequence_number, which was stamped with the new snapshot's sequence number even for manifests whose entries keep older data sequence numbers. Also isolate the 04611/04614/04615 fixtures from each other: all three carried identical internal paths (s3a://test/est/..., inherited from copy-paste), so with the Iceberg metadata caches enabled the parallel test runs poisoned each other -- 04614 was served 04611's healthy manifest list (firing the corrupted-summary warning into stderr) and 04611 was served the malformed one (losing its optimization marker). The two new fixtures now carry their own unique internal locations, and both tests suppress expected warnings like 04611 does. Co-authored-by: Cursor <[email protected]>
Same treatment as total-records in totalRows(): the summary is maintained incrementally by writers (parent total +/- delta), so a corrupted commit in the table history poisons it silently, and a negative value would wrap through std::optional<size_t> into a huge unsigned size in system.tables.total_bytes. totalBytes() now always sums the file-level file_size_in_bytes over the live data files, which is required in all format versions and therefore exact (the previous manifest-scan fallback summed the byte size of a single column per file, which is not the file size at all). A malformed negative size fails closed to 'unknown'. The now-unused total_bytes summary hint is dropped from IcebergDataSnapshot, and a dead getBytesCountInAllDataFilesExcludingDeleted declaration on ManifestFileIterator (never defined) is removed. Co-authored-by: Cursor <[email protected]>
…t counts as added Two fixes: 1. The previous commit removed the unused iterator-level declaration of getBytesCountInAllDataFilesExcludingDeleted from ManifestFileIterator.h but left its out-of-line definition in the .cpp, breaking every build (out-of-line definition does not match any declaration). Remove the definition too; the only caller uses the ManifestFileEntriesHandle variant. 2. Compaction rewrites history manifests without entry lineage, so generateManifestFile emits their data-file entries as ADDED. Writing the per-manifest counts as existing_* in the manifest list therefore contradicted the manifests it points to (added_* = 0 while every entry is ADDED). Generalize ManifestListEntryExistingCounts to ManifestListEntryCounts with an entry_counts_are_added flag: the consolidation path (metadata-only rewrite, entries stay EXISTING) keeps existing semantics, while the compaction data-rewrite path now reports the counts as added_*, keeping manifest-list entries consistent with the ADDED entries in the regenerated manifests. Row-count sums (added + existing) are unchanged. All six touched translation units compile cleanly (clang 22, Debug). Co-authored-by: Cursor <[email protected]>
A single list-wide added/existing flag was wrong for carried-forward manifests: in a history S1(add M1) -> S2(carry M1, add M2), S2's rewritten manifest list reported M1' as added by S2 with S2's added_snapshot_id and sequence_number, contradicting M1's entries (emitted with S1's lineage) and double-counting carried manifests for incremental readers. ManifestListEntryCounts now carries per-entry lineage: a counts_are_added flag plus optional added_snapshot_id / added_sequence_number overrides. Compaction records the owning snapshot for each rewritten manifest; each rewritten manifest list reports a manifest as added_* only in the snapshot that first added it, and as existing_* with the original added_snapshot_id and sequence_number in later snapshots that carry it forward. The consolidation path is unchanged (existing counts, no lineage override). Row-count sums (added + existing) per manifest list are unchanged. All touched translation units compile cleanly (clang 22, Debug). Co-authored-by: Cursor <[email protected]>
… contract The snapshot summary's total-files-size tracks all live table files including position/equality delete files (the write side adds delete_bytes + data_bytes into it). The manifest-scan replacement only summed live data files, so snapshots with live deletes under-reported system.tables.total_bytes relative to correct pre-existing metadata. getBytesCountInAllDataFilesExcludingDeleted is renamed to getBytesCountInAllFilesExcludingDeleted and now sums file_size_in_bytes over data, position-delete and equality-delete live files. The fail-closed behavior for malformed (negative) sizes is unchanged. Co-authored-by: Cursor <[email protected]>
manifest_file_to_first_snapshot is the first *retained* snapshot that references a manifest, which after snapshot expiration is not necessarily the snapshot that added it: the source manifest-list entry can carry an older added_snapshot_id / sequence_number. Deriving lineage from retained history order re-attributed such manifests to a later snapshot, both in the rewritten manifest-list entries and in the regenerated manifest entries, so incremental readers could treat a carried-forward manifest as newly added after OPTIMIZE. The compaction plan now records added_snapshot_id / sequence_number from the source manifest-list entries (available in ManifestFileCacheKey), uses them for the rewritten manifest-list entry counts and lineage, and stamps the regenerated manifest entries with the same lineage via a new user_defined_snapshot_id override in generateManifestFile (paired with user_defined_sequence_number). Existing callers are unaffected. All touched translation units compile cleanly (clang 22, Debug). Co-authored-by: Cursor <[email protected]>
writeMetadataFiles rebuilds table metadata via generateNextMetadata, which renumbers snapshot sequence numbers starting from 1 (snapshot ids are preserved). Copying the source manifest-list entry's sequence_number verbatim into the rewritten manifests therefore produced sequence lineage inconsistent with the rewritten history: a source sequence like 57 would sort the compacted data files as newer than any append/delete committed after OPTIMIZE (which get sequence 2, 3, ...), so those deletes would silently stop applying during delete-span matching. The manifest lineage now keeps only added_snapshot_id (ids are stable across the rewrite) for attribution, and all sequence fields written for rewritten manifests -- entry sequence_number / file_sequence_number, manifest-list sequence_number and min_sequence_number -- use the adding snapshot's *new* sequence number. When the adding snapshot has been expired, the new sequence number of the first retained snapshot referencing the manifest is used: the earliest point in the rewritten history where the manifest exists, which keeps ordering relative to future deletes correct. The consolidation path (writeConsolidatedManifestFile) is untouched: it appends a snapshot to the existing metadata without renumbering, so preserving source sequence numbers there remains correct. All touched translation units compile cleanly (clang 22, Debug). Co-authored-by: Cursor <[email protected]>
A live manifest's first retained reference can be a delete-only snapshot: S1 appends M1, S2 adds only delete files over M1, then S1 is expired. checkIfIcebergHistorySupported accepts that history and manifest_file_to_first_snapshot[M1] = S2, but tryGetAppendUpdate skips delete-only snapshots when generating rewritten snapshots, so snapshot_id_to_snapshot has no entry for S2. The old 'if (!snapshot) continue;' silently dropped such manifests from the rewritten table; in the single-snapshot case the rewrite committed the empty metadata object while clearOldFiles removed the original table files -- data loss. Throw NOT_IMPLEMENTED instead: the exception propagates out of writeMetadataFiles before any metadata commit and before clearOldFiles runs, so OPTIMIZE aborts cleanly and the table is left unchanged. Co-authored-by: Cursor <[email protected]>
Two fail-closed fixes in the OPTIMIZE rewrite path: 1. path_to_data_file was keyed by the containing manifest's path inside the loop over data files, so in a manifest with several live data files only the first got a DataFilePlan; the others aliased it, writeDataFiles rewrote a single file per manifest, and the rest of the manifest's data silently disappeared from the compacted table. The map is now keyed by the data file's own path (one plan per source data file), which still deduplicates the same file referenced from multiple snapshots' lists; per-manifest aggregates remain on ManifestFilePlan. 2. The format-version guard accepted anything >= 2, but writeMetadataFiles rebuilds metadata via createEmptyMetadataFile, which emits format_version 2: a v3 table would be silently downgraded and lose v3-only state such as row lineage (first_row_id / next_row_id). The guard now requires exactly version 2, matching the fail-closed behavior of the MANIFEST-only path. Co-authored-by: Cursor <[email protected]>
…counts The manifest-list per-entry added_rows_count/existing_rows_count are not measured against the data: some writers stamp them from snapshot summary fields. ClickHouse's own generateManifestList copies the summary's added-records into every newly listed entry and zeroes existing_rows_count, so a manifest list rewritten for a compaction snapshot (added-records = 0) describes every manifest as containing zero rows. The manifest-list fast path then returned count() = 0 on a perfectly healthy table (caught by cloud compaction integration tests). Sum the per-data-file record_count from the manifest files instead: the field is required in every format version and written from the actual data files, so the result is exact. Live delete files and negative record_count still bail out to a real scan. The manifest-list row-count parsing became dead code and is removed; the snapshot summary hint is only compared against the computed count to log a warning.
totalBytes(), the manifest-level bytes aggregation and the snapshot's total_bytes summary field are restored to their original implementation; only the row-count path keeps the manifest-file-based calculation. Co-authored-by: Cursor <[email protected]>
Fix Iceberg trivial count bug
|
@groeneai could you please resolve the conflicts? |
|
I cannot push to I reproduced the automation's own merge (base
The read half resolves in one lineThe read side conflict is only an anchoring failure. The fix inserts its block directly above the need_only_count = need_only_count && !hasAttachedDeletes(*object_info);and drop the That hunk has a silent half no-op trap
The compaction half is a missing prerequisite chain, not a resolutionThe struct this PR renames ( Affectedness, for the resolve or drop call26.3 carries the whole read side defect surface ( Options that actually exist
@scanhex12 as the assignee: which do you want? The resolve or drop call on the compaction half really belongs to @ melvynator as the source PR author. Note the automation closes this PR after 7 days of inactivity. |
Original pull-request #111617
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job