Skip to content

Fix Iceberg trivial count bug - #111617

Merged
melvynator merged 22 commits into
masterfrom
fix-iceberg-trivial-count
Aug 3, 2026
Merged

melvynator merged 22 commits into
masterfrom
fix-iceberg-trivial-count

Conversation

@melvynator

@melvynator melvynator commented Jul 23, 2026 •

Copy link
Copy Markdown
Member

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

  • Bug Fix (user-visible misbehavior in an official stable release)

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 Iceberg OPTIMIZE TABLE writing incorrect manifest-list counts and lineage, and make totalBytes metadata robust against corrupted summaries.

Version info

  • Merged into: 26.8.1.693 (included in 26.8 and later)
  • Backported to: 26.7.7.39, 26.6.5.100

… 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.
@melvynator melvynator changed the title Fix Iceberg trivial count Fix Iceberg trivial count bug Jul 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cde7afe]

Summary: ✅


AI Review

Summary

This PR fixes several real count() correctness bugs for Iceberg tables, but the current head still is not safe to merge. The count() path is in much better shape; the remaining problems are in Iceberg compaction and in the reverted totalBytes() logic, where one path still truncates snapshot history and another path can either commit malformed manifest metrics or report permanently wrong table sizes.

Findings

❌ Blockers

  • [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:962-983] OPTIMIZE TABLE still drops delete-only snapshots from the rewritten history. tryGetAppendUpdate returns std::nullopt for position-delete-only overwrites, and writeMetadataFiles then skips both generateNextMetadata and generateManifestList for those snapshots. In S1 append -> S2 delete, the rewritten table keeps S2's row contents baked into the compacted file, but current-snapshot-id falls back to S1, SETTINGS iceberg_snapshot_id = S2 stops working, and timestamp travel to the delete commit disappears. With later appends, rewritten snapshots can also keep parent_snapshot_id = S2 even though S2 was never emitted.
    Suggested fix: either rewrite delete-only snapshots too, or fail closed before commit whenever the retained history contains one.
  • [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:806-810] OPTIMIZE TABLE ... MANIFEST still trusts malformed source metrics and writes them back as unsigned counts. A source record_count = -1 or file_size_in_bytes = -1 is cast to UInt64 here and committed into a brand-new manifest instead of aborting. That turns a readable corrupted table into freshly corrupted metadata produced by ClickHouse itself.
    Suggested fix: validate both metrics are non-negative before filling file_row_counts / file_byte_counts, and throw before writing any rewritten manifest if the source manifest is malformed.

⚠️ Majors

  • [src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp:416-417] The last revert restored summary.total-files-size as an authoritative data source for totalBytes(). createIcebergDataSnapshotFromSnapshotJSON stores it directly into std::optional<size_t> total_bytes, and totalBytes() returns it unconditionally. A corrupted or negative summary value therefore produces permanently wrong system.tables.total_bytes, and a negative one wraps to a huge unsigned size instead of failing closed.
    Suggested fix: restore the manifest-based file_size_in_bytes calculation for totalBytes() and do not store the summary byte count as size_t.
  • [src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp:1199] The fallback totalBytes() path is also wrong on its own terms: it calls getBytesCountInAllDataFilesExcludingDeleted(), whose implementation at ManifestFileIterator.cpp:182-200 iterates only FileContentType::DATA and sums the first available per-column bytes_size, not the file's file_size_in_bytes. So snapshots without summary.total-files-size under-report live delete files and can undercount even plain data files.
    Suggested fix: sum file_size_in_bytes across all live files, not a single column statistic from data files only.
Tests
  • ⚠️ OPTIMIZE TABLE needs a focused regression test with history append -> delete-only overwrite -> append, asserting that after compaction both SETTINGS iceberg_snapshot_id = <delete_snapshot> and timestamp travel to that delete snapshot still work.
  • ⚠️ OPTIMIZE TABLE ... MANIFEST needs a fixture with malformed source metrics (record_count = -1 and file_size_in_bytes = -1) asserting the command throws before committing rewritten metadata.
  • ⚠️ totalBytes() needs coverage for both a corrupted negative summary.total-files-size and a snapshot with live delete files but no byte summary, otherwise the reverted paths can stay green while returning wrapped or under-counted sizes.
Documented surface
  • OPTIMIZE TABLE Iceberg compaction: docs/en/sql-reference/table-functions/iceberg.md:489-499 says compaction preserves previous snapshot IDs and timestamps so time travel keeps working with the same values, and Cloud docs docs/use-cases/data_lake/support-matrix.md advertise Iceberg compaction as an experimental supported feature. Verdict: broken by the current history rewrite, which skips delete-only snapshots and can remove exactly those snapshot IDs from the rewritten metadata.
  • OPTIMIZE TABLE on Iceberg format-version 3: local docs/en/ grep found no full-compaction doc that documents a v2-only restriction for this path; the same local and Cloud compaction docs above describe the feature generically. Verdict: broken by Compaction.cpp:218-219, which now rejects every v3 table without a matching doc update or migration note.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 23, 2026
@scanhex12 scanhex12 self-assigned this Jul 23, 2026
/// 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;

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.

UInt64

}
],
"properties": {
"owner": "divanik",

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.

😄

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.

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;

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

manifest_list_rows += *entry.added_rows_count + *entry.existing_rows_count

?

I think

manifest_list_rows += *entry.added_rows_count

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.

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.

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.

makes sense

@Diskein

Diskein commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

@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:

  • check totals of the summary snapshot
  • correct totals (or just throw) if totals are wrong
  • CHECK TABLE command should also check this totals

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

melvynator commented Jul 24, 2026 •

Copy link
Copy Markdown
Member Author

@Diskein

should we check the data files then?

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

added_rows_count is now required

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 optimize_trivial_count_query and it should probably go to the data files.

WDYT about adding some metadata validation on iceberg tables creation/attaching:
check totals of the summary snapshot
correct totals (or just throw) if totals are wrong
CHECK TABLE command should also check this totals

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

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 new invariant here is that writer-maintained snapshot summaries are not authoritative after a lossy or corrupted commit, but that is still only true for 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.

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

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.

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.

Merged via the queue into master with commit 9203564 Aug 3, 2026
178 checks passed
@melvynator
melvynator deleted the fix-iceberg-trivial-count branch August 3, 2026 16:49
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 3, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @melvynator @scanhex12 — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The body only mentions the corrupted-summary trivial-count case and does not describe the count-from-files delete-aware cache guard, the negative-record_count handling, or the compaction metadata/lineage rewrite (including the per-manifest data-file loss fix).

  • Suggested addition:

    This PR also: (1) disables the count-from-files fast path and its path+mtime-keyed cache for any file with attached Iceberg position/equality deletes or Delta Lake deletion vectors (StorageObjectStorageSource hasAttachedDeletes); (2) fails closed to a real scan on a negative manifest record_count; (3) reworks Iceberg compaction to key DataFilePlan per source data file (previously per manifest, which dropped all but the first data file of each manifest), preserve original manifest lineage / added_snapshot_id, remap sequence numbers onto the renumbered history, and write exact per-manifest row counts into the manifest lists; and (4) restricts compaction to format_version==2 exactly.

Ignore this if the current title/body is intentional.

@scanhex12 scanhex12 added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 7, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 7, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 7, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 7, 2026
Backport #111617 to 26.7: Fix Iceberg trivial count bug
scanhex12 added a commit that referenced this pull request Sep 8, 2026
Cherry pick #111617 to 26.3: Fix Iceberg trivial count bug
PedroTadim added a commit that referenced this pull request Sep 10, 2026
…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]>
PedroTadim added a commit that referenced this pull request Sep 10, 2026
Cherry pick #111617 to 26.6: Fix Iceberg trivial count bug
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 10, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 10, 2026
Backport #111617 to 26.6: Fix Iceberg trivial count bug
thevar1able added a commit that referenced this pull request Sep 10, 2026
Pick up the backport of #111617
(Fix Iceberg trivial count bug), which `05077_iceberg_equality_delete_nullability_mismatch`
depends on.
thevar1able added a commit that referenced this pull request Sep 10, 2026
….3 backport

The test checks `count()` on an Iceberg table with equality deletes, which
depends on #111617 (Fix Iceberg
trivial count bug). That fix cannot be backported to 26.3, see
#118758, so the test fails there
while the code fix itself is unaffected.
thevar1able added a commit that referenced this pull request Sep 10, 2026
Pick up the backport of #111617
(Fix Iceberg trivial count bug), which `05077_iceberg_equality_delete_nullability_mismatch`
depends on.
PedroTadim added a commit that referenced this pull request Sep 15, 2026
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]>
@subkanthi subkanthi mentioned this pull request Sep 16, 2026
11 of 17 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

Iceberg metadata-only count() ignores equality deletes

8 participants