Repository navigation
Fix Iceberg trivial count bug - #111617
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.
|
Workflow [PR], commit [cde7afe] Summary: ✅
AI ReviewSummaryThis PR fixes several real Findings❌ Blockers
Tests
Documented surface
Final VerdictChanges requested. |
| /// status ADDED and EXISTING respectively. Required in format v2+, optional in v1 | ||
| /// (std::nullopt when absent or null). Their sum over all data manifests is the exact | ||
| /// live row count of a snapshot without delete files, see IcebergMetadata::totalRows(). | ||
| std::optional<Int64> added_rows_count; |
| } | ||
| ], | ||
| "properties": { | ||
| "owner": "divanik", |
There was a problem hiding this comment.
Legacy via copy-paste
| if (entry.content_type == Iceberg::ManifestFileContentType::DATA) | ||
| { | ||
| if (entry.added_rows_count.has_value() && entry.existing_rows_count.has_value()) | ||
| manifest_list_rows += *entry.added_rows_count + *entry.existing_rows_count; |
There was a problem hiding this comment.
why
manifest_list_rows += *entry.added_rows_count + *entry.existing_rows_count
?
I think
manifest_list_rows += *entry.added_rows_count
There was a problem hiding this comment.
Because EXISTING manifests are still part of the current snapshot. After the first commit, a snapshot can inherit manifests from earlier snapshots (plain append, manifest-only rewrite, compaction, etc.), and those rows remain live even though they were not newly added in this snapshot. Summing only added_rows_count would undercount every snapshot that carries forward pre-existing manifests.
|
@melvynator we merged some PRs about summary when we do different operations on iceberg tables, and another one on review #109288, with some tests for mutations as well. I think we are testing summary snapshot consistency much better now and the corruption chance by clickhouse is less then before, but what if counters are wrong in manifests lists? should we check the data files then? We would again ended up with broken count. WDYT about adding some metadata validation on iceberg tables creation/attaching:
cc: @scanhex12 |
…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.
I don't think so, the snapshot_summary is an optional field AFAIK (https://iceberg.apache.org/spec/#optional-snapshot-summary-fields) whereas the nb of rows is in the manifest list is mandatory in the spec: https://iceberg.apache.org/spec/#version-2
If these informations are incorrect my assumption would be that the writter is in violation of the spec. if you want to fallback on the data layer then I guess you can disable
That sounds like an expensive operations (especially when you attach a catalog - which could be thousands of table). On the other hand I think the CHECK TABLE for Iceberg table could indeed eventually check for any weirdness and inconsistence in the Iceberg table. |
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]>
| /// Reaching this point means some manifest list row counts are missing (legitimate in | ||
| /// v1 manifest lists, malformed metadata in v2+) or the snapshot has delete manifests. | ||
| /// Either way the snapshot summary hint is not used as a data source: it is maintained | ||
| /// incrementally by writers just like `total-records`, so a corrupted commit in the |
There was a problem hiding this comment.
totalRows. SnapshotSummary::totals.files_size is maintained incrementally in the same parent total +/- delta way, yet createIcebergDataSnapshotFromSnapshotJSON still stores summary.total-files-size directly and totalBytes returns it unconditionally. That is what system.tables.total_bytes / information_schema.tables.data_length read, so the same table can now show a correct count() and a permanently wrong size; a negative total-files-size would also wrap through std::optional<size_t> into a huge UInt64. This path likely needs the same fail-closed treatment, ideally by summing the required manifest file_size_in_bytes values instead of trusting the summary hint.
There was a problem hiding this comment.
Fixed in 4b7d62d: totalBytes() no longer reads the summary hint at all. It always sums the file-level file_size_in_bytes over the live data files -- required in all format versions, so exact -- and fails closed to "unknown" on a malformed negative value instead of wrapping through std::optional<size_t>. Two side findings while doing this: the previous manifest-scan fallback summed the byte size of a single column per file (not the file size at all), now fixed; and the total_bytes summary hint plus a never-defined getBytesCountInAllDataFilesExcludingDeleted declaration on ManifestFileIterator were removed as dead code.
Separately, 416ce3e fixes the writer-side bug this round of CI exposed: compaction rewrote historical manifest lists through the generateManifestList branch that stamps the snapshot summary's added-records into every entry, so a compacted table claimed N x its row count in manifest-list metadata (test_optimize: 180 instead of 90). The compaction now passes the actual per-manifest counts through the same existing-counts mechanism the consolidation path uses.
There was a problem hiding this comment.
This looks reintroduced in the current head. createIcebergDataSnapshotFromSnapshotJSON stores summary.total-files-size back into IcebergDataSnapshot::total_bytes at src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp:416-417, and totalBytes() returns it unconditionally at src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp:1191-1192. That means a corrupted or negative total-files-size again bypasses the manifest scan and can report a permanently wrong or wrapped system.tables.total_bytes.
|
Hi @melvynator @scanhex12 — a couple of suggestions to make this PR easier for reviewers and the changelog reader. Description (currently
Ignore this if the current title/body is intentional. |
Backport #111617 to 26.7: Fix Iceberg trivial count bug
Cherry pick #111617 to 26.3: Fix Iceberg trivial count bug
…ypick/26.6/111617 Resolved the conflicts by keeping only the count() half of #111617. Compaction.cpp, IcebergWrites.cpp and IcebergWrites.h were taken from 26.6: the OPTIMIZE manifest-list count/lineage half of the PR is written against a much newer Iceberg write path (26.6 has no writeConsolidatedManifestFile, and generateManifestFile/generateManifestList take a fraction of the parameters), so cherry-picking it would drag in ~540 lines of unrelated master-only code. The count() half — IcebergMetadata.cpp, ManifestFileIterator.{h,cpp}, Snapshot.h and StorageObjectStorageSource.cpp — is byte-identical to master, as are all five 0461x_iceberg_count_* tests and their fixtures. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Cherry pick #111617 to 26.6: Fix Iceberg trivial count bug
Backport #111617 to 26.6: Fix Iceberg trivial count bug
Pick up the backport of #111617 (Fix Iceberg trivial count bug), which `05077_iceberg_equality_delete_nullability_mismatch` depends on.
Pick up the backport of #111617 (Fix Iceberg trivial count bug), which `05077_iceberg_equality_delete_nullability_mismatch` depends on.
Every build failed on
Compaction.cpp:201: error: unused variable 'data_file_path' [-Werror,-Wunused-variable]
The cherry-pick brought the comment and the declaration of #111617's keying
fix as context of the changed constructor call, but not the code: the three
lookups still used `manifest_file.manifest_file_path`, which the comment right
above them explains makes every data file after the first in a manifest reuse
the first file's plan, so the rest of the manifest's data silently disappears
from the compacted table. 26.6 never received that part of #111617 (#119206
carried only the trivial-count fix), so `-Werror` caught a real hole, not a
stylistic one. Use `data_file_path` for the `contains` check and both map
accesses, which is what `master` does and how the 26.3 backport resolved the
same conflict.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
This is addressing the bug of trivial count mentioned in #92861
When the summary in the snapshot get corrupted by a bad commit it might get out of sync compared to the real count.
Closes: #112347
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Fix
count()on Iceberg tables whose snapshot summary is inaccurate or corrupted: the trivial count optimization now derives exact row counts from the manifest files, and falls back to a real scan when row-level deletes make metadata counts inexact. Also fix IcebergOPTIMIZE TABLEwriting incorrect manifest-list counts and lineage, and maketotalBytesmetadata robust against corrupted summaries.Version info
26.8.1.693(included in26.8and later)26.7.7.39,26.6.5.100