Skip to content

Fix data loss and silent behaviour changes in databases with lazy_load_tables - #113389

Open
evillique wants to merge 132 commits into
ClickHouse:masterfrom
evillique:lazy-load-tables-fixes
Open

evillique wants to merge 132 commits into
ClickHouse:masterfrom
evillique:lazy-load-tables-fixes

Conversation

@evillique

@evillique evillique commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

Closes: #117426
Closes: #117440
Related: #121332
Related: #96283
Related: #117490
Related: #118135
Related: #118152

lazy_load_tables keeps a table behind StorageTableProxy until its first access, and the catalog keeps handing out the proxy afterwards. #121332 made the casts on catalog pointers look through it. This PR fixes what the proxy itself answers wrongly and defers only the engines that are known to be safe.

  • Deferring is opt-in per engine (supports_deferred_load, shown in system.table_engines) instead of the engine-name lists in DatabaseOrdinary, so an engine that has not opted in is loaded eagerly.
  • StorageProxy forwards the IStorage methods a deferrable engine overrides. BACKUP no longer produces an empty archive that reports success, mutations, DELETE FROM and lightweight UPDATE are no longer rejected, and parallel replicas, trivial count and the table-level async_insert setting are no longer silently disabled.
  • The proxy answers the engine name, supportsReplication and storesDataOnDisk from the CREATE query until the table is loaded. system.tables.engine shows the real engine instead of TableProxy, a nondeterministic mutation is rejected again on a replicated table, and /replicas_status loads only the replicated tables instead of skipping the unloaded ones. A new system.tables.is_loaded column shows which tables are loaded.
  • SYSTEM STOP MERGES db.t (and the other action locks) loads a deferred table it names, so the lock is really taken, and a deferred data lake table answers supportsReplication like the loaded one.
  • A table is no longer dropped while the storage it wraps is still in use, and SHOW COLUMNS and SHOW INDEXES load the table to report its keys and indices.
  • Two more style checks: StorageProxy must forward every IStorage virtual that a deferrable engine overrides, and an engine that opts in must list its class in the cast check.

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fix data loss and several silent behaviour changes in databases created with lazy_load_tables = 1: BACKUP produced empty backups, SYSTEM STOP MERGES on a table that was not accessed yet had no effect, mutations and DELETE FROM were rejected, SHOW COLUMNS and SHOW INDEXES reported no keys, and parallel replicas, trivial count and the table-level async_insert setting were disabled. Only the engines that support it are now loaded lazily, and system.tables reports the real engine name and a new is_loaded column.


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

@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ae9e9bb]

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

⚠️ Review sessions stopped as a cybersecurity risk

The model provider stopped these review sessions as a possible cybersecurity risk:

  • attempt 1: gpt-6.1-sol

This summary comes from a session with gpt-5.4. A session is typically stopped when it reaches a memory-safety finding, and the finding is lost with it, so this review can miss a real defect. Please review the change in detail, and run the review internally with a model that has cyber access.

Summary

This PR tightens lazy_load_tables behavior around proxy answers, access-before-load checks, and engine opt-in for deferred loading. Most previously reported issues are addressed, but one blocker remains: RENAME TABLE / EXCHANGE TABLES can still materialize an untouched deferred streaming table under its old StorageID, so some engines keep constructor-derived external identities from the pre-rename name.

Findings

❌ Blockers

  • [src/Databases/DatabaseAtomic.cpp:344] DatabaseAtomic::renameTable now force-loads an untouched deferred table before the catalog rename happens. StorageTableProxy::getNested constructs the real storage from the proxy's then-current id (src/Storages/StorageTableProxy.h:111) and only applies renameInMemory afterwards, which is too late for engines that derive external state in their constructors. StorageKafka builds the default kafka_client_id from table_id_ in its constructor and its renameInMemory only updates the registry (src/Storages/Kafka/StorageKafka.cpp:185, src/Storages/Kafka/StorageKafka.cpp:361). StorageRabbitMQ likewise derives queue_base / sharding_exchange from table_id_ in its constructor and its renameInMemory also only updates the registry (src/Storages/RabbitMQ/StorageRabbitMQ.cpp:277, src/Storages/RabbitMQ/StorageRabbitMQ.cpp:1153). After a restart, renaming an untouched lazy Kafka / RabbitMQ table can therefore keep talking to the old external identity until the table is recreated.
    Suggested fix: either opt such engines back out of supports_deferred_load, or make the rename/preload path rebuild the storage under the post-rename StorageID before startup and add a regression that renames an untouched lazy streaming table after restart.
Final Verdict

Status: ❌ Block

  • Prevent untouched deferred streaming tables from being materialized under the old name during RENAME TABLE / EXCHANGE TABLES, or remove those engines from deferred loading until their constructor-time state becomes rename-safe.

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Aug 4, 2026
Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
Comment thread src/Storages/StorageProxy.h Resolved
Comment thread src/Storages/StorageProxy.h Resolved
Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
Comment thread src/Storages/StorageProxy.h Resolved
Comment thread src/Storages/StorageProxy.h Resolved
Comment thread src/Storages/StorageProxy.h Resolved
Comment thread src/Server/ReplicasStatusHandler.cpp Resolved
Comment thread src/Storages/StorageProxy.h Resolved
Comment thread src/Storages/StorageProxy.h Resolved
Comment thread src/Storages/StorageProxy.h Resolved
…eProxy`

Master added this virtual and overrides it in `StorageObjectStorage`, which is
deferrable, so the `storage_proxy_forwards` style check failed: a lazily loaded
table answered it from the proxy rather than from the nested storage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Server/TCPHandler.cpp Resolved
alexey-milovidov and others added 3 commits November 20, 2026 08:33
…atusRequest`

An ordinary native session could send a `TablesStatusRequest` for a table it has no rights on, and a
deferred replicated table was constructed and started to report its delay. Check the access with
`checkAccessBeforeLoadingLazyTable`, like the other paths that load a lazy table by name. The
interserver mode is authenticated with the cluster secret and is not changed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e` and `05569_lazy_load_tables_iceberg_snapshot_per_select`

`02354_vector_search_drop_cache_for_table_lazy_proxy_rename` was added on master and checks that
`system.tables.engine` is `TableProxy` for a table behind a proxy. This PR reports the engine from
the `CREATE` query instead, so check `is_loaded` too.

`05569_lazy_load_tables_iceberg_snapshot_per_select` hits the known failure of a table created `AS`
a data lake table function with parallel replicas in the server profile:
ClickHouse#132278 (fix in progress:
ClickHouse#132315), so it is tagged `no-parallel-replicas`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113389&sha=a4d7e8c6bb086fc1110ca9b69e14803a174fa498&name_0=PR
PR: ClickHouse#113389

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 20, 2026
@stresshouse

stresshouse Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

no significant changes detected. K_source=4 K_base=14 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 2a4bb380-f978-4aec-92eb-8e4cd1c0deea
  • MIRAI run: 009571cb-d3a3-4580-a1f0-f514cf318222
  • PR check IDs:
    • clickbench_478767_1795180990
    • clickbench_478773_1795180990
    • tpch_adapted_1_official_478810_1795180990
    • tpch_adapted_1_official_478833_1795180990

…e_query_plan`

In the `distributed plan` CI job (`serialize_query_plan = 1`) the remote server
executes the deserialized query plan, and the tables of such a plan are resolved
without the access checks of the interpreter. The query of the user without
rights succeeded, and the table was loaded by the initiator while building the
plan, so the test did not exercise `TablesStatusRequest`. Disable
`serialize_query_plan` for the two distributed queries of the test.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113389&sha=6ecfcfe6eb1931bab16abbcb8d153b7bddd6bd78&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20targeted%29
ClickHouse#113389

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

auto nested_storage = get_nested();
/// A storage built for a `DROP` that did not go through is started and used from here on.
auto nested_storage = built_for_drop ? std::exchange(built_for_drop, nullptr) : get_nested(getStorageID());

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.

[Blocker] RENAME TABLE / EXCHANGE TABLES still construct newly deferred external/streaming storages under the old StorageID

DatabaseAtomic::renameTable now force-loads lazy tables before it updates their catalog name, so this path materializes an untouched deferred table while getStorageID() is still the old one. That changes real behavior for the engines this PR newly allows to stay lazy: StorageKafka / StorageKafka2 bake {database} / {table} macro expansion and the default kafka_client_id in their constructors, and StorageRabbitMQ computes queue_base / sharding_exchange there while its renameInMemory only renames the registry entry. After a restart, RENAME TABLE on an untouched lazy Kafka/RabbitMQ table can therefore keep talking to the old external identity until the table is recreated.

This needs either an opt-out from deferred load for storages whose rename is not fully in-memory, or a way to rebuild that constructor-derived state when the rename path preloads the proxy.

Comment thread ci/jobs/check_style.py Resolved
Comment thread src/Databases/DatabaseAtomic.cpp Resolved
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 20, 2026 12:45

AI review of a later commit does not approve the PR, see the AI Review comment.

…ading, and the deferred-engine audit

- `checkAccessBeforeLoadingLazyTable` and `loadTableIfLazy` follow an `Alias` to the last table of its
  chain, which the alias loads before checking the rights on it. This covers `SELECT`, `EXPLAIN`,
  `INSERT` (also asynchronous), and `SHOW COLUMNS` / `SHOW INDEXES` through an alias. `ALTER` and
  `DELETE FROM` through an alias check `ALTER` / `ALTER DELETE` on the target first. The
  `TablesStatusRequest` does not load the target of an alias, so it keeps checking the named table.
- `RENAME DATABASE` no longer loads the deferred tables to ask `checkTableCanBeRenamedByDatabaseRename`.
  An engine answers it from the definition through `StorageFactory::CheckDatabaseRenameFn` instead,
  which `S3Queue` and `AzureQueue` implement without reading Keeper or starting the queue.
- `check_deferrable_engines_are_audited` follows the creator passed to `registerStorage` and the
  helpers it returns through (`createStorageObjectStorage`, `createQueueStorage`), and fails when it
  cannot tell which class a registration creates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflict in `src/Storages/StorageKeeperMap.cpp`: master removed
`.supports_parallel_insert` from the `KeeperMap` registration ("Preserve input
order for order-sensitive insert destinations"), the branch added
`.supports_deferred_load` next to it. Keep `.supports_deferred_load` only.

Adaptations to master that did not show up as textual conflicts:
- `IStorage::getSerializationHints` now takes the metadata snapshot; update the
  overrides in `StorageProxy` and `StorageTableProxy`.
- Master added `StorageProxy::supportsStreaming`, which the branch also added;
  drop the duplicate.
- The test `05816_streaming_queries_lazy_load_source`, added on master, pinned
  `system.tables.engine` of a table that is not loaded yet to `TableProxy`.
  This branch intentionally reports the real engine there, so the test now
  checks `engine` together with the new `is_loaded` column.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (the PR was conflicting) and pushed 0dfec0e.

  • Conflict in src/Storages/StorageKeeperMap.cpp: master removed .supports_parallel_insert from the KeeperMap registration, so only .supports_deferred_load is kept there.
  • IStorage::getSerializationHints takes the metadata snapshot on master now; the overrides in StorageProxy and StorageTableProxy are updated. StorageProxy::supportsStreaming was added on both sides, the duplicate is removed.
  • 05816_streaming_queries_lazy_load_source, added on master, pinned system.tables.engine of a not yet loaded table to TableProxy. This PR intentionally reports the real engine, so the test now checks engine together with is_loaded (MergeTree, 0).

The only red checks on the previous commit were the two Bugfix validation (functional tests) jobs, for 05511_table_function_proxy_rename_no_resolve and 05573_replicas_status_verbose_and_rejected_request. Both pass without the fix by design: the first guards against a deadlock that existed only in an intermediate state of this PR, and the second is an existing test that only got the no-parallel tag. No code change follows from that; whether to accept the job as is stays with the reviewer.

05569_lazy_load_tables_iceberg_snapshot_per_select stays in parallel_replicas_blacklist.txt until #132315 is merged.

The test failed in `Integration tests (amd_asan_ubsan, flaky)` and
`Integration tests (amd_msan, targeted)` with `assert 0 == 2450`: no row
reached `lazy.dest` within the 60 seconds the test waits.

A Kafka consumer is closed without leaving its consumer group
(`RD_KAFKA_DESTROY_F_NO_CONSUMER_CLOSE`), so the group keeps the consumer of
a detached table as a member until its session expires, and the consumer
created after `ATTACH DATABASE` gets no partition before that. The test
passed only when `DETACH DATABASE` came before the streaming task noticed
the materialized view, which it does within 500 ms, so that no consumer
existed yet. In the failed runs the consumer was created 2 ms before the
`DETACH`, was closed in the middle of joining the group, and the next
consumer logged `No assignment` for the rest of the test.

Wait for the first consumer to get its assignment before the reload, so
that it is always closed in the same state, and lower the session timeout
of the consumers in this test to the minimum the broker accepts (6 seconds
instead of the default 45), so that the consumer created after the reload
gets the partition in about 5 seconds.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113389&sha=0dfec0e3f5ae00b302c1ab5fe1591cd9632178dd&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29
ClickHouse#113389

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The only test failure was the PR's own test_lazy_load_tables/test.py::test_kafka_ingests_after_restart[ReplicatedMergeTree] (assert 0 == 2450) in Integration tests (amd_asan_ubsan, flaky) and Integration tests (amd_msan, targeted). It is a race in the test, not in the lazy loading: a Kafka consumer is closed without leaving its consumer group, so after DETACH DATABASE the group keeps the closed consumer as a member until its session expires, and the consumer created after ATTACH DATABASE gets no partition before that. The test passed only when the DETACH came before the streaming task noticed the materialized view (within 500 ms). In the failed runs the consumer was created 2 ms before the DETACH, was closed in the middle of joining the group, and the next one logged No assignment until the test gave up.

Fixed in f8280dd: the test waits for the first consumer to get its assignment before the reload, and the consumers in this test use a 6 second session timeout instead of the default 45. Locally the consumer created after the reload now gets the partition in about 5 seconds (44 seconds without the shorter timeout), and both engine variants pass.

CH Inc sync failed because the sync PR conflicted with the private master. I pushed a merge of this head with the private master to the sync branch, with the existing private adaptations re-applied; the sync PR is mergeable again and its CI is running.

alexey-milovidov and others added 6 commits November 23, 2026 11:49
… EMPTY`

`TRUNCATE TABLE alias IF EMPTY` asks the `Alias` for its row count, which the alias
takes from its target. A deferred table of a `lazy_load_tables` database reports an
unknown count until it is loaded, and an unknown count passed the emptiness check, so
a nonempty target was truncated through the alias instead of `TABLE_NOT_EMPTY`.

The target is now loaded before it is counted. `TRUNCATE` requires the right to
truncate the target to load it. `DROP` and `DETACH` remove only the alias, so they
load the target for a user who can see it, which is what the alias requires to report
the count of a loaded target.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…STOP` loads it

`SYSTEM STOP|START|PAUSE|CANCEL|REFRESH db.table` requires `SYSTEM STREAMING ENGINES`
for a streaming engine and `SYSTEM VIEWS` for a refreshable materialized view. For a
deferred table of a `lazy_load_tables` database only a user with neither grant was
rejected before the table was loaded, so a user with only `SYSTEM VIEWS` could load
(construct and start) a streaming table and got `ACCESS_DENIED` only after that.

The streaming engines are now registered with the `is_streaming` storage feature, and
a table that is not loaded yet is never a view, so the same decision is made from the
engine in the `CREATE` query before the table is loaded.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…by name again

`InterpreterAlterQuery` resolves the table by name a second time, because a concurrent
`EXCHANGE` can put another table under the name. If that table is a deferred table of
a `lazy_load_tables` database, it was loaded before the access check. It now gets the
same checks as the first resolution before it is loaded.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… the restricted user

The positive branch of `05838_lazy_load_tables_alias_access_before_load` ran as the
default user, so it did not cover a user who holds the rights on the target without
being a superuser.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… what it observes

The stand-in of a lazily loaded table reports the engine from the `CREATE` query and
forwards everything else to the loaded storage, so SQL cannot tell which of the two
objects the catalog holds. The test no longer claims to check when the stand-in is
replaced. It checks that `system.tables` and a read of the table give the same
answers while a query holds the stand-in and after that query is gone.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed ae9e9bb: the seven open review threads are addressed (replies in the threads), and master is merged (no conflicts).

  • TRUNCATE TABLE alias IF EMPTY (also DROP/DETACH ... IF EMPTY) loads an untouched lazy target of the Alias before it counts the rows, so a nonempty target is no longer truncated. Test: 05857_lazy_load_tables_truncate_alias_if_empty.
  • SYSTEM STOP|START|PAUSE|CANCEL|REFRESH db.table decides which grant an unloaded table requires from its engine (new is_streaming storage feature), so a user with only SYSTEM VIEWS no longer loads a streaming table. Test: 05858_lazy_load_tables_system_background_control_access.
  • ALTER repeats the checks before loading for the table it finds by name the second time.
  • 05838_lazy_load_tables_alias_access_before_load runs its positive branch as the restricted user; 05616_lazy_load_tables_replace_proxy_held is narrowed to what SQL can observe.

The only red check on the previous commit, Upgrade check (amd_release) (Cannot parse projection p (SELECT count() GROUP BY 0) during server startup), is not caused by this PR: the projection comes from 04627_lwd_rebuild_normal_projection_no_where on master, and the same failure hit PRs 133655, 101039, 125846, 123890, 133325 and 133299 between 2026-11-20 and 2026-11-23. The fix is in progress in #128105.

@groeneai

Copy link
Copy Markdown
Collaborator

#132315 is merged (2c466c2), so after the next master merge here 05569_lazy_load_tables_iceberg_snapshot_per_select can come out of tests/parallel_replicas_blacklist.txt.

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

comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! submodule changed At least one submodule changed in this PR.

Projects

None yet

5 participants