Skip to content

Fix crash reading materialized view over Distributed table with old interpreter - #107653

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-mv-over-distributed-old-analyzer-crash
Jun 18, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-mv-over-distributed-old-analyzer-crash

Conversation

@groeneai

@groeneai groeneai commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fix a server crash when reading a materialized view whose target is a Distributed table while the query runs with enable_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() in buildQueryTreeDistributed (StorageDistributed.cpp), reached via StorageMaterializedView::readImpl -> StorageDistributed::read.

Root cause. When a materialized view over a Distributed table is read by the old interpreter (enable_analyzer = 0), query_info has no query tree (the old interpreter never populates planner_context). The analyzer-only branch in StorageDistributed::read, however, is selected by the live allow_experimental_analyzer setting and then dereferences query_info.planner_context, which is null.

The two can diverge: the old interpreter keeps allow_experimental_analyzer off on its context, but StorageMaterializedView::readImpl builds the read context with getSQLSecurityOverriddenContext. For DEFINER/NONE views that recreates the context from the global one and clamps the caller's settings against the definer's constraints, so the caller's enable_analyzer = 0 can 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_analyzer off on the read context so the target storage takes the same (old) code path that actually produced query_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) and Merge are not affected: StorageView builds a fresh sub-interpreter for its inner query, and StorageMerge already guards every planner-context use with a null check. Only the materialized-view read path forwards the outer query_info (with a possibly-null query tree) straight into the target storage's read().

Added a stateless regression test that crashes without the fix and passes with it.

Version info

  • Merged into: 26.6.1.963

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE USER d IDENTIFIED WITH no_password SETTINGS enable_analyzer = 1 CONST; GRANT SELECT ON *.* TO d; then a MV with ENGINE = Distributed(test_shard_localhost, currentDatabase(), local) DEFINER = d SQL SECURITY DEFINER and SELECT * FROM mv SETTINGS enable_analyzer = 0 crashes every time (SIGSEGV at PlannerContext.h:115 / StorageDistributed.cpp:870). Captured as test 04338_materialized_view_over_distributed_old_analyzer_crash.
b Root cause explained? Yes. Outer query runs the old interpreter (enable_analyzer = 0), so query_info has no query tree/planner context. StorageMaterializedView::readImpl rebuilds the read context via getSQLSecurityOverriddenContext; for DEFINER/NONE views that recreates the context from the global one and clamps the caller settings against the definer's enable_analyzer = 1 CONST, dropping the caller's enable_analyzer = 0. StorageDistributed::read then selects the analyzer branch on the live setting (now on) and buildQueryTreeDistributed dereferences the null planner_context.
c Fix matches root cause? Yes. The fix restores the interpreter-mode invariant at its origin: if the view is being read by the old interpreter, force allow_experimental_analyzer off on the SQL-security overridden context, so the target storage takes the same (old) path that produced query_info. This is what the old interpreter already does to its own context (IInterpreterUnionOrSelectQuery ctor); the override was discarding it.
d Test intent preserved / new tests added? New stateless regression test added (crash repro). No existing test modified.
e Both directions demonstrated? Yes. Without fix (build 4d295f4c): the test query SIGSEGVs at the exact CI stack. With fix (build 3278e11b): returns 10 45 / 10 45 for both enable_analyzer = 0 and = 1, server stays up.
f Fix is general, not a narrow patch? Fixed at the origin (the context that injected the bad analyzer state), so it covers all analyzer-only sites reached from this read path (getQueryProcessingStage, buildQueryTreeDistributed, ClusterProxy::executeQuery), not just the crashing frame. Checked siblings: the other getSQLSecurityOverriddenContext sites in the file are CREATE-time access checks / the INSERT (write) path / refresh (builds its own interpreter) and do not forward a null-query-tree query_info into a target read(). StorageView builds a fresh sub-interpreter; StorageMerge already null-guards its planner-context use. The MV read path is the only one that forwards the outer query_info straight into the target storage.

Session id: cron:clickhouse-worker-slot-1:20260616-170900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @azat — could you review? Null planner-context deref reading a materialized view over a Distributed table when enable_analyzer=0. The DEFINER/NONE SQL-security context could silently re-enable the analyzer, diverging from the old interpreter that built query_info; the fix preserves the interpreter mode on that context.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [64adf2c]

Summary: ✅


AI Review

Summary

This PR preserves the old-interpreter allow_experimental_analyzer state after the materialized-view SQL-security context is rebuilt, so a Distributed target does not take analyzer-only paths with a null planner_context. The code change is narrowly scoped and the added stateless test covers the reported regression; I found no code-level blockers.

PR Metadata
  • 💡 The Changelog category should be Critical Bug Fix (crash, data loss, RBAC) rather than Bug Fix (user-visible misbehavior in an official stable release), because the PR title, description, and changelog entry all describe a server crash. Suggested replacement:
- Critical Bug Fix (crash, data loss, RBAC)
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.40% 77.40% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 5/5 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on 64adf2c8c52a9256ca7821030da58f7ea5490758. No PR-caused failures; the regression test 04338_materialized_view_over_distributed_old_analyzer_crash passed and the server no longer crashes.

Red checks, all attributed to infrastructure (not this PR):

  • Bugfix validation (functional tests) rows (Lost s3 keys, Exception in test runner, OOM in dmesg, S3_ERROR No such key, Lost forever for SharedMergeTree): a cross-PR S3/runner infra outage in this window, with the identical row set on 53 distinct PRs in the last 24h. Not specific to this change.
  • CH Inc sync: internal sync job, always red on fork PRs.

Ready for review.

@alexey-milovidov alexey-milovidov left a comment

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.

This is weird.

@alexey-milovidov alexey-milovidov self-assigned this Jun 18, 2026
@alexey-milovidov
alexey-milovidov merged commit 952967d into ClickHouse:master Jun 18, 2026
164 of 165 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 18, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Fix crash reading materialized view over Distributed table with old interpreter

ClickGap verified: reproduced it with the script below on 26.5; tested 6 version(s) — 5 affected, 1 clean (see Affects); present since the feature was introduced in v24.8 (not a recent regression).

Reproduction

-- Needs a server with the standard predefined cluster `test_shard_localhost`.
CREATE TABLE t_local (a UInt64, b String) ENGINE = MergeTree ORDER BY a;
INSERT INTO t_local SELECT number, toString(number) FROM numbers(10);

-- Definer pins enable_analyzer = 1 with a CONST constraint, so the caller's
-- enable_analyzer = 0 is clamped away when the SQL-security overridden context
-- is built for the materialized view read.
CREATE USER mv_definer IDENTIFIED WITH no_password SETTINGS enable_analyzer = 1 CONST;
GRANT SELECT ON *.* TO mv_definer;

CREATE MATERIALIZED VIEW t_mv (a UInt64, b String)
    ENGINE = Distributed(test_shard_localhost, currentDatabase(), t_local)
    DEFINER = mv_definer SQL SECURITY DEFINER
    AS SELECT a, b FROM t_local;

-- Crashes the server (SIGSEGV, null planner-context deref in
-- buildQueryTreeDistributed) on a build without #107653:
SELECT count(), sum(a) FROM t_mv SETTINGS enable_analyzer = 0;

Bisect

  • The reproducer requires enable_analyzer, introduced in v24.8 — so this is not pre-existing: it was introduced no earlier than v24.8, and the introducing change is in the 24.8–master range (most likely the change that added the feature). Every release line down to there reproduces.

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.5, 26.4, 26.3, 26.2, 26.1
  • Does NOT reproduce on: master
  • Backport needed: 26.5, 26.4, 26.3, 26.2, 26.1

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-materialized-view
Severity: P2


ClickGap · Finding: phase_d_pr107653

Triage metadata

  • Primary component: comp-materialized-view
  • Secondary components: comp-testing
  • Component owners (comp-materialized-view): @CheSema @al13n321

pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Sep 24, 2026
… 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]>
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 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.

5 participants