Repository navigation
Initialize data lake metadata before OPTIMIZE / ALTER on attach - #104738
PedroTadim merged 2 commits into
Conversation
…kHouse#104711) `OPTIMIZE TABLE` on a freshly attached `IcebergLocal` (or other data lake) table used to raise `Logical error: 'Metadata is not initialized'` and abort the server. Same for `ALTER TABLE ... DELETE`, `ALTER TABLE ... ADD COLUMN`, and the corresponding mutation/alter pre-checks. The user-visible reproducer from the issue is: SET iceberg_metadata_compression_method = 'deflate'; CREATE TABLE t0 (c0 Int) ENGINE = IcebergLocal(local, path = '...'); SET output_format_compression_level = 11; INSERT INTO TABLE t0 VALUES (2); -- fails: INCORRECT_DATA -- restart server OPTIMIZE TABLE t0; -- Fatal: Logical error 'Metadata is not initialized'. Cause: `DataLakeConfiguration::current_metadata` is loaded lazily — `read`, `write` and `mutate` call `update` / `lazyInitializeIfNeeded` before delegating, but `optimize`, `alter`, `checkMutationIsPossible` and `checkAlterIsPossible` did not. When the table was attached lazily (typical after a server restart) or the previous `update` failed (here: the failed INSERT left a corrupted `vN.deflate.metadata.json` on disk and the catch in `StorageObjectStorage`'s constructor swallowed the load failure), the four methods above hit `assertInitialized` and raised `LOGICAL_ERROR` — fatal in debug / sanitizer builds. This patch calls `configuration->update(object_storage, context)` from each of those four methods when the configuration is a data lake. The metadata is either populated successfully and the operation proceeds, or the load error surfaces as a regular user-facing exception (e.g. `INCORRECT_DATA` for the corrupted JSON above) instead of a logical error. `checkMutationIsPossible` has no `Context` parameter, so it uses `CurrentThread::tryGetQueryContext()` — the same fallback already used by `supportedPrewhereColumns` and `getColumnSizes` in this file. A new stateless regression test (`04230_iceberg_optimize_metadata_not_initialized_104711`) reproduces the corrupt-metadata-on-disk state with `DETACH ... SYNC` + `ATTACH` (equivalent to a server restart for `current_metadata`) and asserts that `OPTIMIZE` / `ALTER DELETE` / `ALTER ADD COLUMN` no longer produce a logical error and that the server keeps running. Closes ClickHouse#104711.
|
cc @alesapin @Michicosun @scanhex12 — could you review this? It addresses #104711 (and the related #96806) by calling cc @PedroTadim — thanks for the reproducer, this should cover both the OPTIMIZE crash you reported and the ALTER-side variant from the linked #96806. Pre-PR validation gate
Session: cron:clickhouse-ci-task-worker:20260512-164500 |
|
I think this commit puts too much data lake-specific logic in StorageObjectStorage when it could instead go in DataLakeConfiguration.h. I will push a commit to address it. |
|
I'm not sure when We could also add context as a param, but it would require touching a lot of header files, so might be nice to avoid. |
|
Workflow [PR], commit [7da6615] Summary: ✅ AI ReviewSummaryThis PR adds lazy metadata initialization for several Findings
Tests
Final Verdict
|
| # error code is reported (it depends on what `update` happens to fail | ||
| # with for the corrupted metadata) — only that it is NOT a logical error | ||
| # and that the server keeps running. | ||
| ${CLICKHOUSE_CLIENT} --allow_experimental_iceberg_compaction=1 \ |
There was a problem hiding this comment.
This regression script runs OPTIMIZE before ALTER TABLE ... DELETE (OPTIMIZE at line 56, DELETE at line 62). Since OPTIMIZE now performs lazy initialization, it can mask the DELETE-first entrypoint where supportsDelete is checked before checkMutationIsPossible.
Could we add a case where ALTER ... DELETE is the first operation after DETACH/ATTACH (for example by re-attaching again before the delete check, or by using a second table) so the regression covers that path directly?
There was a problem hiding this comment.
Good catch — with the current order (DETACH → ATTACH → OPTIMIZE → ALTER ... DELETE → ALTER ... ADD COLUMN), OPTIMIZE performs the lazy init and the subsequent DELETE / ADD COLUMN find the metadata already populated, so they never exercise their own init paths.
I'll restructure to three separate tables — one per first-operation entrypoint — so each operation runs as the first post-ATTACH call:
t_optimize:DETACH→ATTACH→OPTIMIZEt_delete:DETACH→ATTACH→ALTER ... DELETEt_add_column:DETACH→ATTACH→ALTER ... ADD COLUMN
That also surfaces the supportsDelete gap you flagged on DataLakeConfiguration.h — the current ordering hides it because OPTIMIZE initializes the metadata before DELETE is dispatched.
I'll wait for @asya-ch's refactor to settle and her view on the supportsDelete follow-up before pushing the restructured test, so the test exercises whatever final shape the lazy init takes.
| } | ||
|
|
||
| void checkMutationIsPossible(const MutationCommands & commands) override | ||
| void checkMutationIsPossible(ObjectStoragePtr object_storage, ContextPtr context, const MutationCommands & commands) override |
There was a problem hiding this comment.
ALTER TABLE ... DELETE can still raise a LOGICAL_ERROR exception before this method runs.
InterpreterDeleteQuery::execute first calls table->supportsDelete() (src/Interpreters/InterpreterDeleteQuery.cpp, line 92). For StorageObjectStorage, that goes through DataLakeConfiguration::supportsDelete, which still uses assertInitialized(). If a lazy ATTACH left current_metadata == nullptr, supportsDelete throws Metadata is not initialized, so this new lazy-init path in checkMutationIsPossible is never reached.
Can we also initialize metadata on the supportsDelete path (or avoid asserting there) so ALTER ... DELETE is covered even when it is the first operation after ATTACH?
There was a problem hiding this comment.
You're right — InterpreterDeleteQuery::execute calls table->supportsDelete() (InterpreterDeleteQuery.cpp line 92) before table->checkMutationIsPossible (line 103). For a freshly-attached datalake table with current_metadata == nullptr, DataLakeConfiguration::supportsDelete would throw Metadata is not initialized from assertInitialized and never reach the lazy init we added in checkMutationIsPossible. The current regression test misses this because it runs OPTIMIZE first, which initializes the metadata — see the related test-gap concern on the script above.
IStorage::supportsDelete() const is a fixed const virtual with no Context, which constrains the options. Three plausible directions:
- Init at the
StorageObjectStoragelayer. CallCurrentThread::tryGetQueryContext()+configuration->lazyInitializeIfNeeded(object_storage, ctx)insideStorageObjectStorage::supportsDelete, mirroring the pattern ofsupportedPrewhereColumnsandgetColumnSizesin the same file. Minimal surface change; brings back a smallisDataLakeConfiguration()branch inStorageObjectStorage, which is the layering @asya-ch is pushing against. - Push the init into the configuration, matching @asya-ch's refactor. Change
StorageObjectStorageConfiguration::supportsDeleteto take(ObjectStoragePtr, ContextPtr), haveDataLakeConfiguration::supportsDelete(...)calllazyInitializeIfNeeded(...). Requires eithermutable current_metadataor dropping theconstqualifier onsupportsDeletein the*Configurationchain (theIStoragelayer can stayconstand just threadobject_storage+CurrentThread::tryGetQueryContext()through). - Honest fallback. Have
DataLakeConfiguration::supportsDeletereturnfalsewhencurrent_metadata == nullptr. Avoids the logical-error exception, but silently disables datalakeDELETEbetweenATTACHand the first read on a corrupted-metadata table — surprising behaviour, andInterpreterDeleteQuerywould then fall through tosupportsLightweightDeletewhich has the sameassertInitializedproblem.
I'd lean toward (2) since it follows the same direction as the rest of the refactor; (1) is the lower-risk minimal change if we'd rather not widen the configuration interface further.
Same applies to supportsParallelInsert (line 139) and any other assertInitialized() caller reachable before read / write / mutate. I'll hold off pushing the supportsDelete fix until the refactor settles, so it can land on one consistent architecture along with the restructured regression test.
LLVM Coverage Report
Changed lines: 54.17% (13/24) · Uncovered code |
|
Re
Both are The alternative — adding If you'd prefer to be more defensive, two cheaper options:
Happy to go whichever way you and @Michicosun prefer. |
|
@groeneai you should add |
It should be okay, mutation validation is being run in the context of an alter interpreter, which is the query context. |
|
Hi @groeneai @PedroTadim — while reviewing this PR I found the following:
Happy to discuss — close anything that's wrong or already addressed. |
|
Backport labels have been automatically added based on https://github.com/ClickHouse/clickhouse-core-incidents/issues/1691 Labels added:
These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels. |
Cherry pick #104738 to 26.2: Initialize data lake metadata before OPTIMIZE / ALTER on attach
…ZE / ALTER on attach
PR ClickHouse#102882 (Smita Kulkarni, merged 2026-05-28) added table->updateExternalDynamicMetadataIfExists() in InterpreterDeleteQuery::execute before the table->supportsDelete() call. That upstream fix initializes the data lake metadata before supportsDelete reaches assertInitialized, so the Logical error path that 04238 was designed to catch is no longer reachable via DELETE FROM on master HEAD. The other five cases in 04238 (TRUNCATE, UPDATE, INSERT, ALTER DELETE, ALTER UPDATE) were documented in the test as shape-coverage-only: the corrupted-metadata setup errors with INCORRECT_DATA before reaching the supports* methods. 04240 stays. It covers the InsertDependenciesBuilder supportsParallelInsert path on MV-dependent sinks, which has no upstream lazy-init guard and which our StorageObjectStorage wrapper does fix. The StorageObjectStorage::supportsDelete wrapper is kept as defense in depth, mirroring the checkMutationIsPossible / checkAlterIsPossible wrappers added by parent PR ClickHouse#104738.
`InterpreterDeleteQuery::execute` calls `table->supportsDelete()` BEFORE `table->checkMutationIsPossible()`. For a freshly-attached `Iceberg` / `DeltaLake` / `Hudi` table whose `current_metadata` has not been loaded (typical after server restart when the previous metadata load failed and was swallowed by the lazy-init catch in `StorageObjectStorage`'s constructor), `DataLakeConfiguration::supportsDelete()` raised `LOGICAL_ERROR: Metadata is not initialized` from `assertInitialized()`, fatal in debug / sanitizer builds. This is the sibling case of the issue fixed for `OPTIMIZE` / `ALTER` by PR ClickHouse#104738 (which moved lazy-init into `DataLakeConfiguration` for `optimize`, `alter`, `checkMutationIsPossible`, `checkAlterIsPossible`). The `supportsDelete()` call site is reached before any of those four methods in the `DELETE FROM` path, so the merged fix never runs. `InsertDependenciesBuilder` reaches `supportsParallelInsert()` with the same shape during `INSERT` pipeline construction, so apply the same treatment to it. Override `supportsDelete()` and `supportsParallelInsert()` on `StorageObjectStorage` (matching the existing pattern of `supportedPrewhereColumns()` and `getColumnSizes()` in the same file) and call `lazyInitializeIfNeeded()` on data lake configurations before delegating. A regular user-facing exception is raised instead of a logical error, and the server keeps running. New regression test `04238_iceberg_supports_delete_metadata_not_initialized_104891` exercises the `DELETE FROM` path right after `DETACH+ATTACH` with no preceding `OPTIMIZE` / `ALTER`, so the `supportsDelete()` lazy-init is not masked by initialization from another code path. Closes ClickHouse#104891 Related: ClickHouse#104711, ClickHouse#104738 Co-Authored-By: Claude Opus 4.7 <[email protected]>
Cherry pick #104738 to 26.3: Initialize data lake metadata before OPTIMIZE / ALTER on attach
…ZE / ALTER on attach
Cherry pick #104738 to 26.4: Initialize data lake metadata before OPTIMIZE / ALTER on attach
…ZE / ALTER on attach
Backport #104738 to 26.4: Initialize data lake metadata before OPTIMIZE / ALTER on attach
Backport #104738 to 26.3: Initialize data lake metadata before OPTIMIZE / ALTER on attach
…ore OPTIMIZE / ALTER on attach
…4738 Backport ClickHouse#104738 to 26.4: Initialize data lake metadata before OPTIMIZE / ALTER on attach
Linked issues
Motivation
OPTIMIZE TABLEon a freshly attachedIcebergLocal(or other data lake) table used to raiseLogical error: 'Metadata is not initialized'and abort the server. Same forALTER TABLE ... DELETE,ALTER TABLE ... ADD COLUMN, and the corresponding mutation/alter pre-checks. The user-visible reproducer from #104711:A close cousin is the
ALTER TABLE ... DELETEstack trace in #96806 — same root cause, different entry point.Root cause
DataLakeConfiguration::current_metadatais loaded lazily.read,writeandmutatecallupdate/lazyInitializeIfNeededbefore delegating, butoptimize,alter,checkMutationIsPossibleandcheckAlterIsPossibledid not.When the table was attached lazily (typical after a server restart) or the previous
updatefailed during ATTACH (in the reproducer above, the failed INSERT leaves a corruptedvN.deflate.metadata.jsonon disk, and the catch inStorageObjectStorage's constructor swallows the load failure), the four methods above hitDataLakeConfiguration::assertInitializedand raiseLOGICAL_ERROR— fatal in debug / sanitizer builds.Fix
Call
configuration->update(object_storage, context)from each of those four methods onStorageObjectStoragewhen the configuration is a data lake. The metadata is either populated successfully and the operation proceeds, or the load error surfaces as a regular user-facing exception (e.g.INCORRECT_DATAfor the corrupted JSON above) instead of a logical error.checkMutationIsPossiblehas noContextparameter, so it usesCurrentThread::tryGetQueryContext()— the same fallback already used bysupportedPrewhereColumnsandgetColumnSizesin this file.Local verification
Built debug, reproduced the LOGICAL_ERROR with the exact issue reproducer, confirmed the fix replaces it with a normal
INCORRECT_DATAexception, and the server stays alive. A new stateless regression test (04230_iceberg_optimize_metadata_not_initialized_104711) reproduces the corrupt-metadata-on-disk state withDETACH ... SYNC+ATTACH(equivalent to a server restart forcurrent_metadata) and asserts thatOPTIMIZE/ALTER DELETE/ALTER ADD COLUMNno longer produce a logical error and the server keeps running. The test fails (server crash) on master and passes on this branch.Related: #104711, #96806.
Closes #104711
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a
LOGICAL_ERRORexception (Metadata is not initialized) raised byOPTIMIZE TABLE,ALTER TABLE ... DELETE,ALTER TABLE ... ADD COLUMNand other ALTER variants on a lazily-attachedIceberg/IcebergLocal/DeltaLake/Huditable whose metadata had not been loaded yet (typical after a server restart, or after a previous metadata write failed and left a corrupted metadata file on disk). The operation now either proceeds normally if the metadata loads successfully, or surfaces the underlying load failure as a regular user-facing exception instead of aborting the server in debug / sanitizer builds.Documentation entry for user-facing changes
Version info
26.5.1.62626.4.5.24,26.3.14.25