Repository navigation
Fix a crash when a CHECK constraint's scalar subquery reads a Distributed table - #121418
Conversation
… Distributed table
A `CREATE TABLE` whose `CHECK` constraint contains a scalar subquery over a
`Distributed` table or `remote(...)` kills the server:
CREATE TABLE t (x UInt64, CONSTRAINT c CHECK x < (SELECT max(id) + 1000
FROM remote('127.0.0.1', currentDatabase(), 'src'))) ENGINE = MergeTree ORDER BY tuple();
`InterpreterCreateQuery::getConstraintsDescription` analyses every constraint with
`TreeRewriter::analyze`, which runs `executeScalarSubqueries`; that visitor built
`InterpreterSelectWithUnionQuery` unconditionally, and the old interpreter never
assigns `query_info.query_tree` or `query_info.planner_context`. Since
`StorageDistributed::read` has no non-analyzer arm any more, it dereferences the
planner context unconditionally and the read faults on a null pointer.
A `TTL ... WHERE` predicate is a second carrier of the same fault, not a separate bug:
`TTLDescription::getTTLFromAST` analyses the `DELETE WHERE` predicate through the same
`TreeRewriter::analyze` (`TTLDescription.cpp:1490` then `:1270`), so the one fix resolves
both slots. The two differ in how the source may be named: the `remote(...)` table
function is rejected before planning there with `THERE_IS_NO_QUERY`, because a TTL
description is built without a query context and resolving a table *function* needs one,
so only a named `Distributed` table reaches the dereference. Both slots are covered by the
new test, the `TTL` one through a named table.
The branch that used to hide this was keyed on `allow_experimental_analyzer`, which has
been frozen at 1 since ClickHouse#118629, and ClickHouse#120311 removed it. That commit's own note in
`InterpreterSelectQuery.h` asks new callers to use `InterpreterSelectQueryAnalyzer`; a
scalar subquery of a standalone expression is the user's own `SELECT`, i.e. exactly that
case. The crash is not a regression of ClickHouse#120311: the same dereference and the same
interpreter construction exist on 26.9 and 26.8, where that setting's default of 1 selects
the analyzer arm as well.
The identical dereference was reached once before through `StorageMaterializedView` and
fixed at its origin by ClickHouse#107653. This is a second entry path, so the producer is fixed
rather than the storage: a null guard in `StorageDistributed` would have no arm to fall
back to and could only throw, turning a crash into a rejected statement that works on
26.9, and it would have to be repeated for every analyzer-only engine.
The interpreter swap carries over four behaviours of the old path, each matching the
analyzer's own scalar-subquery executor in
`src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp`:
* the materialized-view source substitution `JoinedTables::getLeftTableStorage` did,
through the `InterpreterSelectQueryAnalyzer` storage overload, so a scalar subquery
compiled during a view push still reads the inserted block;
* `use_structure_from_insertion_table_in_table_functions` in the subquery settings,
because `QueryAnalyzer` reads it from the scope context rather than from the query
context the pre-existing line mutates (that line stays, it is issue ClickHouse#52494's);
* `allow_experimental_parallel_reading_from_replicas = 0`, because `Planner`'s
constructor inspects the tree for parallel-replica candidates;
* `options.forceMaterializeCTE()`, because `collectMaterializedCTEs` returns nothing for
subquery options, so a materialized CTE would be read unpopulated.
Disabling parallel replicas on the subquery context alone is not enough, and the setting is
also stripped from a clone of the subquery AST. `QueryTreeBuilder::buildSelectExpression`
applies a SELECT's own `SETTINGS` clause onto the context it stamps on the `QueryNode`, and
`findQueryForParallelReplicas` reads the decision from that node context inside `Planner`'s
member-init list, i.e. inside the interpreter's constructor, where nothing can repair it
afterwards. Without the strip, a scalar subquery whose own clause turns parallel replicas on
and names a cluster that does not exist is rejected with `CLUSTER_DOESNT_EXIST` where it used
to succeed: measured on the constraint above with
`parallel_replicas_for_non_replicated_merge_tree = 1` in the same clause. Both spellings of the
aliased setting are stripped, the way the automatic-parallel-replicas probe in
`InterpreterSelectQueryAnalyzer` strips the settings it overrides, and from a clone because the
AST belongs to the statement being analysed rather than to this helper.
The test's session-level arm pins `automatic_parallel_replicas_mode = 0`, which is that
setting's own default. The test runner draws 2 for it in a quarter of runs, and with the
statement's `allow_experimental_parallel_reading_from_replicas = 1` inherited,
`InterpreterSelectQueryAnalyzer::buildContext` then clears `enable_parallel_replicas` on its
own context copy, so the subquery would never reach a cluster lookup and the arm would stop
exercising the strip at all in those runs.
The recursive nested-context walk the reference executor also does stays uncopied: it clones an
already-built tree whose nested nodes carry the original context, while this path builds the
tree from an AST with the subquery context, and `QueryTreeBuilder` stamps a copy of that context
onto every node it creates.
`usesViewSource()` lives on `IInterpreterUnionOrSelectQuery` and has no counterpart on
the analyzer interpreter, so both call sites ask the built query tree with the existing
`isStorageUsedInTree`. The answer is the same wherever the old flag was true and
conservative elsewhere: a scalar can only move from the global cache to the per-query
one, never the reverse.
Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 5 findings over 4 rounds, 4 raised by
Severity: ❌ blocker / Noted and not blocking:
Session id: cron:clickhouse-review-slot-8:20260921-183300 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260921-171700 |
|
Workflow [PR], commit [73fa0e3] Summary: ❌
AI ReviewSummaryThis PR moves scalar subqueries in standalone expressions onto PR Metadata
Exact replacement: ### Changelog category (leave one):
- Critical Bug Fix (crash, data loss, RBAC)Final Verdict✅ No blocking code findings. Change the changelog category to LLVM Coverage ReportMeasured on commit 73fa0e3.
Changed lines: Changed C/C++ lines covered: 32/36 (88.89%) · Uncovered code |
Build profile diff (arm_release)Commit See the job log for details. |
A `CHECK` constraint and a `TTL` expression are analysed with the global
context - `StorageFactory` hands the storage `args.getContext()`, which never
went through `Context::makeQueryContext` and so carries a zero client version.
Reading a `Distributed` table from such a subquery therefore sends a shard
query with an unknown initiator version, and `RemoteQueryExecutor::sendQueryUnlocked`
rejects it:
Sending a distributed query with unknown (zero) client version.
The query context was not initialized as an initial query
Until the previous commit the same statement dereferenced a null
`query_info.planner_context` and killed the server, so this is the next
failure on the same path rather than a new one. This server is the real
initiator of the subquery, so fill in its own version, exactly as
`Context::makeQueryContext` does for the other server-initiated queries and
`DDLTaskBase::makeQueryContext` does for a replayed DDL.
The shard of `test_shard_localhost` is local, so `prefer_localhost_replica`
decides whether `RemoteQueryExecutor` is reached at all; the new test case
pins the network path. Found by `Stress test (arm_asan_ubsan, meta in keeper)`
of the private sync of this pull request (STID: 4148-3044).
`t_scalar_constraint_user` is now dropped as soon as the `DETACH`/`ATTACH`
check is done. A `remote(...)` subquery still cannot be analysed during the
asynchronous database load - `QueryAnalyzer::resolveTableFunction` needs a
query context and a loading table has none - so a stress-test restart taken
while that table exists fails to load it.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
CI finish ledger - 6d65f59Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Gates (a) to (d): 0 of 176 check runs queued or running, Session id: cron:our-pr-ci-monitor:20260922-060304 |
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121418&sha=6d65f5936b09462cd8b3640348583ee081a97ab7&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. Both rows of That failed attach then makes the Fix opened: #121506 |
…query-analyzer-distributed-crash
|
Fixing PR for the That closes the owner column for the ledger line I left open above. Both rows from that job ( Separately, the release branch itself still carries the producer bug, so I asked for |
CI finish ledger - 91ecf88Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
This head is clean everywhere else: a CIDB scan scoped to Why #121260 and not the dashboard-gate fix #121090: this shard's own report does call Not caused by this branch. Session id: cron:our-pr-ci-monitor:20260922-110203 |
ddae061
|
@alexey-milovidov this master CI failure seems related to this PR https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=29dde9d3645cc35344c2edf312b4a453a0630a81&name_0=MasterCI&name_1=Stress%20test%20%28amd_asan_ubsan%29 @groeneai are you looking at this? |
|
@PedroTadim Yes, tracked. Fix PR: #121952, opened 10:35 UTC, after that job started at 08:59 UTC, so master@29dde9d3 does not contain it yet. That run died on Two occurrences so far, both from before the pin: this master run and The loader-side gap itself is pre-existing and not |
This branch rejects a scalar subquery in a `CHECK` constraint on `CREATE TABLE`, so the master test `05234_constraint_scalar_subquery_over_distributed` (added by #121418) cannot create its constraint tables anymore. The `CHECK` cases now expect `BAD_ARGUMENTS`; the `throwIf` probe also shows the remote subquery is not executed on the way. The parallel-replica cases only guarded the execution of such a constraint's subquery, which cannot happen now, so they are removed. The `TTL DELETE WHERE` cases, including the one over the network with `prefer_localhost_replica = 0`, stay unchanged: `TTLDescription` keeps the legacy `TreeRewriter` path on this branch, same as on master. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96886&sha=3e8f0c349a19f06d1da16b219d40abc10303c1c0&name_0=PR&name_1=Fast%20test #96886 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…queries-via-analyzer Brings in #121418, which fixes the `AST fuzzer (amd_debug, targeted)` red `Segmentation fault (STID: 3422-39ed)` on 983463d (the scalar-subquery producer through `ExecuteScalarSubqueriesVisitor`): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121639&sha=983463d6ae29e47625c100c134e9f40c822a41e8&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 PR: #121639 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ottling Pulls in ClickHouse#121418 (tsan segfault in `StorageDistributed::read` from a scalar subquery) and the upgrade check recovery of read-only replicas that refuse `KILL MUTATION`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… 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]>
…e analyzer A standalone expression - a row policy, a `CHECK` constraint, a `TTL` expression - is compiled by `ExpressionAnalyzer`, and `ActionsMatcher::makeSet` built the plan of an `IN` subquery in it with the interpreter that preceded the analyzer. `StorageDistributed` resolves its read through a query tree and a planner context that interpreter never builds, and dereferences them unconditionally, so reading a `Distributed` table from such a subquery crashed the server. `IInterpreterUnionOrSelectQuery` used to set `allow_experimental_analyzer = 0` on the interpreter's own context, and the storages read under it took their AST arm. ClickHouse#120311 removed the assignment together with the arms it protected, which is what uncovered the dereference. It is the same defect as ClickHouse#121464, reached through a second producer: ClickHouse#121418 replaces the one in `ExecuteScalarSubqueriesVisitor`, which accounts for 27 of the 29 occurrences of the two sibling STIDs in the CI database over the last five days; the other two come through `interpretSubquery`, and the STID does not tell them apart because it is computed from the top of the stack, which both share. `makeSet` now builds the plan with `InterpreterSelectQueryAnalyzer`. What `interpretSubquery` does around it - a table name or a table function becomes `SELECT <columns> FROM it`, and the subquery gets its own context with the whole-query result limits lifted - is shared as `prepareSubquery` rather than duplicated. `makeSet` already built a query tree of the same subquery for its set key, so the analyzer was on this path before this change. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=e96f004b984ced9a97237e99b3e744599a917870&name_0=MasterCI&name_1=Stress%20test%20%28arm_tsan%29 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Related: #107653
Related: #120311
Related: #121464
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a server crash when a scalar subquery inside a standalone expression, such as a
CHECKconstraint or aTTLexpression, reads aDistributedtable or theremotetable function.Description
On 26.8 a plain statement kills the server, through the same unguarded dereference:
Found by the AST fuzzer on my PR #121280:
Stress test (arm_tsan),Segmentation fault (STID: 3422-39ed), report.TreeRewriterstill runs the scalar subquery of a standalone expression throughInterpreterSelectWithUnionQuery, which yields aSelectQueryInfowith no query tree and no planner context, whileStorageDistributed::readdereferencesquery_info.planner_contextunconditionally. The branch that hid that was dead onceallow_experimental_analyzerwas frozen at 1 (#118629), and #120311 removed it; that PR's note inInterpreterSelectQuery.hasks new callers to useInterpreterSelectQueryAnalyzer. The identical dereference was reached before through a materialized view and fixed at its origin by #107653, so I fixed the producer rather than guarding one storage.The swap carries over the setup of the analyzer's own scalar executor: view-source substitution through the storage overload, parallel replicas off, the insertion-table structure hint suppressed, and forced CTE materialization. Pinning parallel replicas on the context is not enough, since the query tree builder re-applies a
SETTINGSclause written inside the subquery over the node context the planner reads, so both spellings of that setting are stripped from a clone.usesViewSource()does not exist on the analyzer interpreter, so both call sites now ask the built query tree.Once the crash is gone the same statement reaches the next defect on that path. A standalone expression is analysed with the global context -
StorageFactoryhands the storageargs.getContext(), which never went throughContext::makeQueryContextand so carries a zero client version - andRemoteQueryExecutor::sendQueryUnlockedrejects a shard query with an unknown initiator version. It stays invisible while the shard is local, whichtest_shard_localhostis, so the public run reads it withoutRemoteQueryExecutor; the private sync caught it inStress test (arm_asan_ubsan, meta in keeper)(STID: 4148-3044). The subquery context now reports this server's own version, exactly asContext::makeQueryContextdoes for the other server-initiated queries andDDLTaskBase::makeQueryContextdoes for a replayed DDL, and a new test case pins the network path withprefer_localhost_replica = 0.Validated both directions (gdb, then the new test on unpatched and patched servers), 100/100 randomized and plain runs, and an A/B sweep of 172 neighbouring tests with no new failure.
Also noticed and left alone, both identical without the fix: an
INSERTinto a table with such a constraint fails withUNKNOWN_IDENTIFIER, and such a table usingremote(...)fails to load at startup withTHERE_IS_NO_QUERY; #96886 rewrites that code. The test therefore drops the table carrying theremote(...)constraint as soon as itsDETACH/ATTACHcheck is done, so that a stress-test restart does not land on it.Workflow [PR]
Sync PR [sync-upstream/pr/121418]
Version info
26.10.1.573-master(included in26.10and later)