Skip to content

Fix a crash and a table load failure when a table definition has a scalar subquery with JOIN - #122795

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-standalone-expression-scalar-subquery-query-context
Oct 1, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-standalone-expression-scalar-subquery-query-context

Conversation

@groeneai

@groeneai groeneai commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121418
Related: #122390

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 in CREATE TABLE ... AS <table function> when an argument of the table function is a scalar subquery with a JOIN and enable_join_runtime_filters_index_analysis is enabled in the default settings profile.

Description

On 26.9.1.1629 with enable_join_runtime_filters_index_analysis = 1 in the default profile, and on master by default, this kills the server in buildRuntimeRangePredicate (p is a MergeTree ordered by k):

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

On master, since #121418, the same happens for such a subquery in a TTL expression, and one in a CHECK constraint makes loading the table fail with Logical error: 'Query context is not available for __applyFilter', as does a replica applying such a MODIFY TTL. #122390 is another instance, in the dependency analysis of CREATE.

The two halves of a join runtime filter meet in a per-query lookup: the build side, __applyFilter and HashJoin take it from the thread's query context, but the index analysis of the probe side took it from its read step's context, which has none when the subquery is planned with a copy of the global context (table function arguments, TTL and CHECK expressions, dependency analysis). A thread that runs no query (table loading, the replication queue) cannot use a join runtime filter at all.

So the fix is in the runtime filter code and covers every such caller: ReadFromMergeTree takes the lookup from the thread's query context, and join runtime filters are not planned on a thread without one. The analysis contexts are unchanged, so a table function in such a subquery stays rejected.

The test has one arm per caller, each of which kills or aborts the unfixed server, and checks that the TTL subquery's read still uses its join runtime filter. 50 randomized runs pass.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits September 29, 2026 02:44
… 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]>
Shorten the three comments added in ExecuteScalarSubqueriesVisitor.cpp to one line each, keeping only their invariants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 29, 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) plus my own review; 4 review rounds, the last one with
no new finding. Every fix below is in this PR's code (earlier revisions were never pushed).

# Sev Finding Verdict Evidence / action
1 ❌ An earlier revision made the subquery's analysis context a query context, which also changed behaviour: a table function in a TTL subquery, rejected until then, resolved AGREE, fixed The analysis context is kept as it was; only the join runtime filters get a filter lookup and a thread scope. New test arm: a table function stays rejected with the same error.
2 ⚠️ The description promised that a CHECK subquery reading remote(...) now loads, without a test AGREE, fixed The claim is withdrawn: with row 1 fixed that load keeps failing, as 05234 documents.
3 ⚠️ The test would also pass if the join runtime filter were silently disabled, or built but not used by the read (raised twice) AGREE, fixed Canary on the CREATE in system.query_log: RuntimeFiltersCreated > 0 and RuntimeFilterGranulesConsidered > 0; the second is only counted when the read step finds the filter the build side registered (a mutant giving the read a fresh lookup fails only that column).
4 💡 The branch for a thread with no query whose context already is a query context (a replica of a table in a Replicated database) is not covered AGREE, fixed It aborted the unfixed server, so the test has a Replicated-database arm; skipping the scope there fails exactly that arm.
5 💡 That arm does not prove the read shares the lookup: a scope on a fresh query would keep it green (raised twice) AGREE, fixed No SQL observable exists for the replica's queue work, so the read step now always takes the lookup of the thread's query, which the build side and __applyFilter use. Checked in the server log: a scope on a fresh query loses the replica's read-time predicate on the previous revision and keeps it on this one.
6 💡 The title called the CHECK load failure a crash AGREE, fixed The title names both: a crash at CREATE, a logical error at load.
7 💡 The commit message described an earlier revision AGREE, fixed Rewritten for the final design.
8 💡 The explicit makeQueryContext() before QueryScope::create is redundant (the scope does it) AGREE, not changed Kept: it states at the call site that the copy becomes a query context.

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-self-slot-58:20260929-032000

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [42b433f]

Summary: ✅


AI Review

Summary

This PR fixes the join-runtime-filter/query-context mismatch for standalone scalar-subquery evaluation by making probe-side ReadFromMergeTree pruning use the active thread's query lookup and by skipping runtime-filter planning on threads that have no query scope. I reviewed the current diff, the touched runtime-filter consumers/producers, and the existing discussion, and I did not find a remaining correctness or coverage gap in the changed paths.

Final Verdict

✅ No new review findings. This looks ready once CI finishes green.

LLVM Coverage Report

Measured on commit 42b433f.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 31/31 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 29, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 42b433f2f with master 80508bd5f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 61fda56c2; 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

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

Job report

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

@PedroTadim PedroTadim self-assigned this Sep 29, 2026

return std::make_unique<InterpreterSelectQueryAnalyzer>(
/// A thread with no query (e.g. loading tables) is attached before the constructor, which already executes nested scalar subqueries.
if (!CurrentThread::getGroup())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai make sure this fix is not needed elsewhere. We have been fixing a few of these crashes lately

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked, and it is needed elsewhere. The analyzer's scalar subquery evaluation hits the same null lookup whenever evaluateConstantExpression runs on the global context. On master 6ee563b and on this PR, both of these crash in buildRuntimeRangePredicate (p is a MergeTree ORDER BY k with 10000 rows, b has 10 rows):

CREATE TABLE t1 AS numbers(assumeNotNull((SELECT count() FROM p, b WHERE p.k = b.k)));
CREATE TABLE t2 AS values('a UInt64', (SELECT count() FROM p, b WHERE p.k = b.k));

There ITableFunction::execute evaluates the arguments with the global context. #122390 is the same class, through DDLDependencyVisitor.

With the same subquery, these do not crash on master: mutations and lightweight DELETE with IN (SELECT ...), dictionaries with a QUERY source (load, reload, restart), refreshable and insert-time MVs, background Buffer flushes into MVs, Merge and URL engine arguments (create and restart). DEFAULT/MATERIALIZED subqueries and IN (subquery) in TTL/CHECK are rejected before execution.

So instead of patching the producers one by one, I'm moving the fix into the runtime filter code: ReadFromMergeTree will take the lookup from the thread's query context, as BuildRuntimeFilterStep, __applyFilter and HashJoin already do, and join runtime filters won't be planned on a thread without a query (table loading, the replicated queue). This replaces the change in ExecuteScalarSubqueriesVisitor and makes #122390 unnecessary. A local build already passes all of the above, plus the TTL/CHECK cases and their restarts. I'll push it here after the tests.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pushed 8cc48ce: ReadFromMergeTree now takes the lookup from the thread's query context, join runtime filters are not planned on a thread without one, and the change in ExecuteScalarSubqueriesVisitor is reverted. The test got the CREATE TABLE ... AS numbers(...) and cluster view arms.

The table function case also crashes the official 26.9.1.1629 server when enable_join_runtime_filters_index_analysis is enabled in the default profile, so I changed the category to Bug Fix.

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 groeneai changed the title Fix a crash and a table load failure when a TTL or CHECK subquery has a JOIN Fix a crash and a table load failure when a table definition has a scalar subquery with JOIN Sep 29, 2026
@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... and removed pr-not-for-changelog This PR should not be mentioned in the changelog comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 29, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit 38fd308 Oct 1, 2026
149 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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.

3 participants