Repository navigation
Replace the proxy of a lazily loaded table with the table itself - #118699
Conversation
A database with `lazy_load_tables` attaches every table as a `StorageTableProxy` and keeps it behind that proxy forever, even after the table has been loaded. `StorageProxy` forwards a subset of `IStorage`, and everything that recognizes a table by its concrete type instead - about thirty `IStorage` virtuals that `MergeTree` overrides, plus every `dynamic_cast<MergeTreeData *>` - never sees the table. So `system.parts`, `system.parts_columns`, `system.detached_parts`, `system.mutations` and `system.replicas` stay empty for such a table, `AttachedReplicatedTable` is never counted, and a mutation or a `DELETE` is rejected outright with `Table engine MergeTree doesn't support mutations`. Once the table has been loaded there is no reason to keep the proxy in front of it. The database now notices the load on its lookup paths and puts the loaded storage in the table map and in the `DatabaseCatalog` UUID mapping in its place, so from then on the table is indistinguishable from an eagerly loaded one. The replacement has to happen in the database rather than in the proxy: the proxy loads the table from under the database mutex, through `DatabaseAtomic::renameTable` calling `tryCreateSymlink`, so it cannot take that mutex itself. The two objects are both alive and both reachable as the same table across the replacement: a query that resolved the table before it keeps a reference to the proxy and locks that, while a query that resolves it afterwards locks the loaded storage. Since `lockForShare`, `lockForAlter` and `lockExclusively` are not virtual, the proxy never forwarded them, and the two objects would have formed two independent lock domains - a `DROP` would not have waited for a `SELECT` that is still running. The loaded storage therefore adopts the proxy's `drop_lock` and `alter_lock`, via the new `IStorage::takeTableLocksFrom`, so the two keep excluding each other. Also forward the checks that gate a mutation, an `UPDATE` and a `DELETE`, so that those work as the very first statement addressed to a table that has not been loaded yet, before the replacement can have happened.
|
Workflow [PR], commit [05d6ef3] Summary: ✅
AI ReviewSummaryThe PR replaces an unused, loaded Consumers traced across the catalog replacement:
Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline findings; prior findings are addressed or no longer apply to the current implementation. |
… the load `04239_alter_rename_column_lazy_load_tables_104819` timed out: `ActionLocksManager` keys the locks it holds by the storage they were taken on, and that storage is the proxy when the table has not been loaded yet. The `SYSTEM START MERGES` that comes afterwards addresses the storage that replaced the proxy, does not find the lock and never lifts it, so the alter mutation the test parks behind `SYSTEM STOP MERGES` never finishes. Re-key those locks as part of the replacement, through the new `ActionLocksManager::transfer`. The locks themselves need no adjustment: a proxy forwards `getActionLock` to the storage it stands for, so they already belong to it. `getLoadedLazyTable` also has to stop waiting on `nested_mutex`. The database calls it with its own mutex held, while `getNested` keeps `nested_mutex` for as long as the table takes to load, so waiting there would hold the whole database up for the duration of a load. Reporting "not loaded yet" instead is harmless, because the next lookup replaces the proxy.
…d `DELETE` see the loaded table Two findings from the AI review of the previous commits. Cold `DELETE`: `InterpreterDeleteQuery` takes its metadata snapshot from the storage the catalog returned before anything loads the table, so for a `StorageTableProxy` it saw the constructor cache, which only has the columns, and its `dynamic_cast` to `MergeTreeData` failed on the proxy too. The first `DELETE` after `DETACH`/`ATTACH` on a `MergeTree` with projections and `lightweight_mutation_projection_mode = 'throw'` therefore skipped the guard and went on to drop the projections. The interpreter now loads the table up front through the new `IStorage::loadLazyTable` (the blocking counterpart of `getLoadedLazyTable`) and works with the storage itself. Action locks: re-keying the locks once, at the moment the database replaces the proxy, left a window for callers that already held the proxy pointer - `SYSTEM STOP/START ...` over a database iterates a snapshot of the tables - to add or remove a lock under the proxy key after the transfer. `add` and `remove` now canonicalize a lazily loaded table to the storage it stands for at call time, so both objects address the same locks and `transfer` is gone. The test gains a cold `DELETE` against a lazily loaded table with projections that has to be rejected. Co-Authored-By: Claude Fable 5.1 <[email protected]>
… dropped state with the proxy, and do not load tables in `ActionLocksManager::remove` `StorageAlias::supportsTrivialCountOptimization` resolved the target again and handed it the snapshot taken from the previous target. After the proxy of a lazily loaded table is replaced with the loaded `MergeTree`, the snapshot of the proxy has no `MergeTreeData::SnapshotData`, and `MergeTreeData::supportsTrivialCountOptimization` dereferenced a null pointer (`05137_row_policy_lazy_alias` in Fast test). Ask the storage the snapshot belongs to instead. Address review: a query that resolved the proxy before the replacement must see a `DETACH` or `DROP` that marked only the loaded storage. The lock functions now check the virtual `isDroppedOrDetached`, which `StorageTableProxy` forwards to the loaded storage. `getLoadedLazyTable` no longer uses `try_lock`, so it cannot spuriously report "not loaded". Address review: `ActionLocksManager::remove` no longer loads the table; an unloaded proxy cannot hold an action lock. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118699&sha=d0c7265846f74ed7e14911cb1d6cf12e6df2c353&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/CMakeFiles/dbms.dir/Interpreters/ActionLocksManager.cpp.o |
40.64 KiB | 306.34 KiB | +265.70 KiB (+653.78%) |
src/CMakeFiles/dbms.dir/Databases/DatabasesCommon.cpp.o |
458.57 KiB | 681.77 KiB | +223.21 KiB (+48.67%) |
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.
Slowest function optimization changes (ThinLTO)
Median per-function time ratio to the master baseline: programs/clickhouse ×0.63, programs/clickhouse-keeper ×0.66 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.
| Binary | Function | Master | PR | Δ vs median |
|---|---|---|---|---|
programs/clickhouse |
DB::registerFunctionConversion(DB::FunctionFactory&) |
5.9 s | 12.1 s | +8.4 s (+224%) |
programs/clickhouse |
_ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… |
3.5 s | 7.4 s | +5.2 s (+240%) |
Compile time of recompiled translation units
319 translation units recompiled, 2550 s compile time in total, 319 of them have a recent master baseline.
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
… lazy table proxy Address review: a `SYSTEM START ...` that resolved a `StorageTableProxy` before the database replaced it with the loaded storage lifted the lock under the loaded storage's key, but the wake-up `onActionLockRemove` landed on the `IStorage` no-op, so background work could stay asleep. The proxy now forwards it to the loaded storage (without loading the table). Also make `lockForShare` / `tryLockForShare` consult a virtual `isBeingRestarted`, which the proxy overrides to report the state of the loaded storage, so a stale proxy cannot be locked while `SYSTEM RESTART REPLICA` is restarting the table, same as `isDroppedOrDetached`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… both directions Previously only the proxy looked at the flags of the loaded storage. A query that switched to the loaded storage (e.g. `DELETE` through `loadLazyTable`) while the database still held the proxy did not see a `DETACH`, `DROP` or `SYSTEM RESTART REPLICA` that marked the proxy, and could reacquire the shared `drop_lock` of a detached or restarting table. Canonicalizing the map entry before setting the flags would not be enough either, because the load may finish after the flag is set. Now `is_dropped`, `is_detached` and `is_being_restarted` are shared between the proxy and the loaded storage by `takeTableLocksFrom`, the same way as the table-level locks, so marking either object is seen through both. This also removes the virtual `isDroppedOrDetached` / `isBeingRestarted` overrides. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failures: |
|
Both have a fixing PR in progress:
The current head |
alexey-milovidov
left a comment
There was a problem hiding this comment.
I didn't like the effort we went for adapting locks. Can we make the implementation way simpler, maybe with optimistically trying to replace StorageTableProxy with the actual table, maybe under a short lock? The goal is to make the implementation as simple as possible.
Address review #118699 (review): instead of making the proxy and the loaded storage share their table locks and lifecycle flags, replace the proxy optimistically, under the mutexes of the database and of the UUID mapping, and only when nobody else holds it. Then no query can be using the proxy and its own locks while others use the loaded storage, so none of the lock adaptation is needed. Removed: `IStorage::takeTableLocksFrom`, `SharedLifecycleFlag`, the shared `alter_lock`, `IStorage::isTableNotInUse`, `IStorage::getOwnStorageID` and the forwarding `getStorageID`, `getLoadedLazyTable`/`loadLazyTable`, the restart guard in `StorageTableProxy::getNested`, and the loading of lazy tables in `InterpreterUpdateQuery` and `InterpreterDeleteQuery` (master already resolves the proxy for the `DELETE` checks). The tests of the removed machinery are removed too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…DMapping` `google-runtime-int` rejected `long other_owners`. The only caller passes 1, so the method now always expects the mapping and one reference of the caller. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118699&sha=2e8b402b30c593ba357df4e3908beaad9cc76e4c&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 #118699 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…an throw in between Compute the attached counters of the proxy and of the loaded storage before the UUID mapping is replaced, so that no allocation can fail between replacing it and replacing the entry in `tables`, which would leave the two maps disagreeing for good. Test that the database hands out the loaded storage itself: `total_bytes_uncompressed` in `system.tables` is NULL for a proxy, which does not forward `totalBytesUncompressed`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov
left a comment
There was a problem hiding this comment.
This is non-perfect, but fine.
…obing `supportsTransactions` `StorageTableProxy` now forwards `supportsTransactions`, which loads a lazily loaded table. `InterpreterDropQuery::executeToTableImpl` asked it before checking access, so a user without the privilege could load the table and learn its engine from the `does not support transactions` message. Check the access of the operation first when a transaction is active. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t replaced A query that holds the proxy keeps it in place (`total_bytes_uncompressed` stays NULL, which the proxy does not forward), and the next lookup after that query is gone replaces it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ROP` authorization `CREATE OR REPLACE TABLE` drops the replaced table (or, on failure, its temporary table) under a random `_tmp_replace_*` name with `no_access_check`, having authorized the real name already. With `implicit_transaction = 1`, the early check before `checkStorageSupportsTransactionsIfNeeded` authorized that random name, failing with `ACCESS_DENIED` and leaving the replaced table behind. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The cleanup `KILL QUERY` before the reader starts logged `NOTHING_TO_KILL` on the server, which the test runner reports as fatal stderr: use `kill_throw_if_noop = 0`. With `serialize_query_plan = 1` (the `distributed plan` jobs), the plan that holds the proxy is replaced by a deserialized one that looks the table up anew, so the proxy is released in between and correctly replaced; the test then saw `held: MergeTree 1`. Keep `serialize_query_plan` off for the reader. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118699&sha=latest&name_0=PR PR: #118699 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…te_or_replace_transaction_drop_access` `05616`: the reader joined the table with `numbers(1000000)`, and the join emitted blocks of up to `max_joined_block_size_rows` rows despite `max_block_size = 1`, so `sleepEachRow` threw `TOO_SLOW` (`Requested: 93680000000 microseconds per block (of size 93680)`). The reader ended within a second, released the proxy, and the test saw `held: MergeTree 1`. `serialize_query_plan` was not the cause. Read the table alone, in blocks of one row, from 1000 rows. `05618`: the CI config enables `table_engines_require_grant`, so the user needs `TABLE ENGINE ON Memory`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118699&sha=383b18fe3804f8233c34b5a0bf10ee37b3b148fc&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20targeted%29 PR: #118699 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ndent of block sizes `max_block_size = 1` does not bound the blocks read from `MergeTree` either: a 1000-row part is read in one block, and `sleepEachRow(1)` throws `TOO_SLOW`. Use `function_sleep_max_microseconds_per_block = 0` instead; a long sleep still checks every second whether the query was killed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ClickHouse#118699 replaces a loaded `StorageTableProxy` with the loaded storage only when nobody else holds the proxy (`replaceUnusedTableInUUIDMapping` requires `use_count() == 2`); otherwise the next lookup tries again. The proxy does not forward `totalBytesUncompressed`, so `total_bytes_uncompressed IS NOT NULL` was a witness that the replacement had already happened. A concurrent catalog-wide `system.columns` scan holds a `StoragePtr` to every table for its whole lifetime, so when one covers the lookups after the load (00941 and 00938 on master f538dd0 / c19b253) the replacement is deferred and the column is NULL. Every other line passes either way. Remove the assertion; 05616_lazy_load_tables_replace_proxy_held checks the replacement with a wait. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since #118699 the database replaces a loaded `StorageTableProxy` with the loaded storage, so the unwrapping in the database iterator, the shared drop lock, the detached/dropped flag mirroring, and the `ActionLocksManager` keying are not needed. Their tests pass on master and are removed, as are the `Alias`/materialized view refresh changes made only so that `DESCRIBE` does not load a lazily loaded target. What remains is what still fails on master: - the proxy forwards the backup methods: `BACKUP ... PARTITIONS` of a table that has not been loaded was rejected, and `BACKUP` of a table whose proxy is held by another query wrote no data; - `_row_exists` is classified against the loaded storage, so `UPDATE ... SET _row_exists = 0` requires `ALTER DELETE`, not `ALTER UPDATE`; - `INSERT` checks the `INSERT` grant before the refresh that may load the table; - a materialized view refreshes the loaded storage of a lazily loaded target. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s replaced With `lazy_load_tables = 1`, a table nobody has read since the database was attached is a `StorageTableProxy`. The size check of the `DROP DATABASE` pre-flight loads it and may consume `force_drop_table`, and the exemption was remembered under the proxy. Since ClickHouse#118699 the database replaces an unused proxy by its loaded storage on the next lookup, so `executeToTableImpl` got the loaded storage, missed the exemption and checked the size again without the flag: an authorized `DROP DATABASE` was refused with `TABLE_SIZE_EXCEEDS_MAX_DROP_SIZE_LIMIT` after the tables were prepared for shutdown (merges cancelled). Record and look up the exemption by `resolveStorageProxy`, the loaded storage of a lazy proxy, which is what the database replaces it with. An unrelated storage swapped in under the same name still does not match. Reported by clickhouse-gh[bot]: ClickHouse#123694 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
A database with the
lazy_load_tablessetting attaches every table as aStorageTableProxyand keeps it behind that proxy forever, even after the table has been loaded.StorageProxyforwards a subset ofIStorage; everything that recognizes a table by its concrete type instead never sees the table. That is about thirtyIStoragevirtuals thatMergeTreeoverrides, plus everydynamic_cast<MergeTreeData *>.Reproduced on 26.8:
system.parts,system.parts_columns,system.detached_parts,system.mutations,system.replicasandsystem.replication_queuestay empty for such a table, andAttachedReplicatedTableis never counted.Once the table has been loaded there is no reason to keep the proxy in front of it. On its lookup paths, the database now optimistically replaces a loaded proxy with the loaded storage, in its table map and in the
DatabaseCatalogUUID mapping, but only if nobody else holds the proxy. The check is done under the mutexes of the database and of the UUID mapping, where nobody can obtain the proxy anew, so no query can keep using the proxy and its own table locks while others use the loaded storage. If the proxy is still in use, it is left in place, and the next lookup tries again. Both maps have to be updated, becauseDatabaseCatalog::getTableImplanswers aStorageIDthat already carries a UUID straight from the UUID mapping.The rest is small:
ActionLocksManagerkeys a lock taken through a loaded proxy by the loaded storage, so thatSYSTEM START MERGESaddressed to the storage that replaced the proxy lifts aSYSTEM STOP MERGEStaken through the proxy.StorageTableProxyforwardsonActionLockRemove,supportsTransactionsandisStaticStorage.StorageAlias::supportsTrivialCountOptimizationasks the storage its snapshot was taken from, rather than resolving the target again, which may have been replaced in between.A table that has never been accessed is still a proxy, so this does not make
system.partscomplete for a database that has just started up - that is what lazy loading is.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed tables in a database with the
lazy_load_tablessetting staying hidden behind a lightweight proxy after they have been loaded. They were missing fromsystem.parts,system.parts_columns,system.detached_parts,system.mutationsandsystem.replicas, and were not counted in theAttachedReplicatedTablemetric.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/118699]
Version info
26.11.1.2053-master(included in26.11and later)