Skip to content

Fix a crash when the dependency analysis of CREATE evaluates a subquery with JOIN - #122390

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-ddl-dependency-subquery-query-context
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-ddl-dependency-subquery-query-context

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #96844
Related: #121859

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

Fixed a server crash on CREATE or ATTACH of a table or view when an argument that the table dependency analysis evaluates, such as the cluster name of cluster, the database or table of Buffer or the dictionary name of dictGet, is a subquery with a JOIN and enable_join_runtime_filters_index_analysis is enabled in the default settings profile or in the subquery's own SETTINGS.

Description

On 26.9 with enable_join_runtime_filters_index_analysis = 1 in the default settings profile or in the subquery's own SETTINGS (and on master with stock settings, since #121859 turned it on), creating a view that reads through cluster() with a cluster name computed by a scalar subquery with a JOIN crashes the server (a is a MergeTree table ordered by k):

CREATE VIEW v (k UInt64) AS SELECT k FROM cluster((SELECT if(count() > 0, 'test_shard_localhost', '') FROM a, b WHERE a.k = b.k), currentDatabase(), 't');

Found by Stress test (arm_release) (job, report), where the AST fuzzer swapped the arguments of cluster(view(SELECT ... JOIN ...), '<cluster>').

To find the tables a new table depends on, DDLDependencyVisitor evaluates such arguments on a copy of the global context, and the analyzer executes a scalar subquery inside them. That copy is not a query context, so it has no join runtime filter lookup (only Context::makeQueryContext creates one). The JOIN registers its runtime filter for index analysis on the probe-side ReadFromMergeTree, whose read-time predicate builder dereferences the lookup of its own context: null.

The copy is now made a query context, like other places that run a SELECT on a copy of the global context (SQL SECURITY DEFINER views, ClickHouse dictionary sources). Every argument evaluation of the dependency analysis goes through this one place, and which arguments are evaluated does not change. A JOIN in the scalar subquery of a TTL ... WHERE predicate reaches the same read through another context without a lookup (see #121418) and is not covered here.

The new test crashes the server without the fix and passes with it (50 randomized runs, 20 more with a Replicated database). The existing dependency tests and test_backup_restore_new::test_tables_dependency pass.


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

…uery context

To find the tables a new table or view depends on, `DDLDependencyVisitor`
evaluates a non-literal argument (the cluster name of `cluster`, the
database or table of `Buffer`/`Distributed`, the name in `dictGet`/`joinGet`)
with `evaluateConstantExpressionOrIdentifierAsLiteral` on a copy of the global
context, and the analyzer executes a scalar subquery inside such an argument.

That copy was never made a query context, and `Context::makeQueryContext` is
the only place that creates the per-query join runtime filter lookup, so the
copy had none. A `JOIN` in the subquery registers its runtime filter for index
analysis on the probe-side `ReadFromMergeTree`, whose read-time predicate
builder dereferences the lookup of its own step context, a descendant of that
copy: SIGSEGV in `RuntimeFilterLookup::find` (STID 2771-4f2b, found by the
stress test on a fuzzed `cluster(view(SELECT ... JOIN ...), '<cluster>')`).
The build side and `__applyFilter` take the lookup of the thread's query
context (the CREATE query), which is why only the probe read crashed.

Reachable on 26.9 with `enable_join_runtime_filters_index_analysis = 1` in
the default profile, and on master with stock settings since ClickHouse#121859.

Make the copy a query context, as `ClickHouseDictionarySource` and SQL
SECURITY DEFINER views already do for the queries they run on a copy of the
global context. Which arguments are evaluated does not change: a view whose
`cluster` name is computed by a scalar subquery keeps its dependency, and the
new test checks it. The dropped comment claimed subqueries are not executed
here, which was not true.

The scalar subquery of a `TTL ... WHERE` predicate runs on another copy of
the global context that is not a query context either (see ClickHouse#121418), and a
`JOIN` there still reaches the same read. That path is not changed here.

Inside the evaluated subquery the probe read now looks the filter up in the
new, empty lookup and skips the pruning, which does not change results.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings over a full pass and a delta recheck) plus my own review; 1 fix round.

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test passes without the runtime filter index analysis if a server profile turns it off; pin the settings inside the scalar subquery (05258_...sql:16) AGREE, fixed @ 0ad8ea1 Measured: a SETTINGS clause inside the evaluated subquery reaches its plan. The three settings are pinned there; the unfixed server still dies on the test
2 ⚠️ The commit message said every other place that runs a query on a copy of the global context makes it a query context; the scalar subquery of a TTL ... WHERE predicate does not (#121418) AGREE, fixed @ 0ad8ea1 Claim corrected. Measured: a JOIN in a CHECK constraint's subquery is fine with and without the fix; in a TTL ... WHERE subquery it still reaches the same read. Not changed here, stated in the description
3 💡 test_tables_dependency does not depend on the evaluation (Buffer folds its arguments into the stored CREATE) AGREE, fixed @ 0ad8ea1 Clause dropped from the commit message
4 💡 Use Critical Bug Fix, since the defect is a server crash DISAGREE The Bug Fix criteria hold (reproduced on official 26.9.2.8 with the production-tier setting on); raising it to Critical Bug Fix is the maintainers' call
5 💡 The commit message names only the default profile as the way to reach it on 26.9; the subquery's own SETTINGS works too noted, not blocking The PR description names both
6 💡 The test does not say why the pin sits inside the subquery (session settings never reach the dependency analysis) noted, not blocking none

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-10:20260926-045600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local --enable_join_runtime_filters_index_analysis=1 on a file with two MergeTree tables and CREATE VIEW v (k UInt64) AS SELECT k FROM cluster((SELECT if(count() > 0, 'test_shard_localhost', '') FROM a, b WHERE a.k = b.k), currentDatabase(), 't') crashes every unfixed binary on demand: master debug builds, official 26.9.2.8 (Address: 0x8, RuntimeFilterLookup::find, the CI frames). The new stateless test crashes an unfixed server.
b Root cause explained? DDLDependencyVisitor evaluates dependency arguments on a copy of the global context, and the analyzer executes a scalar subquery inside them. The copy is not a query context, so it has no join runtime filter lookup (only makeQueryContext creates one). The subquery's JOIN registers its runtime filter for index analysis on the probe ReadFromMergeTree, whose read-time predicate builder dereferences its context's null lookup.
c Fix matches root cause? Yes. The evaluation context becomes a query context, as it already is for the queries ClickHouseDictionarySource and SQL SECURITY DEFINER views run on a copy of the global context. No guard at the dereference.
d Test intent preserved / new tests added? New stateless test 05258_create_view_cluster_name_subquery_with_join: the CREATE VIEW must not crash, and a refused DROP (check_referential_table_dependencies = 1) proves the subquery is still evaluated and the dependency registered. No existing test changed.
e Both directions demonstrated? Yes. Unfixed server: the test FAILS (server died, same stack). Fixed: OK, 50/50 with randomized settings, 20/20 with --replicated-database. clickhouse local A/B on four argument shapes: crash vs created.
f Fix is general across code paths? Yes. Every argument evaluation of the dependency analysis (cluster/clusterAllReplicas, Distributed, Buffer, Alias, dictGet*, dictHas, joinGet, dictionary) goes through the one changed function. Both read-time users of that lookup (range predicate, bloom filter index filter) are covered. The scalar subquery of a TTL ... WHERE predicate runs on another copy of the global context and still reaches the read: not covered here (measured).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Checked cluster(<subquery>, db, t), cluster(view(...), name), dictGetString(<subquery>, ...), a probe key in the primary key and in a bloom_filter skip index, setting 0 and 1, Atomic and Replicated databases. The key type only shapes the predicate after the lookup.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default, format or syntax change; the same arguments are evaluated.
i Invariants and contracts preserved? Yes. The copy is local and dropped on every exit, including the catch; query_context is a weak self-reference, so no cycle. The CREATE query's own context and lookup, the build side and __applyFilter are untouched. test_backup_restore_new::test_tables_dependency and the existing dependency tests pass.

Session id: cron:clickhouse-impl-slot-40:20260926-015800

@groeneai groeneai mentioned this pull request Sep 26, 2026
1 task done
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0ad8ea1]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
serialization_pool_lookup #0 FAIL dashboard

AI Review

Summary

This PR fixes the CREATE-time dependency-analysis crash by turning the copied evaluation context into a real query context before evaluateConstantExpressionOrIdentifierAsLiteral runs a scalar subquery. I did not find a remaining correctness, lifecycle, or compatibility issue in the patched path from the current diff.

Missing context / blind spots
  • ⚠️ I did not run the new stateless test locally because this checkout has no usable build_* directory or test binary; this review is based on code tracing and the current diff.
  • ⚠️ The added regression test covers CREATE VIEW. I verified by code inspection that ATTACH and metadata-load paths reuse the same helper, but I did not execute an ATTACH repro locally.
Final Verdict

✅ No new blocking or major issues found in the current patch.

LLVM Coverage Report

Measured on commit 0ad8ea1.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · 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 26, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0ad8ea1

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 2/6) / serialization_pool_lookup #0 dashboard confirmed_regression, client_time 0.6384 -> 0.7661 s (+19.9%). The shard's own report does not flag it (1 too long only), so the dashboard verdict alone made the shard red. The query is a GROUP BY over a Dynamic key from numbers_mt(5000000): it runs no DDL, so it never reaches the dependency collection this PR changes ClickHouse/performance-comparison#5 (external, open): the dashboard's confidence scoring, where @ fm4v handles these verdicts after #121847, which is present in this head. That repository is not publicly readable, so its state cannot be measured from here
Mergeable Check, PR rollups, red only because of the row above ClickHouse/performance-comparison#5 (external, open), the same owner as the row above
Sync - CH Inc sync (private, not actionable by me)

All 176 check runs completed (133 pass, 39 not selected, 4 red) and Finish Workflow is green.
CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20260926-143040

@PedroTadim PedroTadim self-assigned this Sep 28, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 29, 2026
The previous commit fixed one producer of a query plan whose read step has no join runtime filter
lookup, the scalar subquery of a `TTL` or `CHECK` expression. The analyzer's own scalar subquery
evaluation has the same problem whenever `evaluateConstantExpression` runs on the global context,
for example for the arguments of the table function of `CREATE TABLE ... AS <table function>`
(`ITableFunction::execute` with `use_global_context`) and in the dependency analysis of `CREATE`
(ClickHouse#122390). This crashes the server in `buildRuntimeRangePredicate` (`p` is a MergeTree table
ordered by `k`):

    CREATE TABLE t AS numbers(assumeNotNull((SELECT count() FROM p, b WHERE p.k = b.k)));

The two halves of a join runtime filter disagreed on where they meet: the build side
(`BuildRuntimeFilterStep`), `__applyFilter` and `HashJoin` use the lookup of the thread's query
context, while the index analysis of the probe side used the lookup of its read step's context,
which is null when the plan was built with a context that never went through
`Context::makeQueryContext`. Fix it in the runtime filter code instead of in each producer:
* `ReadFromMergeTree` takes the lookup from the thread's query context too, and skips the
  read-time pruning if the thread has none;
* join runtime filters are not added to a plan built on a thread without a query context (table
  loading, the replication queue), where the build side and `__applyFilter` cannot work at all.
Each part is needed: without the first the `CREATE` of the `TTL` table crashes again, without the
second loading the tables aborts with `Query context is not available for __applyFilter`.

This replaces the change of the previous commit in `ExecuteScalarSubqueriesVisitor`, which is
reverted. The analysis contexts are still not query contexts, so a table function in such a
subquery is still rejected with `THERE_IS_NO_QUERY`.

The test gets two more arms: `CREATE TABLE ... AS numbers(...)`, read again after the database is
re-attached, and a view reading through `cluster` with the cluster name computed by such a
subquery, whose dependency on the table it reads is checked.

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

Copy link
Copy Markdown
Collaborator Author

Superseded by #122795: it fixes this case in the join runtime filter code (the read step takes the lookup from the thread's query context), without making the dependency analysis context a query context, and its test has the same cluster view arm. So this PR is no longer needed.

@PedroTadim PedroTadim closed this Sep 29, 2026
raimannma pushed a commit to raimannma/ClickHouse that referenced this pull request Oct 1, 2026
… JOIN

A scalar subquery with a `JOIN` in a `TTL` expression crashes the server on `CREATE`
(`p` is a MergeTree table ordered by `k`):

    CREATE TABLE t (d DateTime, x UInt64) ENGINE = MergeTree ORDER BY tuple()
    TTL d + INTERVAL 1 YEAR WHERE x < (SELECT count() FROM db.p AS p, db.b AS b WHERE p.k = b.k);

with a null read in `buildRuntimeRangePredicate`. The same subquery in a `CHECK` constraint is
created fine, but loading the table afterwards (a restart or `ATTACH DATABASE`) aborts with
`Logical error: 'Query context is not available for __applyFilter'`, and so does a replica
applying `ALTER ... MODIFY TTL` of a `ReplicatedMergeTree`, from `ReplicatedMergeTreeQueue`.

Since ClickHouse#121418 `ExecuteScalarSubqueriesVisitor` plans such a subquery with
`InterpreterSelectQueryAnalyzer`, so its `JOIN` gets join runtime filters. They rendezvous through
a per-query `IRuntimeFilterLookup` that only `Context::makeQueryContext` creates: the index analysis
of the probe side reads the lookup of its read step's context, the build side and `__applyFilter`
read the query context of the current thread. A `TTL` expression (`registerStorageMergeTree`, and
`ReplicatedMergeTreeTableMetadata::Diff::getNewMetadata` on a replica) and a `CHECK` constraint of a
table being loaded (`DatabaseOnDisk`) are analysed with a copy of the global context, which is not a
query context, and the table loader and replication threads run no query. A `CHECK` constraint at
`CREATE` is fine because it is analysed with the context of the `CREATE` query.

The subquery keeps the context it is analysed with and gets what the join runtime filters need:
* a thread with no thread group is attached to a query by a `QueryScope`: the query of that
  context if it has one, otherwise a copy of the context made a query context. The scope is
  created before the interpreter, because the analyzer already executes nested scalar subqueries
  in its constructor, and `getQueryInterpreter` returns that query together with the interpreter,
  because every other reference to a query context is weak (`Context::query_context`,
  `ThreadGroup`) and it has to outlive the pipeline;
* it takes the filter lookup of the current thread's query context, the one the build side and
  `__applyFilter` use.
Each part is needed: without the lookup the `CREATE` crashes again, without the scope or without
keeping its query alive the load aborts again, and with the scope created only after the
interpreter a `JOIN` in a nested scalar subquery still aborts the load.

The analysis context itself is not made a query context: that would also make table functions
resolve in the subquery (`QueryAnalyzer::resolveTableFunction` needs a query context), and a table
function in such a subquery is still rejected with `THERE_IS_NO_QUERY`, as before.

26.8 and 26.9 run these subqueries with the old interpreter, without join runtime filters, so this
is master-only. Found in the review of ClickHouse#122390, which fixes the other producer of a plan without a
lookup, the dependency analysis of `CREATE`.

The new test has one arm per carrier: `TTL ... WHERE` at `CREATE`, `CHECK` at load, a `JOIN` only in
a nested scalar subquery of a `CHECK`, and a replicated `MODIFY TTL` in an `Atomic` and in a
`Replicated` database. Each arm alone kills or aborts the unfixed server. Two more arms check that a
table function in such a subquery is still rejected, and that at `CREATE` the `TTL` subquery built a
join runtime filter and the index analysis of its read used it (`RuntimeFiltersCreated`,
`RuntimeFilterGranulesConsidered`). There is no `TTL ... GROUP BY ... SET` arm: query parameters are
not substituted in its assignments, and a TTL is not analysed in the database of the statement.

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

can be tested Allows running workflows for external contributors comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants