Repository navigation
Fix Iceberg count() on tables whose manifest files over-report row counts - #118942
alexey-milovidov wants to merge 48 commits into
Conversation
…counts `SELECT count()` over an Iceberg table is answered from the metadata: the per-data-file `record_count` is summed over the live data files of the snapshot. That field is required in every format version, but it is not always measured against the data. ClickHouse itself, before #104329 (26.5), stamped the snapshot summary's `added-records` and `added-files-size` into the `record_count` and `file_size_in_bytes` of *every* data file of a manifest it generated, so for a manifest describing N data files the sum comes out N times too large. Tables written by those versions are still out there and cannot be repaired retroactively: SELECT count() FROM icebergS3('https://datasets-documentation.s3.amazonaws.com/lake_formats/iceberg/', NOSIGN) returned 9699757209 for a table of 99997497 rows stored in 97 data files (97 * 99997497), while a real scan of the very same table returns 99997497. The snapshot summary's `total-records` is the only record of that number outside the manifest files, and it is not trustworthy either: it is maintained incrementally, so a single corrupted commit in the table history poisons every later snapshot, which is why #111617 stopped using it as a data source. Neither side can be trusted on its own, but a disagreement between them proves that one of the two is corrupted. Use it as a cross-check and fail closed: when the summary contradicts the manifest files, no metadata-only count is exact, so refuse the trivial count and let the scan count the rows -- for Parquet and ORC data files it reads only the file footers, 1.2 seconds for the table above. The two existing fixtures with a corrupted summary now count from the data files instead of the manifest files; they keep asserting the exact same row count, and no longer assert that the metadata-only optimization is applied. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [3dd4fb1] Summary: ✅
AI ReviewSummaryPR #118942 cross-checks Iceberg manifest row counts against the snapshot summary when the summary cannot answer the count directly. It also makes Final Verdict✅ Approve |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes24 object files changed (+60.82 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units126 translation units recompiled, 1296 s compile time in total, 126 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
…ata-cross-check # Conflicts: # src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp # src/Storages/ObjectStorage/DataLakes/Iceberg/Snapshot.h
The test relied on `iceberg_insert_max_rows_in_data_file = 1` to spread the three rows of a single `INSERT` over three data files, but the runner that enables `async_insert` collapsed them into one data file, and patching the first manifest entry from 1 to 3 then failed with "data_file.record_count is 3, expected 1". Each row is now its own `INSERT` with `async_insert` disabled, so the number of data files depends neither on randomized block sizes nor on asynchronous batching. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118942&sha=96b667227b2cd5c143740b4eba33941a95b07144&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20AsyncInsert%2C%20s3%20storage%2C%20parallel%29 PR: #118942 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…w count is unknown `IF EMPTY` was implemented as `if (auto rows = table->totalRows(context); rows > 0) throw`, so a storage that cannot report its row count from metadata was dropped as if it were empty. That has been the behavior of every storage without `totalRows` since the clause was introduced, and this PR would have extended it to Iceberg tables whose manifest files and snapshot summary disagree: `totalRows` now withholds the count there, and with `iceberg_delete_data_on_drop = 1` the drop also removes the data files. An unknown row count is not an empty table: when the storage reports no count, the table is read until the first row comes out, without requiring `SELECT` on it, and the drop is refused if one does. The `02888` case that pinned the opposite for a never resolved table function proxy is updated: the emptiness check now resolves the proxy, finds the rows of the `Memory` table behind it and refuses, leaving those rows untouched either way. The Iceberg test asserts the refusal for all three fixtures, in particular for the two whose metadata-only count is unavailable, and the new `05223` test covers a `File` table with rows (refused) and an empty view (dropped). PR: #118942 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
📊 Cloud Performance Report 🟢 AI verdict: This PR changes two things: how DROP/TRUNCATE/DETACH ... IF EMPTY decide whether a table is empty (access check first, unknown row count refuses the drop, lazy-loaded targets get loaded), and a new cross-check of the Iceberg metadata-only row count against the snapshot summary. Neither runs during ClickBench or TPC-H SELECT queries. ClickBench Q20 shows a clear -42.7% speedup, from 220 ms to 126 ms, with CPU time cut by about half and the result well below master's recent range of 213-236 ms. The rule for large, clear changes requires the verdict to stay as reported, but this diff cannot explain it, so the likely cause is a newer merge base or another change outside this diff. Re-check it against an exact-base baseline before crediting this PR. Q33 (-6.3%) and Q34 (-5.6%) are borderline, not_sure results on queries whose master history is noisy, and they are unrelated to this change. clickbench🟢 1 improved · Flagged queries (3 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…ead of reading the table The fallback read added in the previous commit answered "does the caller see a row" (row policies and `additional_table_filters` still applied under `ignoreAccessCheck`), consumed messages from stream-like engines such as `Kafka`, and ran before the drop privilege check, turning `IF EMPTY` into an emptiness oracle on unreadable tables. Now an unknown `totalRows` refuses the drop (fail closed), a plain view is still dropped because it stores no rows, and the drop privilege is checked before emptiness is looked at. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…at hides every row Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ata-cross-check Conflict resolution: master (#123267) returned the summary-based trivial count for Iceberg: `IcebergMetadata::totalRows` answers from `IcebergDataSnapshot::getTotalRows` when the snapshot summary provides a usable count. Keep that design, and keep this PR's cross-check of the snapshot summary's `total-records` only on the fallback path that sums the manifest files. Accept the deletion of `04611_iceberg_count_ignores_corrupted_snapshot_summary` and `04614_iceberg_count_malformed_manifest_row_counts` from master.
…sed count Master (#123267) answers the trivial count from the snapshot summary when it provides a usable row count, so a table whose manifest files over-report the per-file `record_count` is now counted from the summary, with the optimization applied. Drop the corrupted-summary case, which master deliberately no longer guards against. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s with a `TO` table `DROP`/`TRUNCATE ... IF EMPTY` on a temporary table went to `executeToTemporaryTable`, which ignored `IF EMPTY` and dropped or truncated the table unconditionally; it now checks the emptiness like the ordinary-table path. A materialized view with a `TO` table keeps no rows of its own and its drop does not touch the target table, so it is treated as empty, like a plain view. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The merge with master committed wrong contents for `04823_logsql_ignore_error_recovery.reference` and `05258_aggregation_single_level_result_fanout_query_shapes.reference`, which this PR does not touch. Restore them to the versions from master. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp
Dropping or detaching an `Alias` only removes the alias itself, so it holds no rows of its own. It used to be judged by `totalRows` of the target, so a non-empty target, or one with an unknown row count, refused the drop with `TABLE_NOT_EMPTY`. `TRUNCATE` of an alias truncates the target, so `TRUNCATE ... IF EMPTY` is still judged by the target. Addresses review: #118942 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since master answers the trivial `count` from the snapshot summary whenever it provides a usable row count, the existing cases of `05264_iceberg_count_manifest_record_count_overreports` pass on master too, so the bugfix validation reported that the test does not reproduce the bug. Add a case where the summary has no delete totals: then the per-file `record_count` of the manifest files is summed, and the cross-check against `total-records` has to refuse the over-reported sum. Co-Authored-By: Claude Opus 5.5 <[email protected]>
In a `lazy_load_tables = 1` database an unloaded table is a `StorageTableProxy`, whose `totalRows` is unknown until it is loaded. Since an unknown row count now refuses the drop, `DROP TABLE IF EMPTY` of an untouched empty table threw `TABLE_NOT_EMPTY`. Resolve the stand-in with `resolveStorageProxyLoading` first. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…CH` and `TRUNCATE` Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118942&sha=latest&name_0=PR ( |
|
Same failure as the one I answered above, on the new head: The fix is #123121 (mine, open). The master failures continue because it is not merged yet. CI on its latest head finished with no failures caused by it, and it is waiting for review. |
… `Alias` * `DROP` / `DETACH ... IF EMPTY` treat any `StorageTableFunctionProxy` as holding no rows, resolved or not: they only remove the table from the catalog. Before, a table function resolved by a read was judged by the rows of its source (e.g. a `merge` table became `TABLE_NOT_EMPTY`). * The access check of `IF EMPTY` requires only `DROP TABLE` for a table function, as the drop itself does: `StorageTableFunctionProxy::isView` does not resolve the table function. * `TRUNCATE ... IF EMPTY` of an `Alias` probes the target it has just authorized directly instead of re-entering `StorageAlias::totalRows`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118942&sha=225355e8cd358369f5355a8e7058f9ec159607dd&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 ( |
|
The fix is in progress: my open #125043. #123121 does not cover it. I ran the failed query from Reduced: UPDATE t_lwu_cte_in_ignore SET v = 256
WHERE ignore(id, id NOT IN (WITH c AS MATERIALIZED (SELECT number AS x FROM numbers(1)) SELECT a.x FROM c AS b, c AS a GROUP BY ALL LIMIT -417, 100));The trigger is the negative offset ( |
…n by its storage Dropping a resolved `StorageTableFunctionProxy` forwards the drop to the nested storage, and an Iceberg storage deletes the table's files on drop when `iceberg_delete_data_on_drop` is enabled in the server settings. So `DROP ... IF EMPTY` of a resolved table function is now judged by the row count of the resolved storage (with the same rules for wrappers such as `Merge`), instead of going ahead unconditionally. An unresolved table function is still dropped without resolving it, and `DETACH` still goes ahead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ble functions metadata-only, authorize temporary alias targets Dropping a resolved `StorageTableFunctionProxy` forwards the drop to the resolved storage, but only a data lake storage can delete data on drop (an Iceberg table with `iceberg_delete_data_on_drop`). So `DROP ... IF EMPTY` of a resolved table function is judged by the resolved storage only when it is a data lake; for `url`, `file`, `postgresql`, `merge`, ... it only removes the table from the catalog and goes ahead, as before the table function was resolved. `TRUNCATE TABLE ... IF EMPTY` of a temporary `Alias` now checks the `TRUNCATE` grant on the target before the emptiness probe looks at (and loads) the target, and probes the authorized target, as already done for ordinary aliases. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The bugfix validation check requires every new test to fail on master, and `05338` passed there, because master drops any table whose row count is unknown. Also check that the `File` source table of the `Merge` table, which does not know its row count, is refused by `DROP TABLE IF EMPTY`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… `table_engines_require_grant` The CI test configuration enables `table_engines_require_grant`, so the test user could not even create the temporary `Alias` table: every probe returned `ACCESS_DENIED` from `CREATE`, and the test did not reach `TRUNCATE ... IF EMPTY`. Grant `TABLE ENGINE ON Alias` to the test user. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118942&sha=c885b41a7d90c30c5739fa80c17c73d6630bcc43&name_0=PR&name_1=Fast%20test #118942 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged master and fixed the Fast test failure of |
…ATE ... IF EMPTY` probes the target An `Alias` can refer to another `Alias` (created while its target name was absent), so checking the `TRUNCATE` grant only on the first target let `isTableEmpty` load and count the final table before `StorageAlias::truncate` checked the grant on it. Walk the whole chain, checking the grant on every hop, and refuse `IF EMPTY` on a cyclic chain, which has no final table. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n by whether its drop may delete data `isDataLake` does not tell whether dropping a storage deletes its data: the `Hudi` and `Paimon` storages are data lakes, but their drop is metadata-only and they cannot report a row count, so after a read resolved a `hudi` or `paimonLocal` table function, `DROP TABLE ... IF EMPTY` refused it with `TABLE_NOT_EMPTY`. Add `dropMayDeleteData` to `IDataLakeMetadata` (true for Iceberg, whose drop deletes the files with `iceberg_delete_data_on_drop`), the object storage configuration and `StorageObjectStorage` / `StorageObjectStorageCluster` (also true with a catalog), and consult the resolved storage only when it is true. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The storage it inspects is the one a table function was resolved to, which is created by the table function itself rather than handed out by `DatabaseCatalog`, so it is never a `StorageTableProxy` stand-in: mark the cast with `NOLINT(storage-cast)`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov
left a comment
There was a problem hiding this comment.
I don't like the premise.
Closes: #92861
Related: #111617
Related: #104321
SELECT count()over an Iceberg table is answered from the metadata: the per-data-filerecord_countis summed over the live data files of the snapshot. That field is required in every format version, but it is not always measured against the data. ClickHouse itself, before #104329 (26.5), stamped the snapshot summary'sadded-recordsandadded-files-sizeinto therecord_countandfile_size_in_bytesof every data file of a manifest it generated, so for a manifest describing N data files the sum comes out N times too large. Tables written by those versions are still out there and cannot be repaired retroactively:returns
9699757209on master for a table of99997497rows stored in 97 data files (97 × 99997497 = 9699757209), while a real scan of the very same table returns99997497. Its single manifest file has 97 entries, and every one of them claimsrecord_count = 99997497andfile_size_in_bytes = 11230919160— the table-wide totals.Since then, master (#123267) answers the trivial count from the snapshot summary (
total-recordsminustotal-position-deletes, when there are no equality deletes) whenever the summary provides a usable count, which also covers the table above. This PR keeps that design and adds a cross-check on the remaining path, where the summary does not provide a usable count and the per-filerecord_countof the manifest files is summed: when the summary'stotal-recordsis present and contradicts that sum, one of the two is corrupted, sototalRowsrefuses the trivial count and the rows are counted from the data files instead (for Parquet and ORC data files only the footers are read,optimize_count_from_files).totalRowsis also whatDROP TABLE ... IF EMPTYconsulted, asif (rows > 0) throw, so a storage that reported no count was dropped as if it were empty — for every storage without a metadata row count since the clause was introduced, and it would have applied to the Iceberg tables above (withiceberg_delete_data_on_drop = 1, deleting their data files). An unknown row count is not an empty table:IF EMPTYnow refuses the drop when no count is reported (a plain view, which stores no rows, is still dropped, and so is anAlias, whose drop removes only the alias;TRUNCATE ... IF EMPTYof an alias is judged by its target). The table is deliberately not read to find out: a read would see the caller's row policies rather than the table, and would consume messages from stream-like engines such asKafka. The drop privilege is now checked before emptiness is looked at, soIF EMPTYdoes not tell a user who may not drop a table whether it is empty.Tests
05264_iceberg_count_manifest_record_count_overreports— new: writes a table of three single-row data files, rewrites therecord_countof a manifest entry to the table total (the shape of the corruption above) with a schema-driven in-place Avro patch, and checks thatcount()returns 3 with the optimization enabled and disabled, and thatDROP TABLE IF EMPTYrefuses each fixture. A third fixture also drops the delete totals from the snapshot summary, so the summary provides no usable count and the manifest sum has to be refused by the cross-check (this case fails on master).05265_drop_table_if_empty_unknown_row_count— new:DROP TABLE IF EMPTYon aFiletable is refused with and without rows, on a plain view it goes ahead.05266_drop_table_if_empty_checks_access_first— new: withoutDROP TABLE,IF EMPTYanswersACCESS_DENIEDfor an empty and a non-empty table alike.05320_drop_table_if_empty_temporary_and_to_view— new:DROP/TRUNCATE ... IF EMPTYrefuses a non-empty temporary table (it used to drop it unconditionally), and a materialized view with aTOtable, which keeps no rows of its own, is dropped.05331_drop_table_if_empty_alias— new:DROP TABLE IF EMPTYof anAliasremoves only the alias, so it goes ahead whatever the target holds, whileTRUNCATE TABLE IF EMPTYof an alias is judged by the target.05332_drop_table_if_empty_lazy_load_tables— new: in alazy_load_tables = 1database, an empty table that has not been loaded since the database was attached is dropped byIF EMPTY, a non-empty one is refused.05333_drop_table_if_empty_lazy_load_alias_and_mv— new: same for storages that report the row count of their target:TRUNCATE TABLE IF EMPTYof anAlias, andDROP TABLE IF EMPTYof a materialized view with an inner table.05385_drop_table_if_empty_unresolved_table_function— new: a never resolved table function is still removed byDROP/DETACH ... IF EMPTYwithout resolving it (it only removes the table from the catalog), whileTRUNCATE ... IF EMPTYrefuses it; a resolvedfiletable function, whose storage keeps the data on drop, is dropped as well.05386_drop_table_if_empty_resolved_iceberg_table_function— new:DROP TABLE IF EMPTYof a resolvedicebergLocaltable function over a non-empty table is refused and the files stay (dropping a resolved table function forwards the drop to its storage, which deletes the data withiceberg_delete_data_on_drop);DETACH ... IF EMPTYstill goes ahead.05401_drop_table_if_empty_temporary_alias_truncate_access— new:TRUNCATE TABLE IF EMPTYof a temporaryAliaschecks theTRUNCATEgrant on the target before looking at it.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
SELECT count()returning more rows than an Iceberg table actually has when its manifest files report the table-wide row count for every data file, which is how ClickHouse itself wrote manifests before 26.5. When the snapshot summary provides no usable row count and itstotal-recordscontradicts the row count described by the manifest files, the metadata-only count is now refused and the rows are counted from the data files.DROP TABLE ... IF EMPTYno longer drops a table whose row count the storage cannot report from metadata: the drop is refused. It also checks the drop privilege before looking at the table, and it is now honored for temporary tables.Workflow [PR]
Sync PR [sync-upstream/pr/118942]