Repository navigation
Fix BACKUP and access checks for lazily loaded tables that are still a proxy - #117972
alexey-milovidov wants to merge 70 commits into
Conversation
…nd `BACKUP`
A table of a database with `lazy_load_tables` is kept in the catalog as a stand-in
(`StorageTableProxy`) that materializes the real storage on first access; the catalog
pointer is never swapped, so everything that inspects the storage object itself sees the
stand-in forever, not just before the first access:
- the `system.parts` / `system.parts_columns` / `system.replicas` family recognizes an
engine by downcasting the object it gets from the database iterator, so such a table was
permanently absent from them;
- `supportsDelete`, `supportsLightweightDelete`, `supportsLightweightUpdate` and
`checkMutationIsPossible` were not forwarded, so `DELETE FROM` was rejected with "DELETE
query is not supported for table" and every mutation with "Table engine TableProxy
doesn't support mutations";
- `backupData` / `restoreDataFromBackup` were not forwarded either, so `BACKUP` wrote the
table definition with no data at all and reported success, and restoring it silently
produced an empty table.
The capability predicates and the backup methods are now forwarded by `StorageProxy` like
the rest of the data-affecting interface, and the database iterator hands out the real
storage once it has been materialized. A table that has not been accessed yet is still left
as the stand-in there, because materializing it in the iterator would load every lazy table
of the server, which is what the setting avoids.
Closes: #117420
Closes: #117426
Closes: #117440
|
Workflow [PR], commit [02085ca] Summary: ❌
AI ReviewSummaryThe PR forwards backup operations through lazy table proxies, checks insertion privileges before refreshing alias targets, and refreshes materialized-view targets before reading. One authorization defect remains: Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Correct |
|
Two problems with the transparency as implemented, both traced at the current head of this PR against master 1. Forwarding 2. A smaller note: the |
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/Storages/StorageTableProxy.cpp.o |
new | 316.78 KiB | +316.78 KiB |
src/CMakeFiles/dbms.dir/Interpreters/ActionLocksManager.cpp.o |
341.29 KiB | 47.11 KiB | -294.18 KiB (-86.20%) |
src/CMakeFiles/dbms.dir/Interpreters/InterpreterDropQuery.cpp.o |
723.27 KiB | 456.24 KiB | -267.04 KiB (-36.92%) |
src/CMakeFiles/dbms.dir/Databases/DatabasesCommon.cpp.o |
764.23 KiB | 522.96 KiB | -241.27 KiB (-31.57%) |
src/CMakeFiles/dbms.dir/Storages/StorageAlias.cpp.o |
673.76 KiB | 513.69 KiB | -160.07 KiB (-23.76%) |
src/CMakeFiles/dbms.dir/Databases/DatabaseOrdinary.cpp.o |
930.12 KiB | 885.71 KiB | -44.42 KiB (-4.78%) |
716 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.
Compile time of recompiled translation units
38 translation units recompiled, 241 s compile time in total, 37 of them have a recent master baseline.
…stem-tables-117420
`ActionLocksManager` keys the locks by the storage object, and the same table reaches it either as the lazy-load stand-in the catalog holds (`SYSTEM STOP MERGES db.table`) or as the storage behind it (the server-wide `SYSTEM STOP MERGES`, which goes through the database iterator this pull request changed). Key by the storage that owns the lock in both cases, so that a `SYSTEM START` under one spelling releases a lock taken under the other, and forward `onActionLockRemove` to a materialized nested storage. `BackupEntriesCollector` and `RestorerFromBackup` answer `supportsBackupPartition` before they reach `backupData` / `restoreDataFromBackup`, so it has to be forwarded as well - otherwise `BACKUP TABLE ... PARTITIONS ...` of a lazy table is still rejected with `Table engine TableProxy doesn't support partitions`. `DELETE` resolves `lightweight_mutation_projection_mode` by downcasting the storage, and reads the metadata before anything materializes the stand-in, whose cached metadata holds the columns of the `CREATE TABLE` query alone and so has no projections. The guard was therefore skipped and the `THROW` mode silently degraded to dropping the projections. Resolve the table to the real storage up front - a `DELETE` materializes it in any case. `getTablesIterator` holds the database mutex, so it must not wait for a materialization that is in flight in another thread: `getNested` holds `nested_mutex` across the whole first-access load, and blocking on it would stall every query on the database for that time. Treat a table that is being materialized right now as not materialized yet, as an untouched one already is. The regression test was using a fixed database name, which collides with itself in the flaky check; it is now two shell tests with unique names, covering the partition backup and restore, the projection guard and both spellings of `SYSTEM START/STOP MERGES`. Each of the three fixes was verified against a control binary with that fix reverted. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Thank you, both are real and both are fixed in e44ad55. 1. 2. On the smaller note: the |
…stem-tables-117420
…rage in `DELETE` `InterpreterDeleteQuery` resolved the real storage behind a lazy-load stand-in into `engine_table`, but still called `updateExternalDynamicMetadataIfExists` on the catalog object. `StorageProxy` does not forward that hook, so for a lazy `StorageObjectStorage` the refresh was a no-op and the metadata snapshot was taken from a stale state while `mutate` refreshed and executed against a newer one. Ask the materialized storage instead, and use the same object for every step of the `DELETE` path - capability predicates, `checkMutationIsPossible`, the non-determinism check, `MutationsInterpreter::validate` and `mutate` - so the validation and the execution reason about one and the same storage state. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…hout views Two review findings on the write-side allowlist this branch added, plus what fixing the second one exposed. `StorageProxy`, the stand-in a `lazy_load_tables` database keeps in the catalog until a table is first accessed, forwards `supportsReplication()` but not `isMergeTree()`, so the allowlist read `false` for a lazily attached `ReplicatedMergeTree` target and refused the distributed write for it: the branch took the fan-out away from those targets, measured as 3 INSERT executions before and 1 after. The classification now resolves the stand-in first, with the same file-local helper `src/Analyzer/ValidationUtils.cpp` already uses for its `isRemote` call sites. Resolving costs nothing here: this is the table the INSERT is about to write into, so the nested storage is materialized moments later anyway. Once the in-flight proxy-transparency work (ClickHouse#113389, ClickHouse#117972) lands, `table` arrives already resolved and the helper becomes a no-op rather than a conflict. The direct target replicating is also not enough. Every replica pushes its own slice of the coordinated read through the target's dependent materialized views, so a view target that does not replicate keeps a different subset of the rows on each replica: measured on three nodes, a `ReplicatedMergeTree` target feeding a plain `MergeTree` view left the view with 0/100000/200000 of 300000 rows per node, and a read of the view from the node that issued the INSERT returned none of them. The write fan-out inside a single INSERT already fails closed on this, on the presence of a dependent view rather than on a proof that the reachable view graph converges, and this reuses that predicate (`InsertDependenciesBuilder::forwardedInsertReachesDependentView`) so a replicated view graph, which does converge, is refused too. Proving convergence recursively would restore the distributed write for that shape; it belongs behind that predicate, not here. That predicate resolves a forwarding chain to its end, which leaves `Alias`: besides `MergeTreeData` it is the only storage answering `isMergeTree()` true, it answers it from the table it points at, and inserting into it pushes the views attached to the alias itself as well (03636_storage_alias_basic asserts that), which the probe skips at every hop it follows. An alias target was therefore still admitted with a non-replicated view hanging off the alias, measured as 3 INSERT executions. Rather than enumerate a chain whose middle hops are not reachable from here, the allowlist now requires a concrete table, so `Alias` is refused whether or not a view is attached. All four cases are pinned by stateless tests whose oracle is the INSERT execution count from `system.query_log`, with a no-view arm as the control that the rig distributes the write at all.
…stem-tables-117420 # Conflicts: # src/Interpreters/InterpreterDeleteQuery.cpp
|
🕵 CI reds on
@groeneai, investigate the |
…ackup` through the lazy stand-in, validate `ALTER` against the real storage - `StorageProxy` forwarded `supportsLightweightUpdate` but not `updateLightweight`, so `UPDATE` (and `DELETE` with `lightweight_delete_mode = 'lightweight_update_force'`) on a re-attached lazy table passed the check and then failed with `Lightweight updates are not supported by storage TableProxy`. - `RestorerFromBackup` calls `finalizeRestoreFromBackup` on the catalog object, which stayed a no-op on the stand-in (e.g. `EmbeddedRocksDB` did not reopen its read-only handles). - `InterpreterAlterQuery::runCommandSegments` validated mutations with `MutationsInterpreter` on the stand-in, which hides `MergeTreeData`, so `alter_column_secondary_index_mode` and `share_nested_offsets` fell back to defaults. Materialize the table first, as `DELETE` does. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…locks and drop tracking `getTablesIterator` hands out the storage behind a materialized lazy-load stand-in, while `DROP` and `TRUNCATE` resolve the stand-in from the catalog. So `BACKUP` and `Merge` locked a different `drop_lock` than `DROP` / `TRUNCATE`, and `DatabaseAtomic` waited for the stand-in alone to become unused before dropping the data or allowing a re-`ATTACH`. - `IStorage::shareDropLockWith`: the nested storage adopts the stand-in's `drop_lock` when it is materialized, before `startup`. - `DatabaseCatalog::enqueueDroppedTableCleanup` and `DatabaseAtomic::detachTable` track the storage behind a materialized stand-in; the stand-in references it, so its users are covered as well. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…` and materialized views `StorageAlias` and `StorageMaterializedView` forward the refresh of external metadata only to a lazy-load target that is already materialized, so that `DESCRIBE` does not load it. Two paths that use the target relied on it being materialized: - The analyzer (and the old interpreter) resolve the columns of a `SELECT` through an `Alias` right after the refresh. For an untouched target they came from its `CREATE TABLE` query, so the first query after an external schema change failed with `UNKNOWN_IDENTIFIER`. Load the targets of an `Alias` there before the refresh. - `InterpreterAlterQuery` and `InterpreterDeleteQuery` loaded only the immediate target, so for `Alias` -> materialized view -> inner Iceberg table the refresh stopped at the inner stand-in and the mutation ran against the old schema (a `LOGICAL_ERROR` exception). Load every target along the chain of `Alias` tables and materialized views. Both use the new `loadLazyTargetsOfAliasesAndViews`, which only loads; the operations still go through every wrapper. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…schema inference An `Alias` forwards `updateExternalDynamicMetadataIfExists` only to a target that is already materialized, so the synchronous and asynchronous `INSERT` paths took the insertion schema from the `CREATE TABLE` query of an unloaded lazy target, and `Merge` schema inference loaded only the immediate target of an alias, missing a lazy table behind successive aliases. Use `loadLazyTargetsOfAliasesAndViews` in all three places after authorization and before the refresh. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…stem-tables-117420
…and `loop` `InsertDependenciesBuilder::observePath` refreshed a dependent target of a materialized view without materializing the lazy-load target of an `Alias`, so the view captured the old schema while `AliasSink` built the pipeline of the target with the new one, and the first `INSERT` failed with a `LOGICAL_ERROR` exception. The `loop` table function had the same problem and failed with `UNKNOWN_IDENTIFIER`. Both now call `loadLazyTargetsOfAliasesAndViews` before the refresh. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged The failures on the previous commit (
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117972&sha=97fdca24e37acddccadea7a6046eda24c51e380c&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 (the upgrade check flags errors from replaying stale |
|
This is the failure my open #125562 fixes: it skips The logs of 26.10.2.103 already contains #122132, which handles only the |
…`DESCRIBE` `StorageMaterializedView::updateExternalDynamicMetadataIfExists` forwards the refresh to the target under the `SQL SECURITY` context of the view, which requires the definer to exist. `DESCRIBE` asked for that refresh, so describing a view whose definer was renamed failed with `UNKNOWN_USER`, although a view exposes its own declared columns and the refresh of its target cannot change them. `DESCRIBE` now skips the refresh for a materialized view, also behind an `Alias`; the mutation paths keep refreshing the target under the definer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Addressed the open review thread in 77b8fa9: The failures on
|
# Conflicts: # src/Interpreters/InterpreterAlterQuery.cpp
|
🕵 Merged |
…ELETE` error `master` reworded the error that `DELETE` throws for a table with projections and `lightweight_mutation_projection_mode = 'throw'`, so the test's `grep` for the old text found nothing. Match the error code `SUPPORT_IS_DISABLED` instead of the wording. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117972&sha=latest&name_0=PR&name_1=Fast%20test PR: #117972 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Fixed the |
…stem-tables-117420 Resolved conflicts in `InterpreterAlterQuery.cpp` and `InterpreterDeleteQuery.cpp`: keep master's `validation_context` with `setAnalyzingBackgroundExpressions`, applied to the PR's `engine_table`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…stem-tables-117420 # Conflicts: # src/Databases/DatabasesCommon.cpp # src/Interpreters/ActionLocksManager.cpp # src/Interpreters/InterpreterAlterQuery.cpp # src/Storages/StorageTableProxy.h
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]>
BACKUP…lds the proxy Add two regression tests in which a concurrent reader keeps the `StorageTableProxy` of a loaded table of a database with `lazy_load_tables` in the catalog: - `05839_lazy_load_tables_backup_proxy_held`: `BACKUP` of such a table and `RESTORE` into another table. Without the `StorageTableProxy::backupData` override the restored table has 0 rows instead of 100. - `05840_lazy_load_tables_mv_external_snapshot_proxy_held`: the Iceberg target of a materialized view gets new snapshots through the view and from a table outside of the database. Without `resolveStorageProxyLoading` in `StorageMaterializedView::readImpl` the view keeps reading the old snapshot. Co-Authored-By: Claude Fable 5.2 <[email protected]>
… refresh The check added before `updateExternalDynamicMetadataIfExists` covered only the table named in the query. `StorageAlias::write` requires `INSERT` on the target as well, but the refresh of an `Alias` loads the lazily loaded target first, so a user with a grant on the alias alone still loaded the table and saw its initialization error instead of `ACCESS_DENIED`. `StorageAlias::checkAccessThroughChain` checks the table-level access on every table of the chain without loading the target, and `INSERT` (sync and async) calls it before the refresh. Co-Authored-By: Claude Fable 5.2 <[email protected]>
| && !access->isGranted(AccessType::ALTER_UPDATE, storage_id.database_name, storage_id.table_name)) | ||
| return RowExistsColumnKind::Unknown; | ||
| } | ||
| const auto metadata_snapshot = resolveStorageProxyLoading(storage)->getInMemoryMetadataPtr(context_, false); |
There was a problem hiding this comment.
[Blocker] Resolve lazy targets through Alias before classifying _row_exists
resolveStorageProxyLoading only unwraps StorageProxy; a StorageAlias passes through unchanged. For alias_t -> lazy_db.t immediately after reattaching lazy_db, StorageAlias::getInMemoryMetadataPtr therefore still returns the untouched target proxy's cached columns, without the virtual _row_exists. This helper returns Regular, so InterpreterUpdateQuery authorizes UPDATE alias_t SET _row_exists = 0 ... with ALTER UPDATE on the alias instead of ALTER DELETE.
For example, give a user SELECT, ALTER on the target (satisfying StorageAlias::updateLightweight's target-side check), but only SELECT, ALTER UPDATE on the alias. With the target configured for lightweight updates, the first such update after database reattachment can delete rows without ALTER DELETE on the alias. Once the target is loaded, the same operation correctly requires that missing privilege. Conversely, an alias user with only ALTER DELETE is incorrectly refused on first access.
Please obtain the effective target's virtual-column metadata through alias chains, preserving authorization before materialization, and add a cold-target permissions regression through an alias. The current regression only addresses the lazy table directly. This finding follows the current code paths; no local server was available for runtime reproduction.
A table of a database with
lazy_load_tablesis kept in the catalog as a proxy (StorageTableProxy) that loads the real storage on first access. Since #118699, the database replaces a loaded proxy with the loaded storage on lookup, if nobody else holds the proxy. That fixedsystem.parts/system.replicas(#117420), and most of what this PR originally did is not needed any more. What remains are the paths that still reach the proxy, because the table has not been loaded yet, or because another query holds the proxy so it has not been replaced yet:BACKUPsilently backs up no data (BACKUP of a lazy-loaded (lazy_load_tables=1) MergeTree/ReplicatedMergeTree table silently backs up no data #117426). The proxy did not forwardbackupData/restoreDataFromBackup, so the default no-op ofIStoragewas used. On master this is now hidden for an idle table: thebackup_metadata_onlystorage policy check loads the table, and the lookup that follows replaces the proxy. But while a concurrent query holds the proxy, a 10-rowMergeTreetable is still backed up as empty, and theRESTOREsucceeds with 0 rows.BACKUP ... PARTITIONSof a table that has not been loaded is rejected withTable engine MergeTree doesn't support partitions, becausesupportsBackupPartitionis asked of the proxy. The proxy now forwardssupportsBackupPartition,backupData,restoreDataFromBackup,finalizeRestoreFromBackup(only to a loaded table), andapplyMetadataChangesToCreateQueryForBackup(loads only aReplicated*table, sostructure_onlybackups do not load every table).UPDATE ... SET _row_exists = 0checked against the wrong privilege. Before the table is loaded, the proxy reports only the columns of theCREATE TABLEquery, so_row_existswas classified as a regular column: a user with onlyALTER UPDATEcould delete rows, and a user with onlyALTER DELETEwas refused. The classification now asks the loaded storage, but does not load the table for a user who has neither privilege.INSERTthrough anAliasloads the target before the access check. The refresh of external metadata loads the lazily loaded target of anAlias, so a user without any grants saw the initialization error of the engine (e.g. a removed named collection) instead ofACCESS_DENIED, and loaded the table.INSERT(sync and async) now checks thatINSERTis granted on the table, and on every table of the chain of anAlias(as itswriterequires), before the refresh.StorageMaterializedView::readrefreshed the external metadata of the proxy of its target, which does not forward it, so after the target was loaded the view kept reading the snapshot it was loaded with. It now refreshes the loaded storage.Related: #118699
Closes: #117426
Related: #117440
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Fixed
BACKUPof a table of a database withlazy_load_tablesthat has not been loaded yet or is in use by another query, which could back up no data or rejectPARTITIONS; fixed the privilege check ofUPDATE ... SET _row_exists = 0and ofINSERTthrough anAliasfor such tables.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/117972]