Skip to content

Resolve lazily loaded table proxies before casting to an engine type - #121332

Merged
evillique merged 21 commits into
ClickHouse:masterfrom
evillique:storage-cast-style-check
Oct 2, 2026
Merged

evillique merged 21 commits into
ClickHouse:masterfrom
evillique:storage-cast-style-check

Conversation

@evillique

@evillique evillique commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

A table in a database with lazy_load_tables is reached through StorageTableProxy, so a cast of the catalog pointer to an engine type sees only the proxy and the table is silently skipped: it never shows up in system.parts or system.replicas, and SYSTEM SYNC REPLICA refuses it. castStorage<T>(ptr, DeferredTable::Load | Skip) resolves the proxy chain before casting and replaces every such cast, and a style check forbids the raw form from now on. Eager tables are unaffected, and Distributed, Buffer, MaterializedPostgreSQL, Merge and Memory are now always eager, since deferring them cancels background work or saves nothing. The rest of the lazy_load_tables fixes stay in #113389.

Closes: #117420
Closes: #122297
Related: #113389

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 into CHANGELOG.md):

Tables in a database with lazy_load_tables were missing from system.parts, system.replicas and related system tables, and refused by replica commands, after a restart.


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

Version info

  • Merged into: 26.10.1.1347-master (included in 26.10 and later)
  • Backported to: 26.9.13.15, 26.8.21.6, 26.7.25.5, 26.3.49.3

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [82dd687]

Summary: ✅


AI Review

Summary

This PR replaces raw engine casts on catalog storages with proxy-aware castStorage / resolveStorageProxyLoading helpers so lazy StorageTableProxy tables stop staying invisible forever after first use, and it adds tests plus a style check to keep future callsites aligned. The helper direction is sound and several earlier proxy bugs are fixed, but the current diff still leaves one correctness regression and several new access-order regressions around lazy-table materialization, so I would block until those are fixed.

Missing context / blind spots
  • ⚠️ The aggregate PR report and Build (arm_tidy) check were still pending while I reviewed, so I could not use full CI evidence to rule out cross-platform fallout from the new proxy helpers.
Findings

❌ Blockers

  • [src/Databases/DatabaseOrdinary.cpp:615] restoreMetadataAfterConvertingToReplicated now probes lazy ReplicatedMergeTree tables with DeferredTable::Skip, then keeps using the original table for getStoragePolicy. A converted table that is still behind StorageTableProxy therefore returns early, never removes the convert_to_replicated flag, and never restores metadata in Keeper; after the first user access it stays read-only until a manual SYSTEM RESTORE REPLICA. Suggested fix: when the flag is present, resolve the storage with castStorage<StorageReplicatedMergeTree>(table, DeferredTable::Load) and use that resolved storage for the disk/policy lookup.
  • [src/TableFunctions/TableFunctionProjection.cpp:72] mergeTreeProjection still resolves and inspects source_table_id before any source-table privilege gate. DESCRIBE TABLE mergeTreeProjection(...) can therefore reveal whether a hidden table has a projection and what columns it exposes, and executeImpl can materialize a hidden lazy table before any SELECT check. Suggested fix: mirror TableFunctionLoop by checking SHOW_COLUMNS before DatabaseCatalog::getTable in getActualTableStructure, and SELECT before building the executable storage in executeImpl.
  • [src/TableFunctions/TableFunctionMergeTreeIndex.cpp:157] mergeTreeIndex has the same contract break: getActualTableStructure resolves the source table and enumerates its key/mark layout before any source-table access check, and executeImpl loads the table before any SELECT gate. That lets an unprivileged caller learn primary-key structure from DESCRIBE TABLE mergeTreeIndex(...) and start a hidden lazy table by naming it. Suggested fix: add the same early SHOW_COLUMNS / SELECT checks as above, before DatabaseCatalog::getTable.
  • [src/Storages/StorageMergeTreeAnalyzeIndexes.cpp:314] The StorageMergeTreeAnalyzeIndexes constructor resolves and materializes source_table, validates that it is MergeTree, and enumerates parts/settings before any early source-table privilege gate. Both mergeTreeAnalyzeIndexes and mergeTreeAnalyzeIndexesUUID can therefore distinguish hidden tables via constructor-time UNKNOWN_TABLE / BAD_ARGUMENTS, and in a lazy_load_tables database they now start the hidden table and its part discovery before readImpl reaches the later SELECT check. Suggested fix: move source resolution / part enumeration behind an early access gate in the table-function entrypoints, or add an equivalent SHOW_TABLES + source SELECT check before constructing StorageMergeTreeAnalyzeIndexes.
  • [src/Interpreters/InterpreterHypotheticalObjectQuery.cpp:231] The index branch still reaches resolveStorageID / DatabaseCatalog::getTable before any index-side privilege check, so DROP HYPOTHETICAL INDEX IF EXISTS ... ON hidden_tbl can still distinguish “hidden table exists” from UNKNOWN_TABLE, and CREATE HYPOTHETICAL INDEX now also materializes a hidden lazy table before the later column-level SELECT check. [dismissed by author -- https://github.com/Resolve lazily loaded table proxies before casting to an engine type #121332#discussion_r4126300352] The existence leak may predate this PR, but the new resolveStorageProxyLoading makes it materially worse by starting the hidden table too, so the regression is still in scope here. Suggested fix: mirror the projection path with an early table-level gate such as ALTER_ADD_INDEX before resolveStorageID / getTable, then keep the later column-level SELECT check for the WHATIF analysis itself.
  • [src/Functions/FunctionJoinGet.cpp:188] joinGet now resolves and materializes the named table before any metadata/access gate on the legacy path. A caller with no grants on db.tbl can distinguish “hidden table exists and uses the Join engine” from “hidden table exists but is some other engine”, and in a lazy_load_tables database can start a hidden Join table just by naming it here. Suggested fix: perform the same early metadata gate as the analyzer path before DatabaseCatalog::getTable / castStorage<StorageJoin>(..., DeferredTable::Load), and defer the engine-specific validation until after that gate succeeds.
Tests
  • ⚠️ The new stateless coverage proves the system.parts / system.replicas / SYSTEM SYNC REPLICA paths, but it does not exercise the new lazy-load access-order surfaces above. Please add focused regressions for joinGet, mergeTreeProjection, mergeTreeIndex, mergeTreeAnalyzeIndexes, and hypothetical index DDL in a lazy_load_tables = 1 database with a user lacking source-table grants.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    • Restore early privilege gates for the new DeferredTable::Load / resolveStorageProxyLoading callsites that can materialize hidden tables.
    • Fix restoreMetadataAfterConvertingToReplicated so a flagged lazy ReplicatedMergeTree is repaired on startup instead of being left read-only.
    • Add focused regression coverage for the newly introduced access-order paths.

LLVM Coverage Report

Measured on commit 82dd687.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.40% 79.50% +0.10%

Changed lines: Changed C/C++ lines covered: 547/633 (86.41%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 21, 2026
@thevar1able thevar1able self-assigned this Sep 21, 2026
Comment thread ci/jobs/check_style.py Resolved
Comment thread src/Storages/StorageProxy.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

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.

Compile time of recompiled translation units

76 translation units recompiled, 817 s compile time in total, 76 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +44.1 s (+6%) in total before that adjustment.

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 22, 2026
…e-check

# Conflicts:
#	src/Interpreters/ActionsVisitor.cpp
#	src/Interpreters/ExpressionAnalyzer.cpp
@evillique
evillique force-pushed the storage-cast-style-check branch from bbabdd8 to 0ecb8c0 Compare September 24, 2026 21:08
void DatabaseOrdinary::restoreMetadataAfterConvertingToReplicated(StoragePtr table, const QualifiedTableName & name)
{
auto * rmt = table->as<StorageReplicatedMergeTree>();
auto rmt = castStorage<StorageReplicatedMergeTree>(table, DeferredTable::Skip);

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.

startupTableAsync calls this on the object returned by tryGetTableNoWait, which is still StorageTableProxy for a lazy ReplicatedMergeTree created via convert_to_replicated. Because StorageTableProxy::startup is a no-op, DeferredTable::Skip makes this return nullptr and we exit before removing the convert_to_replicated flag or calling restoreMetadataInZooKeeper. The first user access later loads the table, but this helper is never re-run, so the table stays in the post-conversion readonly state until someone does a manual SYSTEM RESTORE REPLICA.

This needs to force materialization when the flag is present (or otherwise run the repair from the lazy-load path), and then use the resolved storage for the policy lookup below instead of table->getStoragePolicy(), because StorageTableProxy::getStoragePolicy() is nullptr.

ColumnsDescription TableFunctionMergeTreeProjection::getActualTableStructure(ContextPtr context, bool /*is_insert_query*/) const
{
auto source_table = DatabaseCatalog::instance().getTable(source_table_id, context);
auto source_table = resolveStorageProxyLoading(DatabaseCatalog::instance().getTable(source_table_id, context));

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.

This still resolves and inspects source_table_id before any source-table privilege check. ITableFunction::getActualTableStructureWithAccess only calls checkSourceAccess, but for mergeTreeProjection that is a no-op because getStorageEngineName() returns "". As a result, DESCRIBE TABLE mergeTreeProjection(db, tbl, proj) / CREATE TABLE ... AS can reveal whether a hidden table has a projection and what columns it exposes even when the caller has no grants on db.tbl.

Please add an explicit access check before the catalog lookup, similar to TableFunctionLoop: SHOW_COLUMNS for structure resolution here, and SELECT on the source table before constructing the executable storage in executeImpl.

ColumnsDescription TableFunctionMergeTreeIndex::getActualTableStructure(ContextPtr context, bool /*is_insert_query*/) const
{
auto source_table = DatabaseCatalog::instance().getTable(source_table_id, context);
auto source_table = resolveStorageProxyLoading(DatabaseCatalog::instance().getTable(source_table_id, context));

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.

Same issue here: getActualTableStructureWithAccess reaches this code with no source-table grant check because mergeTreeIndex does not override checkSourceAccess and its getStorageEngineName() is empty. A caller can therefore DESCRIBE TABLE mergeTreeIndex(db, hidden_tbl, ...) and learn the table's primary-key columns / mark-stream layout without SHOW_COLUMNS or SELECT on the source table.

Please gate this entrypoint before DatabaseCatalog::getTable, mirroring TableFunctionLoop / mergeTreeTextIndex: SHOW_COLUMNS for getActualTableStructure, and SELECT when building the executable storage.

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 33 queries analysed

No regressions were flagged. This PR replaces direct storage casts with castStorage so that lazily loaded tables resolve correctly, mostly in DDL, INSERT, SYSTEM and catalog paths, and adds a style check for it. The only flagged queries are TPC-H Q1 (-18.5%) and Q7 (-16.0%), both stayed not_sure and neither is a confirmed result. Master's own timings for both queries became unstable around 2026-10-02, and the diff does not touch scan, aggregation or join execution, so neither improvement can be credited to this change.

clickbench

🟢 No significant changes

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 53 -18.5% <0.0001 The -18.5% looks large, but master's own timings for Q1 shifted around 2026-10-02 and are noisy, so this PR can't be credited with it. Only per-query table lookup casts changed, not the scan or aggregation code.
⚠️ 7 not_sure 81 68 -16.0% <0.0001 The -16.0% falls in the same unstable stretch of master history as Q1, and CPU time barely moved. The diff does not touch join or scan execution, so it can't be credited to this PR.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: c25f77fc-4100-4430-8218-b692dbcaeb83
  • MIRAI run: 12a8f56c-4f89-4c65-b2d5-5e87b5bbb431
  • PR check IDs:
    • clickbench_2909485_1790951133
    • clickbench_2909496_1790951133
    • clickbench_2909502_1790951133
    • tpch_adapted_1_official_2909528_1790951133
    • tpch_adapted_1_official_2909542_1790951133
    • tpch_adapted_1_official_2909556_1790951133

…e-check

# Conflicts:
#	src/Interpreters/ActionsVisitor.cpp
#	src/Interpreters/MutationsInterpreter.cpp
const OptionalVectorSearchParameters & vector_search_parameters_)
: StorageWithCommonVirtualColumns(table_id_)
, source_table(source_table_)
, source_table(resolveStorageProxyLoading(source_table_))

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.

StorageMergeTreeAnalyzeIndexes::readImpl is still the first place that checks SELECT on the source table, but this constructor now resolves the lazy source, verifies that it is MergeTree, and enumerates its parts and settings before that check runs. That means mergeTreeAnalyzeIndexes(...) and mergeTreeAnalyzeIndexesUUID(...) can still disclose an inaccessible table through constructor-time UNKNOWN_TABLE / BAD_ARGUMENTS, and for lazy tables this change now goes further by materializing the table and its part list before any privilege check.

Please move the source resolution and part enumeration behind an access check, or add an equivalent early source-table check in executeImpl for both the name and UUID entrypoints. mergeTreeCodecBlockCounts in the same family now uses that shape.

@protomn

protomn commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

This also fixes #122297 (hypothetical index and projection DDL, and EXPLAIN WHATIF on an empty table, in a lazy_load_tables database). Both casts reported there are the InterpreterHypotheticalObjectQuery.cpp and WhatIfIndexEstimator.cpp hunks here.

@PedroTadim

Copy link
Copy Markdown
Member

@evillique can you add the test cases from #122297 here?

@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 7, 2026
robot-clickhouse added a commit that referenced this pull request Oct 7, 2026
Cherry pick #121332 to 26.9: Resolve lazily loaded table proxies before casting to an engine type
robot-clickhouse added a commit that referenced this pull request Oct 7, 2026
robot-ch-test-poll added a commit that referenced this pull request Oct 7, 2026
Cherry pick #121332 to 26.3: Resolve lazily loaded table proxies before casting to an engine type
robot-clickhouse added a commit that referenced this pull request Oct 7, 2026
robot-ch-test-poll added a commit that referenced this pull request Oct 7, 2026
Cherry pick #121332 to 26.7: Resolve lazily loaded table proxies before casting to an engine type
robot-clickhouse added a commit that referenced this pull request Oct 7, 2026
robot-ch-test-poll added a commit that referenced this pull request Oct 7, 2026
Cherry pick #121332 to 26.8: Resolve lazily loaded table proxies before casting to an engine type
robot-clickhouse added a commit that referenced this pull request Oct 7, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 7, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 8, 2026
Backport #121332 to 26.9: Resolve lazily loaded table proxies before casting to an engine type
clickhouse-gh Bot added a commit that referenced this pull request Oct 8, 2026
Backport #121332 to 26.7: Resolve lazily loaded table proxies before casting to an engine type
clickhouse-gh Bot added a commit that referenced this pull request Oct 8, 2026
Backport #121332 to 26.8: Resolve lazily loaded table proxies before casting to an engine type
PedroTadim added a commit that referenced this pull request Oct 12, 2026
Backport #121332 to 26.3: Resolve lazily loaded table proxies before casting to an engine type
fm4v pushed a commit to BoloniniD/ClickHouse that referenced this pull request Oct 12, 2026
…subcolumns

Conflicts:
- StorageMaterializedView.cpp, StorageMerge.cpp: master removed the legacy
  `order_optimizer` read-in-order path (ClickHouse#121390); kept the access-check changes.
- TableFunctionMergeTreeIndex.cpp, TableFunctionMergeTreeTextIndex.cpp: master wraps
  `getTable` in `resolveStorageProxyLoading` (ClickHouse#121332); kept the `SHOW_TABLES` check
  before the lookup and the pinned metadata snapshot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
JTCunning pushed a commit to JTCunning/ClickHouse that referenced this pull request Oct 18, 2026
JTCunning pushed a commit to JTCunning/ClickHouse that referenced this pull request Oct 18, 2026
jkartseva added a commit that referenced this pull request Oct 23, 2026
…helpers for

Trimmed to what the original change is about - a table on a `backup_metadata_only` storage policy has its data
left out of a backup and a restore - with everything the branch cannot express removed:

- `castStorage`, `DeferredTable` and `resolveStorageProxyLoading` come from #121332, which is not on this branch,
  so the casts are plain `std::dynamic_pointer_cast`. A table behind a `StorageProxy` is no longer resolved, so
  its data is backed up as usual rather than left out.
- `warnBackupMetadataOnlyIgnored` and the lookups of the inner tables of a materialized view and a `TimeSeries`
  table are gone. They only logged, and the answer does not depend on them: the flag is ignored for both kinds
  either way. The test asserts the backups still succeed instead of asserting the warnings.

`context` is unused in the overload that is left, and the includes the removed code needed are dropped.

Co-Authored-By: Claude Opus 5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…helpers for

Trimmed to what the original change is about - a table on a `backup_metadata_only` storage policy has its data
left out of a backup and a restore - with everything the branch cannot express removed:

- `castStorage`, `DeferredTable` and `resolveStorageProxyLoading` come from #121332, which is not on this branch,
  so the casts are plain `std::dynamic_pointer_cast`. A table behind a `StorageProxy` is no longer resolved, so
  its data is backed up as usual rather than left out.
- `warnBackupMetadataOnlyIgnored` and the lookups of the inner tables of a materialized view and a `TimeSeries`
  table are gone. They only logged, and the answer does not depend on them: the flag is ignored for both kinds
  either way. The test asserts the backups still succeed instead of asserting the warnings.

`context` is unused in the overload that is left, and the includes the removed code needed are dropped.

Co-Authored-By: Claude Opus 5 <[email protected]>
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

6 participants