Skip to content

Show views in dependencies in system.tables - #92472

Open
zvonand wants to merge 104 commits into
ClickHouse:masterfrom
zvonand:fix/views-67601
Open

zvonand wants to merge 104 commits into
ClickHouse:masterfrom
zvonand:fix/views-67601

Conversation

@zvonand

@zvonand zvonand commented Dec 17, 2025 •

Copy link
Copy Markdown
Contributor

Closes #67601

Changelog category (leave one):

  • Backward Incompatible Change

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

The dependencies_database and dependencies_table columns of system.tables now list the plain (non-materialized) views that read from the table, in addition to the materialized views. Previously they listed exactly the materialized views which an INSERT into the table triggers, so tools which read them as "what an insert triggers" now also get the plain views and should filter them out, e.g. by engine of the dependent table.


Note

Medium Risk
Touches core catalog dependency bookkeeping and rename/drop flows; bugs could leave stale or missing dependencies in system.tables (and potentially affect operations that rely on dependency graphs).

Overview
system.tables.dependencies_table now reports both materialized views and regular (plain) views that depend on a table, including multi-source JOIN views and cross-database cases.

This adds a new plain-view dependency graph tracked from CREATE/ALTER/ATTACH metadata (DDLDependencyVisitor, TablesLoader, InterpreterCreateQuery) and keeps it consistent through DROP/DETACH, RENAME TABLE, and RENAME DATABASE by extending DatabaseCatalog dependency add/remove/update paths. A new stateless test (03760_view_in_system_tables) validates dependency output and edge cleanup/migration behavior.

Written by Cursor Bugbot for commit 2c3b3f0. This will update automatically on new commits. Configure here.


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

@bharatnc bharatnc self-assigned this Dec 18, 2025
@bharatnc bharatnc added the can be tested Allows running workflows for external contributors label Dec 18, 2025
@clickhouse-gh

clickhouse-gh Bot commented Dec 18, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f7ba0f6]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) FAIL
05443_exchange_view_with_its_source_across_databases FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR adds ordinary views to system.tables.dependencies_* and maintains their dependencies across DDL and metadata loading. Two database-resolution bugs remain: a view using the dictionary table function protects the wrong dictionary, and a local dictionary source query protects the wrong table. Both were reproduced with the Fast-test binary for head f7ba0f65ce7110444becff73fc08318ee38d7089.

Findings

❌ Blockers

  1. src/Databases/DDLDependencyVisitor.cpp:617: The dictionary table function still resolves dependencies against the view's database. With USE reader_db and CREATE VIEW view_db.v AS SELECT * FROM dictionary('d'), the view reads reader_db.d, but both graphs record view_db.d. A guarded DROP DICTIONARY reader_db.d succeeds and subsequent view reads fail. Metadata-only ALTER and cross-database renames retain the mismatch. Apply execution-database resolution to this carrier too.

  2. src/Databases/DDLDependencyVisitor.cpp:816: The outer DDL session overrides a local dictionary source query's execution database. visitDictionaryDef visits the source query against the server default, but the new helper switches joinGet back to the creating session's database. A dictionary created from reader_db reads default.j, yet its referential edge protects reader_db.j. Guarded dropping of default.j succeeds and SYSTEM RELOAD DICTIONARY fails with UNKNOWN_TABLE; the loading graph correctly names default.j. Scope the execution database to the source query while visiting it.

Tests
  • ⚠️ Add a stateless regression for an ordinary view over unqualified dictionary('d') from another database. Verify the displayed dependency and rejection of the actual dictionary's guarded drop after creation, metadata-only ALTER, and rename.
  • ⚠️ Add a stateless regression for a local CLICKHOUSE dictionary source query containing unqualified joinGet, created from a non-default database. Verify that the default-database source is protected and an unused same-named table in the session database is droppable.
Final Verdict

Status: ❌ Block

Correct both resolution paths and add the focused regressions before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Dec 18, 2025
@zvonand

This comment was marked as outdated.

@zvonand

zvonand commented Dec 24, 2025

Copy link
Copy Markdown
Contributor Author

@bharatnc could you pls take a look at the PR?

The only fail: #91974. Everything else passed.

@bharatnc

Copy link
Copy Markdown
Contributor

@bharatnc could you pls take a look at the PR?

The only fail: #91974. Everything else passed.

Sure, I started looking, I'll review it this week.

Comment thread src/Databases/TablesLoader.cpp Resolved
Comment thread src/Databases/DDLDependencyVisitor.cpp Resolved
@zvonand
zvonand requested a review from bharatnc January 6, 2026 15:19
@zvonand

zvonand commented Jan 7, 2026

Copy link
Copy Markdown
Contributor Author

@bharatnc updated as per your review

@zvonand

zvonand commented Jan 21, 2026

Copy link
Copy Markdown
Contributor Author

@zvonand

zvonand commented Jan 21, 2026

Copy link
Copy Markdown
Contributor Author

@bharatnc ping

Comment thread src/Databases/DDLDependencyVisitor.cpp Resolved

@bharatnc bharatnc left a comment

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.

Looks mostly good to me, other than a few recommended changes.

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jan 27, 2026
@zvonand
zvonand force-pushed the fix/views-67601 branch 2 times, most recently from 65a72d4 to 108d859 Compare January 27, 2026 12:37
@zvonand
zvonand requested a review from bharatnc January 27, 2026 12:40
@zvonand

zvonand commented Feb 5, 2026

Copy link
Copy Markdown
Contributor Author

No unexpected fails here. @bharatnc I think it is ready to be looked at again.

@bharatnc

bharatnc commented Feb 7, 2026

Copy link
Copy Markdown
Contributor

No unexpected fails here. @bharatnc I think it is ready to be looked at again.

I'll take a look again.

Comment thread src/Interpreters/DatabaseCatalog.cpp Resolved
@zvonand

zvonand commented Feb 10, 2026

Copy link
Copy Markdown
Contributor Author

@bharatnc I guess it won't be merged automatically due to CH Inc sync

@zvonand

zvonand commented Feb 11, 2026

Copy link
Copy Markdown
Contributor Author

the only fail is because the test is flaky

Comment thread src/Databases/DDLDependencyVisitor.cpp Resolved
Comment thread src/Databases/DDLDependencyVisitor.cpp Resolved
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 2 commits November 2, 2026 17:54
…sion's `enable_global_with_statement`

A view does not store the settings of the session which creates it: it runs with the settings of
the session which reads it. `DDLDependencyVisitor` took `enable_global_with_statement` from the
global context, so with `SET enable_global_with_statement = 0` the bare name in the recursive member
of a recursive CTE was treated as the CTE, although that session reads the physical table there.
The source was then missing from `system.tables.dependencies_table`, and `DROP TABLE` with
`check_referential_table_dependencies` broke the view.

Now, unless a `SETTINGS` clause of the stored definition fixes the setting, a name is excluded
from the dependencies only if it refers to a CTE with either value. The self-reference checks
(`RENAME` of a view into a name it reads, and a materialized view selecting from itself) still use
the precise value, so a recursive CTE named like the view stays allowed; the self-edge it produces
after `RENAME` is erased from the recomputed dependencies.

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

Copy link
Copy Markdown
Member

🕵 Pushed 647e55dba45a..d7eab05abc76: a clean merge of master and a fix for the AI review blocker about session-level enable_global_with_statement.

  • A view does not store the settings of the session that creates it. It runs with the settings of the session that reads it: v_session returns 1, 2, 3 by default and 1, 3 with SETTINGS enable_global_with_statement = 0. So DDLDependencyVisitor no longer takes the value from the global context. If no SETTINGS clause in the stored definition fixes it, a bare name is excluded from the dependencies only if it refers to a CTE with either value. The physical r in the recursive member is now a dependency in every case from the review: session SET, metadata-only ALTER, detach/attach and rename. DROP TABLE r SETTINGS check_referential_table_dependencies = 1 is rejected.
  • The self-reference checks still use the precise value. These are RENAME of a view into a name it reads (DatabaseCatalog::getDependenciesRecomputedForNewName) and selectReadsView for materialized views. So a recursive CTE named like the view or the MV is still allowed. The self-edge that such a view gets after RENAME is erased from the recomputed dependencies.
  • Tests: 05449_plain_view_dependencies_recursive_cte_without_global_with now covers a view whose definition does not fix the setting, and a view created after SET enable_global_with_statement = 0. The reference of 05446_rename_view_with_recursive_cte_named_like_view now lists reads_cte as a dependent of the same-named table r, because a session with the setting disabled reads that table.

All 30 tests of this PR and 05404_materialized_view_cannot_select_from_itself pass locally on a build of the merged tree.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Status of d7eab05abc76: the branch is current with master (merged on 2026-11-02), and there are no unresolved review threads.

The only red is 04105_system_pause_view in Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=92472&sha=latest&name_0=PR&name_1=Stateless%20tests%20(amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20targeted). The diff is <3a: refresh running before stop: 0> (expected 1). This PR does not cause it. I reproduced it locally with the official master binary (4944813cca46) and the remote_database_disk.xml config (database metadata on MinIO), running the test 7 times in parallel. The test failed 7/7 on master and 7/7 with this PR's build. Without the remote database disk, master passes 21/21.

What happens: with the database disk on object storage and several concurrent copies, interrupt_running_refresh sees the refresh as status = 'Running' with read_rows = 0 for several seconds after SYSTEM REFRESH VIEW. The refresh is still setting up and has not read its first row yet. The check requires read_rows between 1 and 8, so all 10 attempts give up and print 0. Log of one copy on master (running, status, read_rows, time):

DBG 0	Running	0	2026-11-02 22:14:31.859
DBG 0	Running	0	2026-11-02 22:14:32.478
...
DBG 0	Running	0	2026-11-02 22:14:45.939
DBG 1	Running	1	2026-11-02 22:14:46.718

@groeneai, please investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=92472&sha=latest&name_0=PR&name_1=Stateless%20tests%20(amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20targeted) and fix it in a separate PR (for example, wait until read_rows >= 1 before sending the statements, instead of retrying with a new view). If a fix is already in progress, link it here.

The CHANGES_REQUESTED review from @bharatnc dates from 2026-02-25. All of its threads have since been resolved, so it needs a re-review.

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. No fix for this shape is in progress. I'm investigating 3a: refresh running before stop: 0 with the remote database disk and will follow up here with a separate PR.

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

The fix is in #128859: interrupt_running_refresh in 04105 and 04319 now waits until the refresh has read its first row (or failed) before the one-call check. With the database disk on MinIO and 10 ms injected latency it went from 14/14 FAIL to 56/56 OK (release) and 42/42 OK (asan_ubsan).

Blargian pushed a commit to Blargian/ClickHouse that referenced this pull request Nov 3, 2026
… the database disk on object storage

`interrupt_running_refresh` checks `status = 'Running' and read_rows between 1 and 8` one client
start-up after `SYSTEM REFRESH VIEW`. The refresh is already `Running` while it creates its target
table, and with the database disk on object storage that takes seconds, so the check saw
`read_rows = 0` and printed 0. Re-creating the view repeated the same timing, so all 10 attempts
missed: `<3a: refresh running before stop: 0>` in `Stateless tests (amd_asan_ubsan, db disk,
distributed plan, targeted)` (reported on ClickHouse#92472; there the check ran 0.4-0.6 s after the refresh
started and the refresh INSERT 0.6-2.6 s after it).

Wait until the refresh has read its first row, or failed, before the one-call check. A new view's
`read_rows` keeps its value after the refresh, so the wait cannot miss it (no hang like the one
ClickHouse#125034 fixed), and `clickhouse_test_time_left` bounds it. The `read_rows <= 8` check, the one-call
statements and the retry from ClickHouse#127917 are unchanged, so a STOP that lands after the refresh is
still retried and an all-miss is still a labelled mismatch.

Validated on master 4944813 CI builds: with the database disk on MinIO and 10 ms injected
latency each way, before 14/14 FAIL (release and asan_ubsan), after 56/56 and 42/42 OK, one attempt
per helper call; a failpoint that holds the refresh before it reads fails before and passes after;
50/50 OK per test with random settings on a local disk and on the database disk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the conflict in `StorageAlias::getTargetTable`: master moved the
column-level access check into `StorageAlias::read`, which now checks the
table returned by `getTargetTable`. The new `StorageAlias::getTargetChain` and
the `checkAlterIsPossible` message use `getTargetStorageID`, so a target
written without a database follows the alias as elsewhere in this PR.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed d7eab05abc76..0a9da0e22b60, a merge of master (0710b90bda5e) that resolves the conflict in src/Storages/StorageAlias.cpp.

  • master moved the column-level access check out of StorageAlias::getTargetTable and into StorageAlias::read. The resolution keeps only the table-level check in getTargetTable, still on the target resolved by getTargetStorageID. read now checks SELECT on the ID of the table that getTargetTable returned, not on the raw target_database.
  • The new StorageAlias::getTargetChain from master and the message in checkAlterIsPossible now also use getTargetStorageID. So an Alias('t') target written without a database follows the alias when it is moved, as everywhere else in this PR.
  • The merge includes Fix 04105_system_pause_view and 04319_system_stop_all_background with the database disk on object storage #128859, which fixes the only red test on the previous head (04105_system_pause_view with a database disk).

On a local build of the merged tree, the 30 tests of this PR, the 21 StorageAlias tests and 03290_alter_mv_dependency_check pass. The local server had no ZooKeeper and no test clusters, so three tests could not run there.

The CHANGES_REQUESTED review from @bharatnc is from 2026-02-25, and all of its threads are resolved. It needs a re-review.

Comment thread src/Databases/DDLDependencyVisitor.cpp Resolved
alexey-milovidov and others added 2 commits November 19, 2026 21:40
Master reverted ClickHouse#114923 (ClickHouse#130531), which removed
the `current_database` parameter of `getLoadingDependenciesFromCreateQuery` and the narrow
qualification pass (`visitTableExpressionsImpl`) of `AddDefaultDatabaseVisitor`.

Resolution:
- `AddDefaultDatabaseVisitor.h`: take master, dropping the narrow pass and the members only it used;
  keep the static alias helpers of this PR which `DDLDependencyVisitor` uses.
- `DDLLoadingDependencyVisitor`: keep the `current_database` and `engine_arguments_database`
  parameters of this PR (the constraint subquery part of ClickHouse#114923 stays removed). At startup,
  `TablesLoader` passes the default database of the server, which keeps the behaviour of master there.
- Call sites in `DatabaseMemory`, `DatabaseOrdinary`, `InterpreterCreateQuery`: keep this PR's version.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…st the session database

Review threads:
ClickHouse#92472 (comment)
ClickHouse#92472 (comment)

The column expressions (`DEFAULT`, constraints, ...) and the table engine with all of its arguments
are evaluated in the context of a query, so an unqualified name in them is resolved against the
current database of the session, not against the database owning the table. Only the query of a
view is bound to the owning database. Rename `engine_arguments_database` to `execution_database`
and apply it to these subtrees:
- `DDLDependencyVisitor` visits the columns, the storage and the view targets with a nested visitor
  while `current_database` is overridden, and skips them in the outer traversal. Before, the
  `SCOPE_EXIT` in `visitTableEngine` restored the database before the depth-first traversal reached
  the arguments, so `dictGet` in the sharding key of `Distributed` was resolved against the owning
  database.
- `DDLLoadingDependencyVisitor` looks only at such expressions, so it resolves everything against
  `execution_database`.

After merging master, which reverted the load-time qualification of ClickHouse#114923
(ClickHouse#130531), `TablesLoader` resolves the query of a view
against the database owning it, as the `ALTER` path and the graph of plain views do, and everything
else against the default database of the server, as master does. Remove
`05444_plain_view_dependencies_rename_after_metadata_reload`: it asserted that loading the view
qualifies its unqualified source, which master reverted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-backward-incompatible Pull request with backwards incompatible changes and removed pr-improvement Pull request with some product improvements labels Nov 19, 2026
@clickhouse-gh clickhouse-gh Bot added comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. and removed comp-view Logical (non-materialized) views. labels Nov 19, 2026
@nickitat

Copy link
Copy Markdown
Member

I merged master into this branch to pick up #133069.

Since 2026-11-19, stateless tests randomize the MergeTree setting enable_adaptive_codec_selection, and 05293_autopr_statistics_plan_based failed in this PR's CI because of that, not because of the changes here. The fix pins the setting in the test; it is in master now, so the next CI run should not hit it.

🤖 Generated with Claude Code

…gainst the execution database

The name of a `joinGet` table, an expression-valued `dictGet` name and a bare parameterized view call
in the query of a view are not qualified in the stored definition, so they are resolved against the
current database of the query which reads the view. The referential and plain-view dependencies now
resolve them against `execution_database` (the current database of the session on `CREATE`, `ALTER`
and `RENAME`, the default database of the server on startup) instead of the database owning the view,
so the actual sources stay protected from `DROP`, also after the view is moved to another database.

Addresses review: ClickHouse#92472
addQualifiedNameFromArgument(function, 0);
/// The name is evaluated and an unqualified one is resolved when the function is executed, in the context
/// of the query which runs it: `AddDefaultDatabaseVisitor` qualifies only literal names of dictionaries.
addQualifiedNameFromArgumentWithExecutionDatabase(function, 0);

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 the dictionary table function against the execution database too

The dictionary branch below still calls addQualifiedNameFromArgument with the view's owning database. Unlike a qualified FROM identifier, dictionary('d') remains unqualified in the stored query and resolves against the reading session. This records both the referential and plain-view dependency on the wrong dictionary.

Reproduced with the Fast-test binary for f7ba0f65ce71:

CREATE DATABASE reader_db;
CREATE DATABASE view_db;
CREATE DICTIONARY reader_db.d (id UInt64, val String)
    PRIMARY KEY id SOURCE(NULL()) LAYOUT(FLAT()) LIFETIME(0);
CREATE DICTIONARY view_db.d (id UInt64, val String)
    PRIMARY KEY id SOURCE(NULL()) LAYOUT(FLAT()) LIFETIME(0);
USE reader_db;
CREATE VIEW view_db.v AS SELECT * FROM dictionary('d');
SELECT count() FROM view_db.v; -- succeeds
DROP DICTIONARY reader_db.d SETTINGS check_referential_table_dependencies = 1;
SELECT count() FROM view_db.v; -- Dictionary (`d`) not found

The guarded drop incorrectly succeeds: view_db.d lists v, while reader_db.d lists no dependent. A metadata-only ALTER preserves the error, and cross-database renames move the edge again without changing what the view reads. Please apply execution-database resolution to this table-function carrier and add coverage for creation and recomputation.

/// Like addQualifiedNameFromArgument, but evaluates the argument and resolves an unqualified name against `execution_database`.
void addQualifiedNameFromArgumentWithExecutionDatabase(const ASTFunction & function, size_t arg_idx)
{
String saved_current_database = std::exchange(current_database, execution_database);

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] Preserve the dictionary source query's execution context

visitDictionaryDef deliberately switches current_database to the server default before visiting a local CLICKHOUSE source query. This override replaces that with the outer DDL session's execution_database for joinGet/dictGet, so the dependency no longer matches the source query's execution context. The loading visitor uses a separate visitor with the default database and still records the correct edge.

Reproduced with the Fast-test binary for f7ba0f65ce71: create default.j and reader_db.j, both Join(ANY, LEFT, id) tables with columns (id UInt64, val String), and insert (1, 'global') into default.j. Then:

CREATE DATABASE owner_db;
USE reader_db;
CREATE DICTIONARY owner_db.d (id UInt64, val String)
PRIMARY KEY id
SOURCE(CLICKHOUSE(QUERY 'SELECT toUInt64(1) AS id, joinGet(\'j\', \'val\', toUInt64(1)) AS val'))
LAYOUT(FLAT()) LIFETIME(0);
SELECT dictGetString('owner_db.d', 'val', toUInt64(1)); -- global
DROP TABLE default.j SETTINGS check_referential_table_dependencies = 1;
SYSTEM RELOAD DICTIONARY owner_db.d; -- UNKNOWN_TABLE: default.j

The guarded drop incorrectly succeeds, while dropping the unused reader_db.j is blocked by owner_db.d. Please scope execution_database to the dictionary source query's default database as well, and add a regression proving the actual source remains protected.

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

can be tested Allows running workflows for external contributors comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-backward-incompatible Pull request with backwards incompatible changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

View does not appear in the dependencies of the tables it uses (system.tables)

8 participants