Skip to content

Fix BACKUP and access checks for lazily loaded tables that are still a proxy - #117972

Open
alexey-milovidov wants to merge 70 commits into
masterfrom
lazy-table-proxy-system-tables-117420
Open

alexey-milovidov wants to merge 70 commits into
masterfrom
lazy-table-proxy-system-tables-117420

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

A table of a database with lazy_load_tables is 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 fixed system.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:

  • BACKUP silently 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 forward backupData / restoreDataFromBackup, so the default no-op of IStorage was used. On master this is now hidden for an idle table: the backup_metadata_only storage policy check loads the table, and the lookup that follows replaces the proxy. But while a concurrent query holds the proxy, a 10-row MergeTree table is still backed up as empty, and the RESTORE succeeds with 0 rows. BACKUP ... PARTITIONS of a table that has not been loaded is rejected with Table engine MergeTree doesn't support partitions, because supportsBackupPartition is asked of the proxy. The proxy now forwards supportsBackupPartition, backupData, restoreDataFromBackup, finalizeRestoreFromBackup (only to a loaded table), and applyMetadataChangesToCreateQueryForBackup (loads only a Replicated* table, so structure_only backups do not load every table).
  • UPDATE ... SET _row_exists = 0 checked against the wrong privilege. Before the table is loaded, the proxy reports only the columns of the CREATE TABLE query, so _row_exists was classified as a regular column: a user with only ALTER UPDATE could delete rows, and a user with only ALTER DELETE was refused. The classification now asks the loaded storage, but does not load the table for a user who has neither privilege.
  • INSERT through an Alias loads the target before the access check. The refresh of external metadata loads the lazily loaded target of an Alias, so a user without any grants saw the initialization error of the engine (e.g. a removed named collection) instead of ACCESS_DENIED, and loaded the table. INSERT (sync and async) now checks that INSERT is granted on the table, and on every table of the chain of an Alias (as its write requires), before the refresh.
  • A materialized view reads a stale snapshot of a lazily loaded Iceberg target. StorageMaterializedView::read refreshed 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):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed BACKUP of a table of a database with lazy_load_tables that has not been loaded yet or is in use by another query, which could back up no data or reject PARTITIONS; fixed the privilege check of UPDATE ... SET _row_exists = 0 and of INSERT through an Alias for such tables.

🤖 Generated with Claude Code


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

…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
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [02085ca]

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 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: _row_exists classification still uses unloaded metadata when the table is reached through an Alias.

Findings

❌ Blockers

  • src/Interpreters/InterpreterAlterQuery.cpp:926: resolveStorageProxyLoading does not follow StorageAlias. For an alias over an untouched lazy MergeTree, its metadata getter returns the proxy's cached columns without the virtual _row_exists, so the helper reports Regular. A user with SELECT, ALTER on the target but only SELECT, ALTER UPDATE on the alias can consequently execute the first UPDATE alias_t SET _row_exists = 0 without ALTER DELETE on the alias. Once the target loads, the same authorization correctly fails. An alias user with only ALTER DELETE is instead incorrectly rejected on first access. Resolve the effective target's metadata through alias chains after the appropriate privilege gate, and cover both privilege combinations before and after materialization. Inline finding.
Tests
  • ⚠️ Add a focused stateless regression for _row_exists permissions through an Alias over an unloaded lazy table. The existing 05333_lazy_load_tables_row_exists_privilege exercises only direct table access. The finding is based on tracing the current code; no runtime reproduction was performed in this review environment.
  • The current head's Fast test report passes the backup, direct permissions, and insertion-access regressions. The Iceberg regressions are skipped there; targeted stateless tests and bugfix validation are still pending.
Final Verdict

Status: ❌ Block

Correct _row_exists classification through aliases and add the cold-target permissions regression before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 3, 2026
Comment thread src/Databases/DatabasesCommon.cpp Resolved
Comment thread src/Storages/StorageProxy.h Resolved
@zlareb1

zlareb1 commented Sep 3, 2026

Copy link
Copy Markdown
Member

Two problems with the transparency as implemented, both traced at the current head of this PR against master 302f28fb673f.

1. Forwarding supportsLightweightDelete silently bypasses the lightweight_mutation_projection_mode = 'throw' guard, so a DELETE on a lazy-loaded table with projections drops the projections instead of throwing. The guard in InterpreterDeleteQuery.cpp:118-126 resolves the mode by downcasting the catalog object: if (const auto * merge_tree_data = dynamic_cast<const MergeTreeData *>(table.get())). For a table of a lazy_load_tables database, table is the StorageTableProxy, the cast returns nullptr, and the check is skipped entirely — the same catalog-pointer pattern this PR fixes elsewhere. Execution then treats THROW as DROP: MutateTask.cpp:2985-2991 sets lightweight_delete_drops_projections for both DROP and THROW (the enforcement of THROW lives only in the interpreter guard), so should_create_projections = false and the mutated parts lose their projections silently. Default mode is THROW (MergeTreeSettings.cpp:2090). Before this PR the shape was unreachable on lazy tables because DELETE was rejected outright (#117440); on non-lazy tables the cast succeeds and the query throws. Repro sketch: CREATE DATABASE d ... SETTINGS lazy_load_tables = 1, a MergeTree table with a projection, insert, DETACH DATABASE / ATTACH DATABASE, DELETE FROM d.t WHERE ... — with this PR it succeeds and the rewritten parts have no projection; the non-lazy control throws SUPPORT_IS_DISABLED. The guard should resolve the settings through the nested storage (or through a virtual on IStorage) rather than a downcast of the catalog object.

2. getTablesIterator now blocks on nested_mutex while holding the database mutex, so one materializing table stalls every query on the database. The new unwrapMaterializedLazyTable runs inside std::lock_guard lock(mutex) in DatabaseWithOwnTablesBase::getTablesIterator and calls StorageTableProxy::tryGetNested, which takes std::lock_guard{nested_mutex} — a blocking acquire. getNested holds nested_mutex across the entire first-access materialization (createTableFromAST including loadDataParts, plus startup), which is unbounded on a large table or with slow Keeper. While that load is in flight, any system.tables / SHOW TABLES / system.parts scan — including the periodic ServerAsynchronousMetrics thread, which iterates all databases — blocks holding the database mutex, and with it tryGetTableNoWait, i.e. every query touching any table of that database, for the duration of the load. Before this PR the iterator never touched nested_mutex. A std::unique_lock{nested_mutex, std::try_to_lock} in tryGetNested (treating a mid-load proxy as not yet materialized, as the iterator already does for unloaded tables) keeps the fix without the coupling.

A smaller note: the TablesStatus handler (TCPHandler) and restoreMetadataAfterConvertingToReplicated also resolve through the catalog pointer and downcast to StorageReplicatedMergeTree, so #117441 and #117413 remain open after this PR — the iterator unwrap does not reach them.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 02085ca80 with master f455c7537 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

12 object files changed (-684.74 KiB total), 1 added.

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.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 4, 2026
alexey-milovidov and others added 2 commits September 10, 2026 15:25
`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thank you, both are real and both are fixed in e44ad55.

1. lightweight_mutation_projection_mode guard. Confirmed, and the root cause is a little deeper than the downcast alone: InterpreterDeleteQuery takes the metadata snapshot before anything materializes the stand-in, and an untouched StorageTableProxy answers from the columns cached out of the CREATE TABLE query alone - so metadata_snapshot->hasProjections() is already false and the guard is skipped before the downcast is even reached. Fixing only the downcast was not enough; I checked that on a build. The table is now resolved to the real storage right after the share lock is taken (a DELETE materializes it in any case), and both the metadata snapshot and the downcast go through that. Covered in 05175_lazy_load_tables_proxy_transparency: a MergeTree table with a projection in a lazy_load_tables database, detached and re-attached, now refuses the DELETE with lightweight_mutation_projection_mode is set to THROW and keeps its projection parts; before the fix the query succeeded and the projection was gone, exactly as you described.

2. getTablesIterator blocking on nested_mutex. Agreed - getNested holds nested_mutex across the whole first-access load, and waiting for it under the database mutex couples every query on the database to that load. Adopted your suggestion: tryGetNestedWithoutWaiting uses std::try_to_lock and reports a table that is being materialized right now as not materialized yet, which is exactly how the iterator already treats an untouched one, and that is the variant the iterator uses. The blocking tryGetNested is kept for the action-lock bookkeeping, which does not hold any wider lock and where a stale answer would misplace a lock.

On the smaller note: the TablesStatus handler in TCPHandler and DatabaseOrdinary::restoreMetadataAfterConvertingToReplicated are indeed not reached by the iterator unwrap, and #117441 / #117413 stay open after this pull request. I left them out on purpose: the first one needs a cluster to test meaningfully, and the second one cannot simply unwrap - the flag is processed during startup, where a lazy table has no nested storage yet and materializing it there would defeat lazy_load_tables, so it needs a decision about when the conversion flag is honoured. Both deserve their own change rather than a blind one-liner here.

alexey-milovidov and others added 2 commits September 17, 2026 19:57
…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]>
Comment thread src/Storages/StorageProxy.h Resolved
Comment thread src/Storages/StorageProxy.h Resolved
Comment thread src/Storages/StorageProxy.h Resolved
Comment thread src/Databases/DatabasesCommon.cpp Resolved
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 23, 2026
…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
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI reds on 16d8bf7c are unrelated to this PR:

  • Storage memory check / 05_multiple_tables.sql (PR=+250,512 bytes): same signature as the known race between the 04_add_projection.sql mutation task and the heap-dump checkpoint; fix in progress: Wait for background tasks before each storage memory checkpoint #121545
  • Performance Comparison (arm_release, master_head, 2/6) / order_by_read_in_order #1 (+18% on a 15 ms query): the PR only changes lazy-load stand-in handling, which that test does not use.

@groeneai, investigate the order_by_read_in_order failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117972&sha=16d8bf7c6a4040b4a32f549bef4124c4d7d2c167&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%202%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

alexey-milovidov and others added 2 commits September 26, 2026 11:33
…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]>
Comment thread src/Storages/StorageAlias.cpp Resolved
alexey-milovidov and others added 2 commits October 27, 2026 21:57
…` 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]>
Comment thread src/Storages/StorageAlias.cpp Resolved
Comment thread src/Storages/StorageMerge.cpp Resolved
alexey-milovidov and others added 2 commits October 28, 2026 14:21
…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]>
Comment thread src/Storages/StorageAlias.cpp Resolved
alexey-milovidov and others added 3 commits October 29, 2026 17:33
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (clean merge, no file overlaps with this PR, and the build passes locally).

The failures on the previous commit (97fdca24) look unrelated to this PR:

@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 ON CLUSTER DDL entries after the upgrade, mainly Failed to make internal backup ... Query was cancelled) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the failure my open #125562 fixes: it skips 05082_kill_and_system_on_cluster_access_types in the stress phase of the upgrade check.

The logs of 97fdca24 show the same chain as the other carriers. The previous release (26.10.2.103) retried the 05082 KILL PART_MOVE_TO_SHARD ... ASYNC entry query-0000000019 222 times between 22:07:30 and 22:25:54 (Code: 999, Session expired every time) and never started a later entry. The 05289 BACKUP (query-0000000024), the two 02423 CREATE TABLE entries for the same table (query-0000000027, query-0000000031) and the 02907 BACKUP (query-0000000035) waited behind it, and KILL QUERY WHERE 1 SYNC at 22:22:53 cancelled the backup initiators. The upgraded server executed query-0000000019 at 22:26:35 and then replayed the backlog: both backups fail with Got error from the initiator ... Query was cancelled, and the second CREATE TABLE hits TABLE_ALREADY_EXISTS.

26.10.2.103 already contains #122132, which handles only the No node part, so the previous release keeps wedging on Session expired; the runner-side skip covers both. #125562 is green and mergeable but has no review yet.

…`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the open review thread in 77b8fa9: DESCRIBE of a materialized view no longer needs the view's definer to exist. Thanks @groeneai for tracing the upgrade-check chain to #125562.

The failures on c6daf5df are unrelated to this PR, and each one has an open fix:

# Conflicts:
#	src/Interpreters/InterpreterAlterQuery.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master to resolve the conflict in src/Interpreters/InterpreterAlterQuery.cpp. It was only in the includes: the PR adds Access/ContextAccess.h and master added Access/EnabledRowPolicies.h, so the merge keeps both. The clickhouse binary builds locally after the merge.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fixed the Fast test failure of 05175_lazy_load_tables_proxy_transparency in 53a69de. The last master merge brought in a reworded error message for a DELETE on a table with projections and lightweight_mutation_projection_mode = 'throw', so the test's grep for the old text found nothing. The test now matches the error code SUPPORT_IS_DISABLED. The Finish Workflow failure only followed from it: the bugfix validation jobs were dropped after the Fast test failure.

alexey-milovidov and others added 3 commits November 8, 2026 12:43
…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]>
@alexey-milovidov alexey-milovidov changed the title Make the lazy-load table stand-in transparent to system tables, DML and BACKUP Fix BACKUP and access checks for lazily loaded tables that are still a proxy Nov 14, 2026
alexey-milovidov and others added 2 commits November 20, 2026 23:58
…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]>
alexey-milovidov and others added 2 commits November 24, 2026 03:38
… 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);

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] 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.

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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BACKUP of a lazy-loaded (lazy_load_tables=1) MergeTree/ReplicatedMergeTree table silently backs up no data

3 participants