Skip to content

Delete Iceberg table files on DROP with iceberg_delete_data_on_drop - #109071

Open
groeneai wants to merge 24 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-drop-cleanup-108524
Open

groeneai wants to merge 24 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-drop-cleanup-108524

Conversation

@groeneai

@groeneai groeneai commented Jul 1, 2026 •

Copy link
Copy Markdown
Collaborator

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 into CHANGELOG.md):

Fixed DROP TABLE on an Iceberg table with iceberg_delete_data_on_drop = 1 not deleting the table's files, which made re-creating a table at the same path fail with TABLE_ALREADY_EXISTS.

Description

Closes: #108524

Since at least v25.9, DROP TABLE with iceberg_delete_data_on_drop = 1 kept the files. Two bugs:

  1. IcebergMetadata::drop passed the table path as both the listing base and the prefix, so it matched nothing. Tables can share a location, so it now deletes only the files reachable from the table's metadata (collectReachableFiles), plus the metadata files with the same table-uuid that metadata-log misses. In a Replicated database only the replica that receives the DROP deletes files, and nothing is deleted when no metadata file, or not the latest one, carries the table's table-uuid.

  2. drop() runs in a background pool and read iceberg_delete_data_on_drop from the global context, always false. The query settings are now captured in checkTableCanBeDropped, which DatabaseDataLake::dropTable replays on its fresh instance.

Data and delete files from the manifests are deleted first, then the catalog entry (Glue), then the metadata, so a failed DROP stays retryable. REST catalogs (S3 Tables too) and Unity are asked to purge instead; Unity refuses a setting contradicting the table's managed/external type, and Hive cannot drop tables, both before anything is deleted. Known residuals: a DROP failing midway is not atomic, so a Glue table, or an Atomic one restored by UNDROP during the retry, can miss deleted files; a table not read since ATTACH deletes the table currently at its path, the one its SELECT reads; and a restart before an Atomic database's delayed drop keeps the files, as before.

Tests: 04365 (setting on and off, re-create, leftover version hint, a table inside its directory, a new table or another table's metadata at the path, a table not read since ATTACH) and 04366 (failure handling, also with Avro data and on a retry) fail without the fix. test_database_iceberg (two tables at one location too), test_database_glue and test_database_unity_v2 cover catalogs.


Workflow [PR]
Sync PR [sync-upstream/pr/109071]

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a real server: SET iceberg_delete_data_on_drop=1; CREATE TABLE t ... ENGINE=IcebergLocal('<user_files>/t/'); DROP TABLE t SYNC; leaves t/metadata/v1.metadata.json on disk, and re-CREATE at the same path fails with Code: 57 TABLE_ALREADY_EXISTS. (clickhouse-local does not exercise it: its async drop never runs before the process exits, so a real server + DROP ... SYNC is required.)
b Root cause explained? Two bugs. (1) IcebergMetadata::drop called listFiles(os, table_path, table_path, ""); listFiles keys on path / prefix, so it listed table_path/table_path and matched nothing. (2) StorageObjectStorage::drop runs in a background pool and read iceberg_delete_data_on_drop from the global context, where it is always the default false, so the deletion block never ran even after fixing (1).
c Fix matches root cause? Yes. (1) prefix changed to "" so the whole table path is enumerated (matches the create/Hudi callers). (2) the setting is captured from the query context in checkTableCanBeDropped and applied to the context passed to the background drop. No symptom band-aid.
d Test intent preserved / new tests added? New regression test 04365_iceberg_delete_data_on_drop_108524 added: setting-on removes files and allows re-create at the same path; setting-off (default) leaves files in place.
e Both directions demonstrated? Yes, via the real clickhouse-test runner. Unfixed binary: [ FAIL ] (clean 2-line diff: drop on: table path NOT empty, recreate at same path: failed). Fixed binary: [ OK ] 10/10.
f Fix is general across code paths? Yes. Both DROP paths use one storage instance: the self-managed engine path (Iceberg/IcebergLocal, background dropTableFinally -> drop()) and the DataLakeCatalog DB path (DatabaseDataLake::dropTable -> table->drop()) are both preceded by InterpreterDropQuery calling table->checkTableCanBeDropped(query_context) on the same object, so the captured value is honored by both.
g Fix generalizes across inputs? The setting is a plain Bool; both values are covered by the test (on -> delete, off -> keep). The listFiles prefix fix is path-shape independent (empty prefix lists everything under the table path regardless of partitioning/format).
h Backward compatible? Yes. iceberg_delete_data_on_drop default is unchanged (false); the off path leaves files exactly as before (verified). No settings-history / on-disk / wire-format change.
i Invariants and contracts preserved? Yes. checkTableCanBeDropped remains a non-throwing "can always be dropped" hook (only sets a mutable flag, like StorageNATS/StorageRabbitMQ). For non-datalake StorageObjectStorage engines configuration->drop() is the base no-op, so passing the extra setting through the copied context is inert.

Session id: cron:clickhouse-worker-slot-5:20260701-133700

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @divanik — could you review this? It fixes DROP TABLE not deleting Iceberg files under iceberg_delete_data_on_drop=1 (issue #108524): IcebergMetadata::drop passed the table path as both the listFiles base and prefix (so it listed table_path/table_path and matched nothing), and StorageObjectStorage::drop read the setting from the global context (always default false) since the drop runs in the background. The value is now captured in checkTableCanBeDropped and honored by the background drop.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8480ef5]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR makes iceberg_delete_data_on_drop effective, deletes files selected through Iceberg metadata, and delegates purge to supporting catalogs. Reviewed head 8480ef50195b3f17cf82b1f6e94ff00ab1f536e7, the full diff, and all prior discussion. The latest allocation-ordering and root-validation findings are fixed; their threads were resolved. Six earlier concerns remain in the current code, including the explicitly accepted residuals identified below. No duplicate inline findings were posted.

Missing context / blind spots
  • ⚠️ No built ClickHouse binary is available in this checkout, so the failure traces below were verified from source without local runtime reproduction. The retrieved Praktika report reports no failed tests; the specific remaining cases need the focused coverage described below.
Findings

❌ Blockers

  1. Cleanup can delete a replacement table after lazy attachment. StorageObjectStorage.cpp:1265 initializes metadata at deletion time. After attaching A without reading it, replacing its remote files with B, then dropping A, initialization adopts B's UUID; both ownership checks compare B with itself and delete B. Suppressing secondary DDL replay does not protect the initiating server or a standalone Atomic database. Persist an independent identity or skip destructive cleanup when it cannot be established. [dismissed by author -- https://github.com/Delete Iceberg table files on DROP with iceberg_delete_data_on_drop #109071#discussion_r4316648697] The current code still obtains the purported original identity from the replacement files. The related UUID-less case also remains: two absent UUIDs compare equal at IcebergMetadata.cpp:2325 and :2363, which cannot establish ownership between distinct version 1 tables. [dismissed by author -- https://github.com/Delete Iceberg table files on DROP with iceberg_delete_data_on_drop #109071#discussion_r4330562571] Keeping cleanup when both UUIDs are absent preserves this ambiguity.

  2. A failed Glue drop can leave a visible table with deleted rows. IcebergMetadata.cpp:2404 deletes data before dropFromCatalog at line 2421. A subsequent data-delete failure or Glue catalog failure propagates under CatalogRetry, leaving the catalog entry and manifests referencing missing data. Retaining metadata permits another drop attempt but does not keep the live table intact. Use a durable cleanup flow after catalog removal, or another transition that prevents the damaged table from remaining available. [dismissed by author -- https://github.com/Delete Iceberg table files on DROP with iceberg_delete_data_on_drop #109071#discussion_r3830683549] The acknowledged partial-drop corruption remains reachable on the Glue path.

  3. UNDROP can restore an Atomic table after irreversible cleanup. IcebergMetadata.cpp:2261 propagates all AsyncRetry failures. If data deletion succeeds and a later step fails, DatabaseCatalog::dropTablesParallel requeues the table. DatabaseCatalog::undropTable accepts that entry without checking whether cleanup started, so it restores a table referencing missing files. Mark cleanup as irreversible before the first deletion and reject recovery thereafter while retaining cleanup retries. [dismissed by author -- https://github.com/Delete Iceberg table files on DROP with iceberg_delete_data_on_drop #109071#discussion_r4313270841] The thread was resolved without a change preventing this recovery path.

  4. An unknown delete outcome is still treated as safe to roll back. IcebergMetadata.cpp:2293 only logs a failing existence probe. If the first S3 delete succeeds remotely but loses its response, and the probe also fails, any_object_deleted remains false and the original exception escapes. DatabaseMemory and DatabaseOnDisk then reattach a table with missing data. Treat an unverified outcome as irreversible or move deletion beyond the rollback boundary. [dismissed by author -- https://github.com/Delete Iceberg table files on DROP with iceberg_delete_data_on_drop #109071#discussion_r3536306209] S3::objectExists still throws on transport/service errors, and this catch still leaves the rollback flag false.

⚠️ Majors

  1. Valid version 1 metadata can make cleanup retry indefinitely. SnapshotFilesTraversal.cpp:191 unconditionally reads current-schema-id for populated snapshots. Version 1 permits that field to be absent, and the existing schema parser has a schema.schema-id path for that representation. The new drop caller has no version restriction, so such metadata causes a deterministic exception; an Atomic cleanup keeps retrying and DROP TABLE ... SYNC cannot complete. Resolve the schema through the version-aware parser. Existing unresolved finding.

  2. The asynchronous drop loses its query settings across restart. StorageObjectStorage.cpp:1222 stores the cleanup intent only in memory. Restart recovery constructs a new storage from the dropped table's original creation metadata, without calling checkTableCanBeDropped; dropImpl consequently uses global settings. With the default global value, a requested cleanup is silently skipped and the files still prevent recreation at the same path. Persist the intent or complete the requested cleanup synchronously. [dismissed by author -- https://github.com/Delete Iceberg table files on DROP with iceberg_delete_data_on_drop #109071#discussion_r3511667841] The documented limitation still violates the requested cleanup behavior on the default asynchronous lifecycle.

Tests
  • ⚠️ Extend the existing attachment/path-reuse coverage to attach A, replace its files with B, and drop A without an intervening read; B must remain readable.
  • ⚠️ Cover a Glue failure after a successful data deletion, an UNDROP during an Atomic cleanup retry, and a delete whose response and subsequent existence probe both fail. These must not expose a partially deleted table.
  • ⚠️ Add a populated version 1 fixture without current-schema-id, and a restart between an asynchronous drop and its cleanup. Verify cleanup completes and the requested deletion intent survives.
Final Verdict

Status: ❌ Block

Prevent deletion of another table and restoration/exposure of partially deleted tables. Address or explicitly track the version 1 cleanup and restart-durability gaps. Previously dismissed concerns remain confined to this summary; their inline threads were not reopened or repeated.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 1, 2026
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up commit 5e56bda extends the fix to the DataLakeCatalog path (per the bot review). Pre-PR validation gate for the follow-up:

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. DROP TABLE demo.\ns.t`withiceberg_delete_data_on_drop=1on a DataLakeCatalog (REST) table leaves the S3 files 100% of the time. Covered by new integration testtest_database_iceberg/test.py::test_drop_table_delete_data`.
b Root cause explained? DatabaseDataLake::dropTable re-fetches a fresh StorageObjectStorage via tryGetTable and calls drop() on it, so (1) the mutable delete_data_on_drop flag (set only by checkTableCanBeDropped) stays default false, and (2) that instance's data lake metadata was never initialized, so configuration->drop() sees current_metadata==nullptr and no-ops. Both must hold for files to be deleted.
c Fix matches root cause? Yes. (1) Call checkTableCanBeDropped(context_) on the instance dropTable operates on (context_ is the query context, matching InterpreterDropQuery). (2) In StorageObjectStorage::drop(), lazy-init the data lake metadata when about to delete data so configuration->drop() runs. Directly targets both mechanisms in (b), no band-aid.
d Test intent preserved / new tests added? New integration test added asserting both directions (setting on -> S3 files removed; setting off -> files kept). Existing test_drop_table and the self-managed stateless test 04365_iceberg_delete_data_on_drop_108524 unchanged and still pass.
e Both directions demonstrated? Yes. New test FAILS with each fix alone (assert 7 == 0) and PASSES only with both fixes present. Verified locally on Build-ID-checked binaries; also re-confirmed the setting-off control keeps files.
f Fix is general across code paths? The tryGetTable-then-drop pattern is unique to DatabaseDataLake among DB engines (Atomic/OnDisk/Replicated reuse the same instance). Self-managed path already worked; the fix is scoped to the one broken path. Not a symptom guard: it restores the exact precondition (checkTableCanBeDropped + initialized metadata) the working path already has.
g Fix generalizes across inputs? IcebergMetadata::drop reads the table path from configuration->getPathForRead().path and enumerates via object storage, independent of column types/wrappers. The lazy-init is gated on isDataLakeConfiguration(), so it applies uniformly to Iceberg catalog tables (the family with a data-delete path).
h Backward compatible? Yes. No setting default, format, or metadata change. iceberg_delete_data_on_drop default stays false; a plain DROP keeps its prior no-op behavior (lazy-init is gated on delete_data_on_drop, so it does not newly touch object storage).
i Invariants and contracts preserved? lazyInitializeIfNeeded is a no-op when current_metadata != nullptr (self-managed drop unaffected). It reads metadata JSON from S3, which catalog->dropTable (purgeRequested=False) does not remove, so init-after-catalog-drop is safe. checkTableCanBeDropped only sets a mutable bool; no new locks or ordering.

Session id: cron:clickhouse-worker-slot-8:20260701-155000

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 4e31967

CI has fully finished (Mergeable Check completed). Every failure below has an owner; only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, s3 storage, parallel, 2/2) transient job-level ERROR (exit 125, results: []) a fix task is created (investigating at full effort; fixing-PR link to follow here)
CH Inc sync — CH Inc sync (private, not actionable by us)

Notes:

Session id: cron:our-pr-ci-monitor:20260701-210000

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the parallel-replicas catalog-drop fix (commit 0f251a6):

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. test_drop_table_delete_data_parallel_replicas fails deterministically without the fix: DROP TABLE ... SETTINGS iceberg_delete_data_on_drop=1, parallel_replicas_for_cluster_engines=1, enable_parallel_replicas=2, cluster_for_parallel_replicas='cluster_simple' leaves the catalog entry (assert 1 == 0) and the S3 files behind.
b Root cause explained? With parallel replicas usable, tryGetTableImpl returns a StorageObjectStorageCluster. That class (via IStorageCluster) overrides neither checkTableCanBeDropped nor drop, so both resolve to the empty IStorage defaults (IStorage.h:453, :649). dropTable therefore made no catalog call and never captured iceberg_delete_data_on_drop, so the drop was a full no-op.
c Fix matches root cause? Yes. dropTable now calls tryGetTableImpl(..., skip_cluster_wrapper=true), returning a real StorageObjectStorage that implements both methods. Targets the exact mechanism (wrapper lacks DDL overrides), not a symptom.
d Test intent preserved / new tests added? New integration test test_drop_table_delete_data_parallel_replicas added, asserting catalog-entry AND S3-file removal under parallel replicas. Existing test_drop_table / test_drop_table_delete_data unchanged and still pass.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Without fix (f9aad182…): FAIL (assert 1 == 0). With fix (c3ef47bf…): PASS (24s). Existing drop tests: 2 passed (57s).
f Fix is general across code paths? dropTable is the only DDL method on DatabaseDataLake that acts on a tryGetTable-fetched storage (createTable/renameTable/alterTable are not overridden here). Read paths keep skip_cluster_wrapper=false, so distributed SELECT via the cluster wrapper is unaffected.
g Fix generalizes across inputs? The wrapper-vs-real-storage dispatch is independent of table datatypes/formats. Covered both settings states: on -> files removed; off (default) -> the earlier test_drop_table_delete_data proves the plain-drop no-op is preserved. The parallel-replicas branch is gated purely on the parallel-replica settings, which the new test exercises directly.
h Backward compatible? Yes. No setting default, on-disk/wire format, or metadata change. skip_cluster_wrapper defaults to false, preserving prior behavior on every existing caller; only the internal DROP path opts in.
i Invariants and contracts preserved? Yes. StorageObjectStorage is exactly the storage IcebergMetadata/catalog operations are written against; the cluster wrapper is a distributed-SELECT execution object with no drop semantics, so routing DROP to the real storage restores the intended contract rather than weakening it. No locking or block-structure invariants are touched.

Session id: cron:clickhouse-worker-slot-1:20260701-212300

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

The Stateless tests (amd_tsan, s3 storage, parallel, 2/2) job-level ERROR (exit code 125, empty results) on this PR is not caused by this PR's changes. It is a praktika watchdog bug that hangs the job into its 9000s timeout: TeePopen._check_timeout ran the cleanup command and returned without signalling the launched process group, and the cleanup's docker rm -f container name was derived from the pre-parametrized job name so it never matched the launched --name. It recurred across ~25 unrelated PRs in 30 days (0 on master). Fixing PR: #109096.

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Partially. The Iceberg path is deterministically exercised by test_drop_table_delete_data (+ parallel-replicas variant). The non-Iceberg failure the guard could trigger is latent ("can start failing"): it needs a fresh non-Iceberg StorageObjectStorage with uninitialized metadata AND a metadata/object-storage error at drop. That combination is not reachable through supported DDL (see f/d), so no on-demand repro of the negative case exists.
b Root cause explained? isDataLakeConfiguration() is true for Iceberg + DeltaLake + Hudi + Paimon, but only IcebergMetadata overrides IDataLakeMetadata::drop(); the others keep the no-op default. iceberg_delete_data_on_drop is Iceberg-only. So for non-Iceberg engines the pre-drop lazyInitializeIfNeeded() did work whose only possible effect was to throw on a metadata/object-storage error irrelevant to a no-op drop.
c Fix matches root cause? Yes. Narrow the guard from isDataLakeConfiguration() to isIcebergConfiguration(), so only the engine whose drop() actually deletes data pays the init.
d Test intent preserved / new tests added? Preserved. No test weakened. A new distinguishing regression test is architecturally infeasible (see f); the existing test_drop_table_delete_data and test_drop_table_delete_data_parallel_replicas (Iceberg, both paths) guard that Iceberg deletion is unchanged.
e Both directions demonstrated? Positive direction: all 3 Iceberg drop tests pass on the fixed binary (build id 26a1c0fa..., 3 passed in 58.07s). Negative direction (old guard failing for a non-Iceberg engine) could not be produced: DeltaLakeLocal drops cleanly under both guards, and the catalog path cannot drop non-Iceberg tables at all.
f Fix general across code paths? Yes, and this is why no negative test exists. Non-Iceberg catalog drops are impossible (UnityCatalog/PaimonRestCatalog inherit ICatalog::dropTable = NOT_IMPLEMENTED, throwing before this code; only RestCatalog/GlueCatalog implement dropTable and both build Iceberg configs). Non-Iceberg self-managed drops keep current_metadata set from CREATE, so lazyInitializeIfNeeded() is a no-op regardless of guard. The narrowing is a strict subset (isIcebergConfiguration() implies isDataLakeConfiguration()), so it removes only the never-useful init for those engines.
g Generalizes across inputs? N/A (guard narrowing, not an input-typed code bug). The guard is a per-engine predicate; the change is uniform across all non-Iceberg data-lake engines (Delta/Hudi/Paimon) and all storage backends.
h Backward compatible? Yes. Behavior is unchanged for Iceberg (the only engine iceberg_delete_data_on_drop applies to and the only one that deletes on drop). For non-Iceberg engines the observable drop result is identical (their drop() is a no-op); only a redundant, potentially-throwing init is removed. No setting default, on-disk/wire format, or metadata format changes.
i Invariants and contracts preserved? Yes. isIcebergConfiguration() implies isDataLakeConfiguration(), so no path that previously initialized for Iceberg loses it. DataLakeConfiguration::drop() still calls current_metadata->drop() only when metadata is set; for non-Iceberg that remains the inherited no-op. drop() still runs in the background pool with the constructed drop_context; the delete_data_on_drop capture in checkTableCanBeDropped is unchanged.

Session id: cron:clickhouse-worker-slot-4:20260701-225900

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for fadc690 (partial-drop atomicity fix).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SYSTEM ENABLE FAILPOINT iceberg_drop_data_cleanup_fail then DROP TABLE ... SETTINGS iceberg_delete_data_on_drop=1 throws FAULT_INJECTED at the cleanup step every time.
b Root cause explained? StorageObjectStorage::drop() removed the catalog entry (catalog->dropTable) FIRST, then ran the file cleanup (lazyInitializeIfNeeded + configuration->drop). A throw in the cleanup (metadata init, listFiles, or an object-storage delete) left the catalog row already gone, so DROP failed AND the files were orphaned with no SQL path to retry (table no longer in the catalog).
c Fix matches root cause? Yes. Reorder so the file cleanup runs first and catalog->dropTable runs last (the commit point). A cleanup failure now aborts the DROP while the table is still registered, keeping it retryable. Not a symptom guard.
d Test intent preserved / new tests added? New integration test test_drop_table_delete_data_cleanup_failure_keeps_catalog_entry: injects a cleanup failure via the failpoint, asserts the catalog entry survives, then retries DROP to success. The three existing drop tests are unchanged and still pass.
e Both directions demonstrated? Yes. Old ordering: test FAILS (AssertionError: assert 0 == 1 - catalog entry gone). Reordered fix: test PASSES. All 4 drop tests pass on the fixed binary (Build ID 7f137ac2, 4 passed in 61.76s).
f Fix is general across code paths? Yes. StorageObjectStorage::drop() is the single drop path for object-storage/data-lake tables (self-managed and catalog-backed, incl. the parallel-replicas path already routed to the real storage). No sibling drop method has the pre-cleanup catalog removal.
g Fix generalizes across inputs? Yes. The reorder is independent of column types/wrappers/engines: it only moves the catalog-removal step relative to the existing cleanup. The Iceberg-only guard (isIcebergConfiguration()) on the init is unchanged, so DeltaLake/Hudi/Paimon are unaffected.
h Backward compatible? Yes. No setting, format, or on-disk/wire change. The only observable difference is that a failed cleanup no longer leaves an orphaned catalog entry - strictly safer; a successful DROP behaves identically.
i Invariants and contracts preserved? Yes. The cleanup ops depend only on object_storage + table_path (no catalog handle), so running them before catalog->dropTable upholds their preconditions. catalog->dropTable is unchanged and still the last step. The failpoint is a no-op unless explicitly enabled.

Session id: cron:clickhouse-worker-slot-0:20260702-004300

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — fadc690

CI is complete and green on this head. Every check passes; only CH Inc sync (private fork mirror) is non-reporting, which is expected and not actionable.

Check / test Reason Owner / disposition
Bugfix validation (integration tests, amd64 + aarch64) / test_database_iceberg suite transient infra (setup-phase server boot on first attempt) reran and PASSED (final: green). The same suite is 30/30 OK in all 6 regular Integration test variants on this exact head, so the first-attempt reds were harness-transient, not this diff.
CH Inc sync private fork mirror CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260702-053000

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. New failpoint iceberg_drop_catalog_remove_fail throws at the catalog-removal commit point; SYSTEM ENABLE FAILPOINT iceberg_drop_catalog_remove_fail + DROP TABLE ... SETTINGS iceberg_delete_data_on_drop=1 fails deterministically with the metadata anchor deleted on the old ordering.
b Root cause explained? IcebergMetadata::drop sweeps every object under the table path (empty prefix) including metadata/vN.metadata.json, and ran before catalog->dropTable. A DROP retry reconstructs IcebergMetadata from that anchor (DatabaseDataLake copies iceberg_metadata_file_location into iceberg_metadata_file_path). So a throw during a later object delete or at the catalog call left the catalog row present but the anchor gone, breaking the retry.
c Fix matches root cause? Yes. Delete data/manifest files first, run the catalog-removal commit, then delete the metadata anchor last. The anchor survives until the catalog entry is gone, so any failure before the commit is fully reconstructable/retryable.
d Test intent preserved / new tests added? New test test_drop_table_delete_data_catalog_failure_keeps_metadata asserts the catalog entry AND the *.metadata.json anchor both survive a failed commit, then a retry reconstructs and removes everything. Existing 4 drop tests unchanged.
e Both directions demonstrated? Yes. New test FAILS on the old single-phase ordering (assert 0 > 0, anchor gone) and PASSES with the fix. All 5 drop tests: 5 passed, Failures 0/5. Build-ID-verified binaries (fix 85019275, no-fix fed2ebda).
f Fix is general across code paths? Only IcebergMetadata overrides metadata drop; Delta/Hudi/Paimon inherit the base which just runs commit, so their single catalog removal is preserved. dropTable is the only DDL method acting on a tryGetTable-fetched storage.
g Fix generalizes across inputs? The ordering fix is input-independent (it reorders data-vs-metadata deletion + catalog commit for any Iceberg table). Setting off / non-Iceberg engines just run commit (no init, no deletion).
h Backward compatible? Yes. No setting default, on-disk/wire format, or metadata format change. Only the internal drop sequencing changes; a plain DROP remains a no-op on files.
i Invariants and contracts preserved? commit invoked exactly once on every path (Iceberg, non-Iceberg, setting-off). The catalog entry remains the single commit point; the metadata anchor is the retry anchor and outlives it. Deletions are logged (deletion-logging rule).

Session id: cron:clickhouse-worker-slot-0:20260702-052700

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes for CR#2 (version-hint): iceberg_use_version_hint=1 + iceberg_drop_catalog_remove_fail failpoint deterministically deletes version-hint.text in phase 1 without the fix. For CR#1 (settings snapshot): the drop-time init reads use_iceberg_metadata_files_cache from drop_context (confirmed via server log), so the one-boolean copy was demonstrably incomplete; the specific geometry/geography example does NOT fail today (drop never materializes the schema, see the inline reply).
b Root cause explained? CR#2: IcebergMetadata::drop phase-1 loop kept only *.metadata.json, deleting version-hint.text, but getLatestOrExplicitMetadataFileAndVersion reads the hint first and throws if missing, so a mid-drop failure left an unreconstructable table. CR#1: drop_context is designed to carry the session settings the background drop needs, but it copied only one boolean while init reads several session-scoped settings.
c Fix matches root cause? Yes. CR#2 keeps metadata/version-hint.text in the phase-1 anchor set (deleted last, after the catalog commit). CR#1 snapshots the whole query Settings and applies it to drop_context.
d Test intent preserved / new tests added? Added test_drop_table_delete_data_keeps_version_hint_on_failure; the 5 existing drop tests are unchanged and still pass.
e Both directions demonstrated? Yes for CR#2: without fix version-hint.text is deleted, with fix it survives (Build-ID-verified binaries). CR#1 is a strict generalization (superset of the prior one-boolean copy), validated by the full 6/6 drop-test run.
f Fix is general across code paths? Yes. IcebergMetadata::drop is the only metadata drop override (Delta/Hudi/Paimon inherit the no-op base). checkTableCanBeDropped/drop are the only pair carrying settings across the query/background boundary here.
g Fix generalizes across inputs? CR#2 keeps the anchor regardless of engine/format/metadata layout (the keep-set is name-based). CR#1 snapshots ALL settings, so it covers every current and future session-scoped setting the init path reads, not just the geo one.
h Backward compatible? Yes. No setting defaults, on-disk/wire formats, or validation changed. Behavior only widens drop_context to match the query context and keeps one extra file until commit.
i Invariants and contracts preserved? Yes. The "catalog entry is the drop commit point / metadata anchor survives until commit" invariant from the prior round is now self-consistent (the anchor includes the file the retry path actually needs). Non-Iceberg engines still run only the commit callback.

Session id: cron:clickhouse-worker-slot-1:20260702-071500

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up on the restart-durable async-drop gap the bot raised above (mechanism confirmed in my earlier reply on this thread, r3511954160). Tracking it separately from this PR as agreed. Before anyone implements, I would like your call on the direction, since both viable fixes are core-layer changes I do not want to pick unilaterally:

  1. Persist the drop-time intent into the dropped metadata / a sidecar and recover it in the table == nullptr restart branch of DatabaseCatalog::enqueueDroppedTableCleanup. This is an on-disk metadata_dropped/*.sql format change (it currently holds only the original CREATE text).
  2. Add a per-storage force-synchronous-drop hook on IStorage so a storage with drop intent set runs its cleanup inside the DROP query. This changes core DROP latency/semantics and would also make every self-managed StorageNATS/StorageRabbitMQ drop synchronous unless gated.

@alesapin as the Iceberg owner: option 1, option 2, or document as a known limitation? No urgency, this is a post-merge follow-up and not a blocker for this PR. The decision itself is independent of the merge, so answering now is fine; I will only implement after this merges. Whichever you pick I will cover all three affected engines (StorageObjectStorage Iceberg, StorageNATS, StorageRabbitMQ) and link the fix PR back here.

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ac5fc3c

CI fully finished and green on this head. No failed checks; every job is SUCCESS (including the 4 Bugfix validation and all Integration test lanes). The test_database_iceberg rows visible in CIDB are the bugfix-validation master-side baseline runs, and all four Bugfix validation checks concluded SUCCESS.

Check / test Reason Owner / fixing PR
(none) fully green n/a

Session id: cron:our-pr-ci-monitor:20260702-133000

@SmitaRKulkarni

Copy link
Copy Markdown
Member

@groeneai : Please delete only the files reachable from the table's own metadata (collectReachableFiles, which already takes the root from the catalog and ignores iceberg_metadata_file_path) instead of sweeping everything under table_path, because tables can share a location and dropping one would delete the other's data as you mentioned in couple of your comments

Tables can share a location, and one can be stored inside another table's
directory, so listing everything under the table path and deleting it
destroyed the files of tables that were not dropped. DROP now deletes the
files reachable from the table's metadata (`collectReachableFiles`, which
takes the root from the catalog when there is one), plus the metadata files
`metadata-log` misses: ClickHouse does not log the version written by
CREATE or by a schema change, so those are matched by `table-uuid`.

A retried drop of an Atomic table reuses the collected list, because the
metadata it was collected from may already be partly deleted.

The list can name files that do not exist (`version-hint.text`), so in a
database that reattaches the table after a failed DROP, such a file no longer
counts as the first deleted one, which made the next failure ignored.

Tests: `04365` keeps a table stored inside the dropped table's directory,
`test_tables_with_same_location` keeps the other table at the shared
location, `04366` fails the DROP of a table without data files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in e938b95: DROP now deletes the files collectReachableFiles reaches from the table's root (the catalog's pointer when there is a catalog) instead of everything under table_path.

One addition was needed. ClickHouse does not put the metadata file written by CREATE (or by a schema change) into metadata-log, so the closure alone left v1.metadata.json behind, and re-creating the table at the same path failed again with TABLE_ALREADY_EXISTS (#108524). Metadata files in the table's metadata/ directory with the same table-uuid as the root are deleted as well; another table at the same location has a different UUID and keeps its files.

Tests: test_tables_with_same_location now drops one of the two tables with iceberg_delete_data_on_drop = 1 and reads the other, and 04365 does the same for a table stored inside the dropped table's directory. Both fail on the previous head (a1f8ddc) and pass now.

In a Replicated database every replica drops its copy of the table, and
the copies share one location. Since `drop()` collects the files from the
latest metadata, every replica after the first one fails with
`FILE_DOESNT_EXIST`, `DatabaseCatalog` retries it every 5 seconds forever,
and `DROP TABLE ... SYNC` / `DROP DATABASE ... SYNC` on that replica never
returns (Stateless tests (arm_binary, s3 storage, DBReplicated, parallel,
1/2): the replicated DDL queue stalled and the job stopped at
`--max-failures`). The initiator does not wait for that replica, so a
table created at the location in the meantime is deleted by the retry.

Before deleting, look at the metadata files at the location: when none of
them carries the table's own `table-uuid` (compared as an optional, so a
table without one is told apart from a table with one), delete nothing.
A retry of an earlier failed attempt still deletes its remaining files when
the location holds no metadata at all, but not when another table is there.
The files are read bypassing the metadata cache: it is keyed by the table
uuid and the file name, so it would return this table's old content for a
file name the new table reuses.

Measured with two replicas sharing one `IcebergLocal` path: before, the
second replica retried 482 times in 40 minutes, its `DROP DATABASE SYNC`
hung, and a re-created table lost `v1.metadata.json`; after, the second
replica logs "nothing to delete" and returns, and the new table is intact.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits October 19, 2026 18:12
A table attached by `ATTACH` or at server startup loads its Iceberg
metadata lazily, so a DROP with `iceberg_delete_data_on_drop = 1` reads
the table identity from the files that are at the path at drop time.
In a `Replicated` database every replica replays the DROP on the same
files, which gave two failures for a replica whose table was not read
since startup:

- The initial replica has already deleted the files: the metadata init
  throws `FILE_DOESNT_EXIST`, and the background drop retries every 5 s
  forever, so `DROP ... SYNC` and the replica's DDL queue hang.
- The replica was down while the table was dropped and another table was
  created at the path: its replay adopts the new table's `table-uuid`,
  passes the ownership check and deletes the new table's files.

Only the initial run of a `Replicated` database's DDL creates the
Iceberg table (a replay is `SECONDARY_CREATE`), so a replayed DROP no
longer deletes data either. A lazy init that finds no metadata file left
means there is nothing to delete.

Measured with two servers in one `Replicated` database sharing an
IcebergLocal path: before, the restarted replica retried the drop
forever (first case) and deleted all 5 files of the new table, whose
SELECT then failed with code 107 (second case); after, neither happens.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment on lines +1870 to +1871
auto reachable = Iceberg::collectReachableFiles(
object_storage, persistent_components, data_lake_settings, context, log, catalog, storage_id.getTableName());

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.

[P2] Support version 1 metadata in the new cleanup traversal

This newly used helper assumes version 2 metadata: for any nonempty snapshots, SnapshotFilesTraversal.cpp:179 unconditionally reads current-schema-id. That field is optional in version 1 (Iceberg specification), and the existing reader supports its absence through parseTableSchemaV1Method, using schema.schema-id. The helper's existing remove_orphan_files caller explicitly rejects version 1 before invoking it; this caller has no corresponding restriction.

A readable, populated version 1 table without current-schema-id therefore throws before cleanup. In an Atomic database, background cleanup retries the same deterministic exception indefinitely, and DROP TABLE ... SYNC cannot finish. Make the traversal handle the supported version 1 representation and add a regression using version 1 metadata without the optional version 2 fields.

groeneai and others added 2 commits October 20, 2026 22:57
Two gaps in the delete-on-drop cleanup of an Iceberg table:

1. Without a catalog, `collectReachableFiles` roots at the latest metadata
   file at the table path, chosen by version and not by table UUID. When the
   location also holds another table's newer metadata file, the ownership
   guard passes (this table's own files are still there), the traversal
   follows the other table's graph, and dropping this table deleted the other
   one. Measured: after the drop the other table's SELECT returned no rows
   instead of its two. Now the cleanup keeps every file when the UUID of the
   root differs from the one the table was loaded with. The traversal no
   longer reads through the metadata cache, like the ownership scan before
   it: when the other table's root reuses a file name this table read
   before, the cache returns this table's old content for it, the UUID
   check passes, and the other table's metadata was deleted. Selecting the root
   by UUID instead (as `iceberg_metadata_table_uuid` does) was not taken:
   that selection throws on any metadata file at the location without a
   `table-uuid`, so a background drop would retry forever.

2. Data files were told from the rest by their extension, `.parquet` or
   `.orc`. Avro data files were deleted with the metadata files, after the
   catalog drop, so for a catalog table a failed delete of one was ignored
   and the DROP succeeded with no catalog entry to retry through. The
   traversal now returns the data and delete files it read from the
   manifests, and the cleanup uses them.

Tests: 04365 keeps a table whose newer metadata, under a file name the
dropped table used before, sits at the dropped table's path; 04366 adds an
Avro table to the first-delete failure arm. Both fail before the change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Without a catalog, `drop()` keeps every file when the latest metadata file at
the location carries a `table-uuid` other than the dropped table's. That
check required the dropped table's own uuid to be known, so a format version 1
table loaded without `table-uuid` (optional in v1) skipped it: with another
table's higher-version metadata file (which has a uuid) at the same location,
dropping the v1 table with `iceberg_delete_data_on_drop = 1` deleted the other
table's metadata, manifests and data, and that table then read 0 rows.

Compare the two optional uuids directly, so a root with a uuid is never
followed by a table without one. ClickHouse never adds a `table-uuid` to an
existing table (writes copy the previous metadata), so a uuid-less table's own
later versions stay uuid-less and are still cleaned up. Two uuid-less tables
at one location remain indistinguishable, as before.

The 04365 shared-location case now also runs with a format version 1 table
whose metadata has no `table-uuid`; it fails without the change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`collectReachableFiles` adds `metadata/version-hint.text` unconditionally, but
the hint belongs to the location, not to a table. When another table's metadata
file stays at the location (for example a table selected there with
`iceberg_metadata_table_uuid`), that table can read through the hint
(`iceberg_use_version_hint = 1`), and deleting it made its next read fail with
FILE_DOESNT_EXIST. Now the hint is deleted only when every metadata file at the
location is this table's; a metadata file whose owner cannot be told (no
`table-uuid`) counts as another table's. A kept hint that names a deleted file
is harmless: a numeric hint that resolves to no file falls back to listing.

The shared-location case of 04365 now reads the other table through its version
hint after a table selected by `iceberg_metadata_table_uuid` is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits October 21, 2026 02:42
A REST catalog (and S3 Tables, which is one) gets `purgeRequested=true`
on DROP with `iceberg_delete_data_on_drop`, and the catalog server
deletes the files. ClickHouse still deleted the data files itself before
asking for the purge, so ClickHouse now needed `s3:DeleteObject` on the
table location even when the catalog can purge with its own credentials.

Measured with the REST fixture and a MinIO user allowed only to read and
list, used as the DataLakeCatalog storage credentials:
- master: DROP succeeds, purge requested, 0 files left;
- f1d4035: DROP fails with Access Denied on the first data file, the
  table stays in the catalog;
- this commit: DROP succeeds, purge requested, 0 files left, no delete
  sent by ClickHouse.

`supportsDropTable()` is replaced by `keepsFilesOnDrop()`, true only for
Glue, whose DeleteTable leaves the files: only there does ClickHouse
delete them (data, catalog entry, metadata). Every other catalog either
purges or cannot drop at all, and is asked first.

Tests: the REST retry test now asserts that a failed catalog drop deletes
no file (fails on f1d4035), and the two failure-path cases that only
the client-side deletion reaches moved to `test_database_glue`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 3 commits October 22, 2026 13:49
UnityV2Catalog now implements dropTable (ClickHouse#124481): for an external table it
refuses `iceberg_delete_data_on_drop = 1` with SUPPORT_IS_DISABLED before
sending anything, instead of the base ICatalog NOT_IMPLEMENTED. The file and
row assertions are unchanged; a mutant that sends Unity down the client-side
delete path still fails them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
After the master merge, IcebergMetadata::data_lake_settings is a
DataLakeStorageSettingsPtr instead of a reference, so the drop cleanup
call no longer compiled (Build (arm_tidy, 1/4) on f8b21bf). Pass
*data_lake_settings, like the other call sites in this file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 88eb78b

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Changed settings are not reflected in the settings changes history (see changed_settings.txt) not from this PR (it does not touch settings): v26.10.2.103-stable ships use_query_condition_cache_for_time_conditions = false after #127632, while master's settings history still says its default became true in 26.10. The only row in changed_settings.txt is that setting (1 / 0), the same row every PR on current master reports #127687 (mine, open)
Mergeable Check, PR praktika rollups of the row above #127687 (the owner of the row above)
CH Inc sync - CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head (the Bugfix validation (integration tests, *) rows are the expected inversion: the new tests fail on master).

Session id: cron:our-pr-ci-monitor:20261024-100006

…eanup-108524

Resolve the conflicts in IDataLakeMetadata.cpp and test_database_iceberg/test.py by keeping both sides.
@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Dear @SmitaRKulkarni, 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.

@clickhouse-gh clickhouse-gh Bot added comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 19, 2026
…eanup-108524

Resolve the conflicts in IcebergMetadata.cpp, StorageObjectStorage.cpp and
StorageObjectStorage.h by keeping both sides. The CREATE existence check keeps
its version-hint predicate and lists only the direct children of `metadata/`,
as master now does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Without a catalog, the drop walked the latest metadata file's manifests
before checking that the file belongs to the dropped table. At a location
shared with another table whose manifests do not fit this table's schemas
(a String column partitioned by day in the other table, or any conflicting
schema with iceberg_tolerate_conflicting_manifest_schemas = 0), the walk
threw ILLEGAL_TYPE_OF_ARGUMENT / ICEBERG_SPECIFICATION_VIOLATION, so an
Atomic table was retried in the background forever and DROP TABLE ... SYNC
never returned. The root is now resolved and checked first, and the
traversal starts from it (collectReachableFilesFromRoot), so the other
table is left alone and the drop finishes. 04365's shared-location case
now uses such a table.

The cleanup also no longer builds a separate list of metadata files while
deleting data files: an allocation failure there, after a data file was
deleted, escaped the best-effort handling of a reattaching drop. The set
is iterated twice instead.

Also drop the duplicate <Common/FailPoint.h> include the last master
merge left (Build (arm_tidy, 1/4): readability-duplicate-include).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Iceberg S3 path isn't cleaned up after DROP TABLE

6 participants