Repository navigation
Fix crash reading materialized view over Distributed table with old interpreter - #107653
Conversation
…nterpreter When a materialized view whose target is a Distributed table is read by the old interpreter (allow_experimental_analyzer = 0), query_info carries no query tree, but the analyzer-only code in StorageDistributed::read (buildQueryTreeDistributed) dereferences the planner context. This is a null pointer dereference (SIGSEGV). The old interpreter keeps allow_experimental_analyzer off on its context, but StorageMaterializedView::readImpl builds the read context via getSQLSecurityOverriddenContext, which for DEFINER/NONE views recreates the context from the global one and clamps the caller settings against the definer constraints. The analyzer setting can therefore be silently turned back on, diverging from the interpreter that actually built query_info. Preserve the interpreter mode on the SQL security overridden context so the target storage takes the same (old) code path that produced query_info. Found by the BuzzHouse fuzzer. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-1:20260616-170900 |
|
cc @al13n321 @azat — could you review? Null planner-context deref reading a materialized view over a |
|
Workflow [PR], commit [64adf2c] Summary: ✅
AI ReviewSummaryThis PR preserves the old-interpreter PR Metadata
- Critical Bug Fix (crash, data loss, RBAC)Final VerdictStatus: ✅ Approve |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 5/5 (100.00%) | Lost baseline coverage: none · Uncovered code |
|
CI finished on Red checks, all attributed to infrastructure (not this PR):
Ready for review. |
|
Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment. TL;DRFix crash reading materialized view over Distributed table with old interpreter ClickGap verified: reproduced it with the script below on ReproductionBisect
Affects
Suggested next stepThe fix has landed on master; the affected release branches above still need the backport. Component: ClickGap · Finding: Triage metadata |
… 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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a server crash when reading a materialized view whose target is a
Distributedtable while the query runs withenable_analyzer = 0.Description
Found by the BuzzHouse fuzzer. CI:
BuzzHouse (amd_msan)on report https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107318&sha=68307276ece200b8028af8d16212923a409cd3ee&name_0=PR&name_1=BuzzHouse%20%28amd_msan%29 (STID 3422-364d; the PR there only touches S3 upload code, so the crash is a pre-existing trunk bug, not caused by that PR). No related open issue found.Crash: null pointer dereference (SIGSEGV) at
PlannerContext::getQueryContext()inbuildQueryTreeDistributed(StorageDistributed.cpp), reached viaStorageMaterializedView::readImpl->StorageDistributed::read.Root cause. When a materialized view over a
Distributedtable is read by the old interpreter (enable_analyzer = 0),query_infohas no query tree (the old interpreter never populatesplanner_context). The analyzer-only branch inStorageDistributed::read, however, is selected by the liveallow_experimental_analyzersetting and then dereferencesquery_info.planner_context, which is null.The two can diverge: the old interpreter keeps
allow_experimental_analyzeroff on its context, butStorageMaterializedView::readImplbuilds the read context withgetSQLSecurityOverriddenContext. ForDEFINER/NONEviews that recreates the context from the global one and clamps the caller's settings against the definer's constraints, so the caller'senable_analyzer = 0can be silently dropped and the read context ends up with the analyzer back on.Fix. Preserve the interpreter mode on the SQL-security overridden context: when the materialized view is read by the old interpreter, keep
allow_experimental_analyzeroff on the read context so the target storage takes the same (old) code path that actually producedquery_info. This is the origin of the bad state, so it also protects the other analyzer-only sites reached from this read path (getQueryProcessingStage,ClusterProxy::executeQuery), not just the one frame that crashed.Regular views (
StorageView) andMergeare not affected:StorageViewbuilds a fresh sub-interpreter for its inner query, andStorageMergealready guards every planner-context use with a null check. Only the materialized-view read path forwards the outerquery_info(with a possibly-null query tree) straight into the target storage'sread().Added a stateless regression test that crashes without the fix and passes with it.
Version info
26.6.1.963