Skip to content

Make a table read by a scalar subquery in a CONSTRAINT a loading dependency - #114923

Merged
alexey-milovidov merged 43 commits into
masterfrom
constraint-subquery-loading-dependency
Sep 19, 2026
Merged

alexey-milovidov merged 43 commits into
masterfrom
constraint-subquery-loading-dependency

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 15, 2026 •

Copy link
Copy Markdown
Member

Attaching a table analyzes its constraints in InterpreterCreateQuery::getConstraintsDescription, and the analysis executes the scalar subqueries of a constraint expression. The tables such a subquery reads were not registered as loading dependencies, because DDLLoadingDependencyVisitor only looks at functions, dictionary sources and the storage definition. Nothing prevented dropping such a table, and the server did not start afterwards - attaching the dependent table threw UNKNOWN_TABLE and loading the metadata failed:

CREATE TABLE t1 (id UInt64) ENGINE = MergeTree ORDER BY tuple();
CREATE TABLE t2 (conversation UInt64, CONSTRAINT c CHECK (SELECT id FROM t1 LIMIT 15) IN (conversation)) ENGINE = MergeTree ORDER BY tuple();
DROP TABLE t1;   -- accepted, and the server cannot start anymore

The referential dependency was recorded, since DDLDependencyVisitor visits ASTTableExpression, so check_referential_table_dependencies = 1 rejected the DROP. But that setting is off by default, and it is the loading graph that the default check_table_dependencies check and the DROP DATABASE drop order (#97057) use.

A constraint declaration is now visited, and the tables of every subquery that the analysis executes are added to the loading dependencies. Subqueries which the analysis does not execute - the right argument of IN and the argument of exists, see ExecuteScalarSubqueriesMatcher::visit - are skipped, because what they read is needed only when the constraint is checked, not to attach the table. That keeps 02916_joinget_dependency-style patterns working, in particular 02841_not_ready_set_constraints, which drops the table read by an x IN (SELECT ...) constraint on purpose.

The names that SQL UDF expansion brings into a CREATE query (a table expression, the right argument of IN, the first argument of dictGet or joinGet) are qualified with the current database before the query is persisted, because the expansion runs after AddDefaultDatabaseVisitor. Metadata written before that is repaired against the owning database when it is attached and when the dependency graphs are built, so both graphs describe the tables the attached storage actually uses.

Seen in CI as a Cannot start clickhouse-server stress failure, e.g. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110231&sha=4de836223549fd5224ca017b8c1a28e344ce38e9&name_0=PR&name_1=Stress%20test%20%28amd_msan%29

Closes: #114918
Related: #87369
Related: #115648

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):

A table read by a scalar subquery inside a CONSTRAINT is now a loading dependency of the table that declares the constraint. Previously such a table could be dropped, after which the server did not start, because attaching the dependent table executes the subquery.


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

Version info

  • Merged into: 26.10.1.238-master (included in 26.10 and later)

…ndency

Attaching a table analyzes its constraints in
`InterpreterCreateQuery::getConstraintsDescription`, and the analysis executes the
scalar subqueries of a constraint expression. The tables such a subquery reads were
not registered as loading dependencies, because `DDLLoadingDependencyVisitor` only
looks at functions, dictionary sources and the storage definition. Nothing prevented
dropping such a table, and the server did not start afterwards: attaching the
dependent table threw `UNKNOWN_TABLE` and loading the metadata failed.

    CREATE TABLE t1 (id UInt64) ENGINE = MergeTree ORDER BY tuple();
    CREATE TABLE t2 (conversation UInt64,
        CONSTRAINT c CHECK (SELECT id FROM t1 LIMIT 15) IN (conversation))
    ENGINE = MergeTree ORDER BY tuple();
    DROP TABLE t1;   -- accepted, and the server cannot start anymore

The referential dependency was recorded (`DDLDependencyVisitor` visits
`ASTTableExpression`), so `check_referential_table_dependencies = 1` rejected the
`DROP`, but that setting is off by default, and it is the loading graph that the
default `check_table_dependencies` check and the `DROP DATABASE` drop order use.

A constraint declaration is now visited, and the tables of every subquery that the
analysis executes are added to the loading dependencies. Subqueries which the
analysis does not execute - the right argument of `IN` and the argument of `exists`,
see `ExecuteScalarSubqueriesMatcher::visit` - are skipped, because what they read is
needed only when the constraint is checked, not to attach the table.

Closes: #114918
Related: #87369

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2ab96d2]

Summary: ✅


AI Review

Summary

This PR correctly extends loading dependencies to scalar subqueries inside CONSTRAINTs and repairs several older name-qualification gaps around SQL UDF expansion and legacy metadata. I am still at ⚠️ Request changes: two carriers of database-sensitive names remain uncovered in the current code, and one previously discussed over-collection issue in skipped CONSTRAINT subqueries is still real.

Findings

⚠️ Majors

  • [src/Interpreters/AddDefaultDatabaseVisitor.h:204-205] The narrow post-SQL UDF / legacy-metadata pass still leaves dictionary(...) table functions bare. A SQL UDF body can expand to a scalar subquery such as SELECT count() FROM dictionary(dict), but visitTableFunction still only canonicalizes merge(...). The stored definition then resolves dict through the reader's current database, while DDLDependencyVisitor already records dictionary(...) as a dictionary-name dependency, so the persisted metadata and the dependency graph can still disagree after a database switch or a restart.
  • [src/Interpreters/InterpreterCreateQuery.cpp:2074-2078] The post-SQL UDF repair still skips create.storage, even though UserDefinedSQLFunctionVisitor::visit(query_ptr, getContext()) expands the whole CREATE AST and storage-side key / TTL expressions are another persisted carrier. A MergeTree key or TTL expression that expands to dictGet, joinGet, or x IN table still stays bare in stored metadata and can resolve against the wrong database later. The same omission is mirrored in qualifyNamesFromLegacyMetadata.
  • [src/Databases/DDLLoadingDependencyVisitor.cpp:139-183] [dismissed by author -- https://github.com/Make a table read by a scalar subquery in a CONSTRAINT a loading dependency #114923#discussion_r3823751989] The PR description says the right argument of IN and the argument of exists are skipped because those subqueries are not executed while a table is attached, but the generic traversal still descends into them and records joinGet, dictGet, and x IN table carriers there. That still makes objects needed only when the constraint is checked at insert time block DROP as loading dependencies.
Final Verdict

⚠️ Request changes.

LLVM Coverage Report

Measured on commit 2ab96d2.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 161/166 (96.99%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2ab96d25e with master f77edf0f9 (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.

Object file sizes

11 object files changed (+78.86 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Databases/DatabaseOnDisk.cpp.o 428.48 KiB 487.57 KiB +59.09 KiB (+13.79%)

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

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

Job report

Pass the query context to loading dependency extraction so table names introduced by SQL UDF expansion resolve in the database where the CREATE query runs. Add a regression test for a scalar subquery in an expanded constraint UDF.

#114923
Fixes the persisted constraint metadata path reported in #114923.
Qualify table names while expanding a SQL UDF, before the expanded AST is persisted. This avoids re-walking an expanded view query, which can invalidate scalar-subquery aliases.

Renumber the regression test after the original number became occupied on master.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114923&sha=591176b09804b1cc176cde36297bf2bfba9d5d1a&name_0=PR&name_1=Fast%20test
Qualify tables before normalization only when expanding `SQL UDF`s for persisted `CREATE` metadata. Other query types retain their target-table database resolution.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114923&sha=022513e2ece06537e993b73860b0b248e5b09c5a&name_0=PR&name_1=Fast%20test
@tuanpach tuanpach self-assigned this Aug 17, 2026
@tuanpach

Copy link
Copy Markdown
Member

The code looks good to me.

Can you check the failure of 04908_constraint_subquery_loading_dependency?

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Updated the branch with current master (merge 0d507169e11f) and rebuilt clickhouse successfully. This includes the upstream scalar-subquery changes relevant to the reported UDF-view failure and triggers a fresh validation run. The focused local runner could not connect to a ClickHouse server in this worktree.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Investigated 04908_constraint_subquery_loading_dependency and updated the branch with current master (merge b74ccf8de5de). The failure is in the added SQL-UDF view regression (UNKNOWN_IDENTIFIER for generated _subquery_1); the merge includes the current scalar-subquery implementation. This worker has no configured build graph (build.ninja is absent), so its bundled binary is stale and cannot validate the checked-out sources locally. The push has triggered fresh CI validation.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fixed and pushed 4ee1a99. The post-UDF table qualifier replaced a table-identifier AST child without synchronizing ASTTableExpression’s cached pointer; this left scalar-subquery aliases inconsistent when reading the persisted UDF view. The existing 04908_constraint_subquery_loading_dependency regression covers the case. Direct compilation of the affected translation unit passed; the local Ninja executable segfaults before starting any build work, so CI will provide the full validation.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fixed and pushed f505a69. The post-UDF qualification path now uses ASTTableExpression::setOrReplace, keeping database_and_table_name synchronized with children; the prior replacement left the two representations inconsistent and caused 04908_constraint_subquery_loading_dependency to reference a stale scalar-subquery alias. Direct compilation of the affected InterpreterCreateQuery.cpp translation unit passed. The local Ninja frontend segfaults before starting work, so the pushed update will receive the full CI validation.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into master with commit 659cc1c Sep 19, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the constraint-subquery-loading-dependency branch September 19, 2026 23:49
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Sep 20, 2026
…-aliases-per-select

Conflict in `AddDefaultDatabaseVisitor.h`: master's ClickHouse#114923 added a narrow
qualification pass (`visitTableExpressions` / `visitTableExpressionsImpl` /
`visitFunctionTableNameArguments`) which tracks `WITH` names in the flat
`with_aliases` set this branch had replaced with the per-`SELECT` `Scope`
stack. Resolution keeps both: `with_aliases` stays as the state of the narrow
pass, the `Scope` stack stays as the state of the full traversal, and
`visit(ASTTableIdentifier &, ASTPtr &)` consults both - the two are separate
traversals, so only one of them is ever populated.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
shankar-iyer pushed a commit to shankar-iyer/ClickHouse that referenced this pull request Oct 3, 2026
…olumn

On 26.9.8.3 `CREATE TABLE` qualified table and dictionary names before
expanding SQL UDFs and never after, so `v ALIAS f(id)` with
`f = x -> dictGet(d, 'v', x)` was persisted as `dictGet(d, 'v', id)`.
Every later reader resolved `d` against its own current database: a
`SELECT` from another database failed with `Dictionary (d) not found`,
and the mutation of a lightweight `DELETE` (analyzed in a background
context) failed with Code 341 wrapping the same error.

Master already persists `dictGet(<db>.d, 'v', id)` since ClickHouse#114923, which
runs `AddDefaultDatabaseVisitor::visitTableExpressions` on the columns
list after the UDF expansion. Its tests cover `dictGet` only in a view
and `joinGet` in a `DEFAULT`, so this adds the issue's shape: an
identifier-form `dictGet` from a UDF in an `ALIAS` column, read from
another current database and by a lightweight `DELETE`.

The test is a shell test because a SQL UDF is server-wide and
`CREATE FUNCTION` takes no query parameter, so the name must be scoped
by `${CLICKHOUSE_DATABASE}` to be safe under concurrent runs.

Closes ClickHouse#123489

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 13, 2026
…nt-subquery-loading-dependency"

This reverts commit 659cc1c, reversing
changes made to f75df10.

Conflicts resolved by removing only what ClickHouse#114923 added: the narrow
qualification pass in AddDefaultDatabaseVisitor.h is removed together with
the parts ClickHouse#114908 later added inside it; InterpreterCreateQuery.cpp keeps
the expansion bound of ClickHouse#122362 on the neighbouring call; the string overload
of qualifyDictionaryNameWithDatabase in ExternalDictionariesLoader is kept,
because the dictionary usage record of ClickHouse#121567 is built on it.
04908_constraint_subquery_loading_dependency.sh (edited by ClickHouse#124408) is
deleted with the rest of the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Nov 14, 2026
… visitor pass

Master reverted ClickHouse#114923, which removed `AddDefaultDatabaseVisitor::visitTableExpressions`,
so the merged branch no longer compiled. The full traversal of the visitor, as used by
`CREATE VIEW`, already qualifies table expressions, `dictGet` and `IN`, but leaves the table
name of `joinGet` alone. Qualify it in `InterpreterCreateHandlerQuery` itself, so a handler
reads the `Join` table its query was checked against (case 19 of
`05493_create_handler_creator_access`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 14, 2026
…getree

Conflict resolutions:
- `FailPoint.cpp`: keep both the PR's and master's new failpoints.
- `DatabaseOnDisk.h`: master removed `qualifyNamesFromLegacyMetadata` (revert of #114923); keep only `DatabaseRenameGuardHint`.
- `MergeTask.cpp`: keep the PR's failpoint; master now initializes `rows_written` from the checkpointed columns, so drop the reset to zero.
- `MetadataStorageFromPlainRewritableObjectStorage.cpp`: master made the same explicit-refresh change; keep the PR's explanatory comment.
- `StorageTableProxy.h`: keep both the PR's members and master's `is_loaded`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 15, 2026
…lify-new-stored-definitions

Conflicts in AddDefaultDatabaseVisitor.h and InterpreterCreateQuery.cpp:
master removed the post-UDF qualification pass (ClickHouse#130531, the revert of
ClickHouse#114923), and this branch had added its assignCentroid literal branch
and a setIsNewDefinition call there. Resolved by taking master's removal:
like dictGet, a dictionary name brought in by a SQL UDF body is no longer
qualified at CREATE. The full traversal and the ALTER path keep this
branch's qualification unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Nov 16, 2026
…ema_2

master reverted ClickHouse#114923, so CREATE no longer stores the joinGet table name
with the session database. The stored name is database-less again, and
--dump-schema refuses it like a database-less dictionary() reference, because
it would rebind on replay. The test expected the qualified name and failed
on every job.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 16, 2026
Backport of the revert of #114923 (CONSTRAINT scalar-subquery loading
dependency) to 26.10. Conflict: 05397_implicit_minmax_index_alias_unresolvable_attach.sql
does not exist on 26.10 (it is a master-only test the revert only re-qualified),
so it is kept absent rather than introduced here.
novikd added a commit that referenced this pull request Nov 17, 2026
…mpound-identifiers

Conflicts:
- `src/Databases/DataLake/Common.cpp`: master added `icebergTypeToGlueType` in front of `parseTableName`; kept both, with `tryParseTableName` of this branch.
- `src/Interpreters/InterpreterCreateQuery.cpp`: master removed the `visitTableExpressions` block (revert of #114923) next to the `foldTablePaths` calls of this branch; the block is removed, the calls are kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
alexey-milovidov added a commit to zvonand/ClickHouse that referenced this pull request Nov 19, 2026
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]>
alexey-milovidov added a commit to zvonand/ClickHouse that referenced this pull request Nov 19, 2026
…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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 23, 2026
…rewrite

The revert of ClickHouse#114923 (ClickHouse#130531) removed `qualifyNamesFromLegacyMetadata`:
metadata load no longer qualifies the bare names that metadata written
before SQL UDF table names were qualified at CREATE time can contain. The
rewrite reads the definitions the same way load does, so it no longer
qualifies them either, and a rewritten view keeps the state a restart gives
it. The dependencies of a rewritten definition are still resolved against
the database of the view rather than the current database of the RENAME
query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 23, 2026
Since the revert of ClickHouse#114923, metadata load resolves the referential
dependencies against the default database, and it counts the CTE name of
`cte_mv` as a table, so `ATTACH DATABASE` logs `Replacing outdated
dependencies` for it. A materialized view with a CTE that was never renamed
gets the same warning on a reload of its database.

Co-Authored-By: Claude Opus 5.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-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Table referenced in a subquery inside a CONSTRAINT is not a loading dependency, so the server does not start after it is dropped

4 participants