Repository navigation
Fix a crash and a table load failure when a table definition has a scalar subquery with JOIN - #122795
Conversation
… 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]>
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
Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20260929-032000 |
|
Workflow [PR], commit [42b433f] Summary: ✅
AI ReviewSummaryThis PR fixes the join-runtime-filter/query-context mismatch for standalone scalar-subquery evaluation by making probe-side Final Verdict✅ No new review findings. This looks ready once CI finishes green. LLVM Coverage ReportMeasured on commit 42b433f.
Changed lines: Changed C/C++ lines covered: 31/31 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 42 s compile time in total, 8 of them have a recent master baseline. |
|
|
||
| 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()) |
There was a problem hiding this comment.
@groeneai make sure this fix is not needed elsewhere. We have been fixing a few of these crashes lately
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]>
Related: #121418
Related: #122390
Changelog category (leave one):
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 aJOINandenable_join_runtime_filters_index_analysisis enabled in the default settings profile.Description
On 26.9.1.1629 with
enable_join_runtime_filters_index_analysis = 1in the default profile, and on master by default, this kills the server inbuildRuntimeRangePredicate(pis a MergeTree ordered byk):On master, since #121418, the same happens for such a subquery in a
TTLexpression, and one in aCHECKconstraint makes loading the table fail withLogical error: 'Query context is not available for __applyFilter', as does a replica applying such aMODIFY TTL. #122390 is another instance, in the dependency analysis ofCREATE.The two halves of a join runtime filter meet in a per-query lookup: the build side,
__applyFilterandHashJointake 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,TTLandCHECKexpressions, 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:
ReadFromMergeTreetakes 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
TTLsubquery'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
26.10.1.1222-master(included in26.10and later)