Skip to content

Fix a crash when a materialized view reads its source table through a Buffer over a Distributed table - #125990

Merged
PedroTadim merged 23 commits into
ClickHouse:masterfrom
groeneai:mv-source-merge-loop-executable-crash
Nov 12, 2026
Merged

PedroTadim merged 23 commits into
ClickHouse:masterfrom
groeneai:mv-source-merge-loop-executable-crash

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129338
Related: #123514
Closes: #130103

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 crash on INSERT when a materialized view reads its source table on the right of IN or in a JOIN over a Buffer of a Distributed table. The IN subqueries of the view query now also read the inserted block when a merge table with a Distributed child plans the query again for the source table.

Description

On 26.8.34.13 and 26.10.2.103, this INSERT crashes the server (SIGSEGV in KeyCondition), also when a refreshable view appends to src:

CREATE TABLE buf AS dist_target ENGINE = Buffer(db, dist, ...);  -- dist: Distributed over dist_target
CREATE MATERIALIZED VIEW mv TO dst AS
    SELECT (SELECT count() FROM buf WHERE x NOT IN src) AS value FROM src;
INSERT INTO src VALUES (1);

Same crash family as STID 1288-3bd5 and STID 2395-4d91, which #129338 fixed at merge, loop and executable.

Root cause. Since #123514 the resolver types the source table by the view source's key-less metadata in every analysis of the push, but only an interpreter given the view source as storage swaps it in. A Buffer over Distributed plans the query again for its blocks with its own storage, so a source table there is planned without its primary key.

Change. The resolver takes the view source's types only in the analysis that swaps it in (replaced_storage, #122603). SelectQueryOptions::view_source_in_subqueries decides whether IN, scalar and filter subqueries read the inserted block: set by the interpreter given the view source and passed on to the Merge child and Buffer plans. A merge source child then reads the table while the view query's IN subqueries keep the block, as without a Distributed child; rows read through Distributed are checked on the shard, against the table. The IN rewrite now also replaces a bare table on the right of IN. An inlined view (analyzer_inline_views = 1) keeps its boundary through these replans and reads the table.

Validation. New test (Buffer with NOT IN and JOIN, merge source child, also with flushed rows and an inlined view; INSERT and refreshable views): master crashes; removing the resolver check, the Merge or the Buffer option fails it; 30/30 randomized, 10/10 in a Replicated database.


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

Version info

  • Merged into: 26.11.1.2067-master (included in 26.11 and later)

groeneai and others added 2 commits October 15, 2026 09:18
… and `executable` under a materialized view

Inside a materialized view query, `tryResolveTableIdentifier` (ClickHouse#123514) types every
reference to the view source table by the view source metadata (`StorageValues`, no
primary key) while keeping the catalog storage, and relies on `replaceStorageInQueryTree`
to swap the view source in after the passes. That swap only happens for an interpreter
given the view source as its storage. Three reads re-analyze an AST under a copy of the
push context without one: a `Merge` child planned by a nested interpreter (a `Distributed`
sibling raises the read above `FetchColumns`), the inner query of `loop`, and the input
queries of `executable`. The catalog `MergeTree` was then planned with key-less metadata
and `KeyCondition` dereferenced a null primary key expression (SIGSEGV, STID 1288-3bd5).

Pass the view source as the interpreter's storage at these three sites, as
`interpretSubquery` and `ExecuteScalarSubqueriesVisitor` already do. The nested
re-analysis reads the inserted block again, as before ClickHouse#123514 and as the old interpreter
did. The context is unchanged, so row-policy subqueries of a `Merge` child keep reading
the inserted block (05321), the local shard of a `Distributed` read keeps reading the
table (05294) and ordinary view inner queries are unaffected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`LocalConnection` sends accumulated progress to the client from its interactive cancel
callback, so the progress bar moves during query analysis. The callback also runs on pipeline
threads: during an `INSERT`, a materialized view analyzes its query on a pipeline thread, and a
scalar subquery there polls the callback. `ClientBase::onProgress` then ran concurrently with
the main thread, which forwards progress from the `CompletedPipelineExecutor` callback (TSan:
data race on `processed_rows_from_progress`, found by `05389_mv_source_merge_loop_executable_crash`).
Progress is now forwarded only on the client's thread; progress collected on another thread
stays in the query state and is sent by the main thread on its next poll.

The same callback sets `is_cancelled` when the query is interrupted, which the main thread
reads from the `CompletedPipelineExecutor` callback (TSan: data race on Ctrl+C during such a
scalar subquery). The flag is now atomic.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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; 1 finding) plus my own review (1 nit).

# Sev Finding Verdict Evidence / action
1 ⚠️ No test cancels the query, so reverting is_cancelled to bool keeps the new test green DISAGREE A TSan reproducer (SIGINT while a view's scalar subquery runs in clickhouse-local) raced 3/3 without the atomic (write in the interactive cancel callback vs read in the executor callback on the main thread) and 0/6 with it. A permanent test would depend on signal timing. The PR description now says the new test reaches the progress race only.
2 💡 The isViewInnerQuery() ? nullptr : getViewSource() idiom now appears at five sites AGREE, noted Kept inline so the hunks stay identical to #125610, which is stacked on this PR.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261015-093900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05389_mv_source_merge_loop_executable_crash with --no-random-settings crashes a master debug server (merge, loop) and clickhouse-local (executable) on every run; v26.8.27.9-lts and v26.9.19.9-stable crash on all three arms.
b Root cause explained? Yes. Since #123514 a source-table reference in a view query is typed by the view source's key-less metadata and needs the interpreter's storage swap; the nested interpreters of a Merge child, loop and executable input queries run without the view source as storage, so KeyCondition gets a null primary key expression.
c Fix matches root cause? Yes. The three sites now pass the view source as storage, like interpretSubquery and ExecuteScalarSubqueriesVisitor; no guard at the crash site.
d Test intent preserved / new tests added? Yes. New test with one arm per site; each arm alone crashes master at its own site.
e Both directions demonstrated? Yes. Master crashes, the fix passes (output = reference), 50/50 randomized runs pass.
f Fix is general across code paths? Yes. The other re-analysis sites under a push context already pass the view source; view inner queries (incl. obfuscate) read the table and do not crash; the local shard of Distributed keeps reading the table by design.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The defect is table resolution, so column type wrappers do not apply; covered merge() (same path as the Merge engine), loop, executable, randomized settings, and MV contract tests for Distributed, row policies, ordinary views, scalar and IN subqueries.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; the three sites read the inserted block again, as before #123514.
i Invariants and contracts preserved? Yes. Only table nodes named as the view source are swapped and the context is unchanged; progress collected on other threads stays queued for the client thread's next poll, and is_cancelled is atomic.

Session id: cron:clickhouse-impl-slot-6:20261015-091700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov, could you review this and add can be tested? It is the crash-fix part of #125610, split out to make it small: the nested interpreters of merge, loop and executable now get the materialized view source as storage, so the source MergeTree is planned with its primary key.

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ee5895e]

Summary: ✅


AI Review

Summary

The PR fixes invalid source-table metadata during materialized-view query replanning and preserves inserted-block reads in IN, scalar, and filter subqueries across Merge and Buffer plans. Review of ee5895eae46572431e916cb27de61ad4db74c95f found no new actionable issues; prior findings are addressed. The new regression test, existing 05507 coverage, and 20 additional ordinary-view boundary probes passed using the PR head's CI binary.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 15, 2026
@PedroTadim PedroTadim self-assigned this Oct 15, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-materialized-view Materialized views: insert-triggered MV pipeline, insert dependencies, deduplication. label Oct 15, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Oct 15, 2026
Comment thread src/Client/LocalConnection.h Resolved
@PedroTadim

PedroTadim commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

@groeneai 🕵️

The fix works for these three sites; I reproduced the merge crash on master (SIGSEGV in KeyCondition from ReadFromMergeTree::buildIndexes). Two things about the wider picture:

  1. The crash comes from the two halves of Fix mv source engine checks #123514 coming apart. IdentifierResolver gives the source table the view source's key-less metadata for every interpreter whose context has a view source, but only an interpreter given that view source as its storage swaps the block in. There are about 40 other InterpreterSelectQueryAnalyzer constructions without a storage, so any of them that re-analyzes the source table can still crash this way, and each would need its own patch like these three. Could it be fixed once instead? Either let IdentifierResolver substitute the metadata only when the interpreter will also substitute the storage, or let the InterpreterSelectQueryAnalyzer constructor default its storage to context->getViewSource() when !context->isViewInnerQuery().

  2. Which data is the source table supposed to be when it's reached indirectly? On master, the same view built with remote('127.0.0.1', db, src), a Distributed table over src (local shard) or view(SELECT x FROM db.src) doesn't crash, but it reads the whole table: after three inserts of (1), (2), (3) into a table holding 100..109, it wrote 1051, 1057 and 1063. With this PR, merge, loop and executable read only the inserted block, like a plain subquery does. If the block is the intended answer everywhere, the second option in (1) would also fix those three paths. If not, it would change them. Could the description say which one is intended?

The analyzer typed the source table of a materialized view by the view source in every analysis
whose context has one (`tryResolveTableIdentifier`), but only an interpreter given the view source
as storage swaps it in after the passes. Any other interpreter that re-analyzes the table under a
copy of the push context planned the catalog `MergeTree` with key-less metadata and crashed in
`KeyCondition`: `merge` with a `Distributed` sibling, `loop`, the input query of `executable`.

`InterpreterSelectQueryAnalyzer` now marks its context with `setViewSourceSubstituted` when it is
given the view source as storage, and `tryResolveTableIdentifier` takes the types from the view
source only under that mark. Other analyses type the table from the catalog and read it, as before
ClickHouse#122345: measured on 26.8.2.7, `merge`, `loop` and `executable` inside a view query read the table,
while an IN or scalar subquery of the view query reads the inserted block even when `merge` pushes
it into its child.

The view source rewrite of an IN subquery now replaces every reference to the source table in it,
not only the leftmost one, so a join inside such a subquery reads the block too when `merge` pushes it
into its child, like it does in the view query itself.

This replaces the per-site storage arguments for `merge`, `loop` and `executable`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both points are addressed in 2aaf5ae.

  1. Fixed once, with your option A: InterpreterSelectQueryAnalyzer marks its context when it is given the view source as storage, and tryResolveTableIdentifier takes the view source's types only in a marked analysis. An interpreter built without the view source now types the table from the catalog, so none of them can crash this way; the three per-site arguments are gone. Option B would not have reached remote/Distributed (createLocalPlan clears the view source) or view() (a view inner query), so merge, loop and executable would have read the block while those read the table.

  2. The table is the intended answer for a read through another engine or table function; only the view query itself, with its IN and scalar subqueries, reads the block. That is what Fix LOGICAL_ERROR on lambda over an Array(Tuple(...)) #122345 settled for the local shard ("like the remote shards do", 1906c4f), and merge without a Distributed sibling already reads the table on master. Your shape, max(x) after inserting (1), (2), (3) into a table holding 100..109 (3 = block, 109 = table):

read in the view query 26.8.2.7 (before #122345) 26.8.16.41 this PR
src directly 3 3 3
merge, plain / with Distributed 109 / 109 109 / 3 109 / 109
loop 109 3 109
executable 109 3 109
remote, Distributed, view 109 109 109

So the three reads get their pre-#122345 answer back. An IN subquery that merge pushes into its child still reads the block, as in the view query. The IN rewrite now replaces every source reference in it, not only the leftmost one, so this also holds through a join (new test arm). The description now says this.

This changes the premise of #125610 (its scalar-cache part assumes these reads see the block). I'll rework it on top of this one.

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ee5895eae with master 31dd125f5 (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Object file sizes

124 object files changed (-17.67 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Resolve/resolveFunction.cpp.o 1.06 MiB 1.03 MiB -23.39 KiB (-2.16%)
src/CMakeFiles/dbms.dir/Analyzer/QueryNode.cpp.o 250.38 KiB 271.33 KiB +20.95 KiB (+8.37%)
src/CMakeFiles/dbms.dir/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp.o 283.72 KiB 264.42 KiB -19.30 KiB (-6.80%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse-keeper ×1.05 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.9 s 17.3 s +9.8 s (+130%)
Compile time of recompiled translation units

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

Job report

The view source substitution of IN and scalar subqueries ran in every analysis under the push
context, so in the input query of `executable` the table read returned the table while an IN or
scalar subquery over the same table returned the inserted block. They now substitute only where
the view query is analyzed (`isViewSourceInSubqueries`): the interpreter given the view source,
and the replan of its query for a `Merge` child, so an IN pushed into the child still reads the
block. A read through `Buffer` over `Distributed` now reads the table in both its parts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e child

`x IN db.src` takes the `TableNode` branch of the IN rewrite, which did not
substitute the view source. In the view query the final
`replaceStorageInQueryTree` swaps it anyway, but when `merge` with a
`Distributed` sibling plans the query again for a child, the substitution is
lost in the AST and the child read the table for the set: `x IN db.src`
counted the stored rows while `x IN (SELECT x FROM db.src)` used the inserted
block (also `GLOBAL IN` and `NOT IN`). Substitute before the branches, so both
spellings agree. The input query of `executable` still reads the table for
both forms.

The test gets a `NOT IN` arm in the `merge` child replan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 16, 2026
ClickHouse#125990 fixes the crash in `InterpreterSelectQueryAnalyzer` instead of at these three sites, and `merge`, `loop` and `executable` read the source table there instead of the inserted block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 16, 2026
With ClickHouse#125990, a read of the source table through `merge`, `loop` or `executable` reads the table, so it does not make a scalar subquery depend on the inserted block. What still does is a row policy or `additional_table_filters` entry with a subquery of a table that a `Merge` (directly or through `Alias`, `Buffer`, a materialized view, a table function table, `loop` or `executable`) reads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

#125610 is reworked for this design: it no longer contains this PR's crash fix (only the identical clickhouse-local race fix, so the two merge in either order) and keeps only the per-block evaluation of a scalar subquery over a table whose row policy or additional_table_filters has a subquery.

A refreshable view appending to the source table pushes its block to the
views on it like an INSERT; on master that crashed the server in the
refresh thread (`RefreshTask::executeRefreshUnlocked` ->
`ExecutingInnerQueryFromViewTransform` -> `KeyCondition`) for `merge`
with a `Distributed` sibling, `loop` and `executable`. A refreshable view
reading the source through these engines has no view source and reads the
table, on master and with this change alike.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… blocks

`StorageBuffer::read` plans the enclosing query again for its blocks when the
destination processes it above `FetchColumns` (a `Distributed` destination).
That replan passes the buffer blocks as storage, so the flag that lets the
view query's IN subqueries read the view source was cleared there, and
`x IN (SELECT x FROM src)` over such a `Buffer` read the stored rows: with
`src` and the buffer holding 100..109, inserting (1), (2), (3) wrote 10 instead
of 0. Keep the flag in that replan, as for a `Merge` child.

Released 26.8.26.12, 26.8.28.14 and 26.9.19.9 crash on the bare form
`x IN src` over such a `Buffer` (SIGSEGV), and fail the subquery form with
`INCORRECT_RESULT_OF_SCALAR_SUBQUERY`; master gives 0 for the subquery form and
crashes on the bare one. Both forms now give 0, while an `executable` input
query over the `Buffer` still reads the table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
AVMusorin pushed a commit to AVMusorin/ClickHouse that referenced this pull request Nov 10, 2026
…nary read

`SourceFromQueryPipeline`, used by `DirectDictionary::read` (a `DIRECT`
dictionary read as a table, or as the source of another dictionary),
called `BlockIO::onFinish` / `onException` while its
`PullingPipelineExecutor` was still alive. Those reset the inner
`QueryPipeline` and release its resources (the source table's share lock
and storage holder), but the executor's `ExecutingGraph` still owned the
processors, so the inner `EmbeddedRocksDBSource` and its live RocksDB
iterator outlived the lock. A `TRUNCATE` waiting for the exclusive lock
then closed the RocksDB database (`DBImpl::Close`), and destroying the
outer pipeline later read the freed `ColumnFamilyData`. The early release
of the storage holder also let an Atomic `DROP TABLE` drop the table under
the live iterator.

Hold the executor in `std::optional` and reset it before `onFinish` /
`onException`, the order `getColumns` / `hasKeys` in the same file,
`ObfuscateSource`, `ReadFromLoopStep` and `StorageAlias` already use, so
the pipeline is the last owner of its processors and `~QueryPipeline`
destroys them before its resources. The `QueryPipeline &` constructor
(caller-owned pipeline) keeps its executor until destruction.

Found by BuzzHouse (arm_asan_ubsan), STID 4594-55ad, on PR ClickHouse#125990.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes, sorry for the delay. I went through every QueryAnalyzer, QueryAnalysisPass, addQueryTreePasses, InterpreterSelectQueryAnalyzer and buildFilterQueryTree site at 91bff3f (line numbers are at that commit).

1. A missed hop cannot bring the crash back. The key-less types are taken only when replaced_storage is the view source (IdentifierResolver.cpp:395). Only two analyses set it, and each swaps right after itself: buildQueryTreeAndRunPasses (InterpreterSelectQueryAnalyzer.cpp:430, swap at :458) and buildFilterQueryTree (Planner/Utils.cpp:739, swap at :747). The two nested analyzers that inherit it (the row policy filter of an inlined view, QueryAnalyzer.cpp:6979, and type inference, resolveFunction.cpp:1529) build subtrees of the parent tree, which the parent's swap covers. An analysis without the flag takes the catalog types and reads the table, so a missed hop would be a wrong-table read, not a crash.

Re-plans of the view query that get the flag:

  • Merge child (StorageMerge.cpp:2066) and Buffer (StorageBuffer.cpp:624), from the planner context;
  • the MV interpreter itself (InsertDependenciesBuilder.cpp:647), loop (ReadFromLoopStep.cpp:73) and executable inputs (StorageExecutable.cpp:204): given the view source as storage, so buildSelectQueryOptions sets it;
  • the automatic parallel replicas rebuild (InterpreterSelectQueryAnalyzer.cpp:268): same options and storage;
  • scalar subqueries (evaluateScalarSubqueryIfNeeded.cpp:213), and sets and subqueries in the planner (Planner.cpp:2319, PlannerJoinTree.cpp:3177) through SelectQueryOptions::subquery(), which copies it;
  • all six buildFilterQueryTree callers (PlannerJoinTree.cpp:2308, 2621, 2654, 2673, 2918, Utils.cpp:759).

Without it, reading the table on purpose: the local shard of Distributed/remote (DistributedCreateLocalPlan.cpp:33 clears the view source, as on remote shards), view bodies (StorageView.cpp:749, inlined at QueryAnalyzer.cpp:6878, the view over Distributed pushdown at PlannerJoinTree.cpp:2480/2570), and a Merge child's own identifiers and ALIAS columns (StorageMerge.cpp:1640/1821/2550). The query tree constructor does not re-analyze, so its callers (buildQueryTreeForShard.cpp:673, ParallelReplicasLocalPlan.cpp:174/259, getHeaderForProcessingStage.cpp:206) keep the parent's swaps. The remaining sites are header-only or formatting analyses, or do not run under a view source (INSERT, EXPLAIN, DESCRIBE, mutations, DDL-time analyses).

2. Yes, those sites are deliberate; none decides what a subquery reads:

  • IdentifierResolver.cpp:314 and isInsertedDataOfTableFunction (Analyzer/Utils.cpp:2124) match the RETURNING source of INSERT INTO FUNCTION, which is not in the catalog; that node is the view source itself, so there is nothing to type or swap.
  • evaluateScalarSubqueryIfNeeded.cpp:74/138 only pick the query-wide or the per-analyzer scalar cache, broadly on purpose: a scalar over the source table stays out of the query-wide cache whichever it reads.
  • FunctionToSubcolumnsPass.cpp:1331/1394 skip the rewrite for the source table by name, since StorageValues has no subcolumns; where the table is read it only skips an optimization.

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 12, 2026
Merged via the queue into ClickHouse:master with commit 7c17f94 Nov 12, 2026
187 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 12, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 12, 2026
PedroTadim added a commit that referenced this pull request Nov 12, 2026
… `Buffer` over a `Distributed` table

Backport of #125990, ported onto this branch by hand. The fix is written on top of the
`replaced_storage` plumbing of #122603 (and #126075 below it), which this branch does not have, so
the port adds only what the fix needs: `replaced_storage` and `view_source_in_subqueries` through
`addQueryTreePasses`, `QueryAnalysisPass`, `QueryAnalyzer` and `IdentifierResolver`. The resolver
types the source table by the view source only in the analysis that swaps it in, as in #125990; the
data snapshot of the table stays as it is on this branch, since the snapshot-without-data change of
#122603 is a performance change and is not part of this fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 12, 2026
… `Buffer` over a `Distributed` table

Backport of #125990, ported onto this branch by hand. The fix is written on top of the
`replaced_storage` plumbing of #122603 (and #126075 below it), which this branch does not have, so
the port adds only what the fix needs: `replaced_storage` and `view_source_in_subqueries` through
`addQueryTreePasses`, `QueryAnalysisPass`, `QueryAnalyzer` and `IdentifierResolver`. The resolver
types the source table by the view source only in the analysis that swaps it in, as in #125990; the
data snapshot of the table stays as it is on this branch, since the snapshot-without-data change of
#122603 is a performance change and is not part of this fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 12, 2026
… `Buffer` over a `Distributed` table

Backport of #125990, ported onto this branch by hand. The fix is written on top of the
`replaced_storage` plumbing of #122603 (and #126075 below it), which this branch does not have, so
the port adds only what the fix needs: `replaced_storage` and `view_source_in_subqueries` through
`addQueryTreePasses`, `QueryAnalysisPass`, `QueryAnalyzer` and `IdentifierResolver`. The resolver
types the source table by the view source only in the analysis that swaps it in, as in #125990; the
data snapshot of the table stays as it is on this branch, since the snapshot-without-data change of
#122603 is a performance change and is not part of this fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 12, 2026
Cherry pick #125990 to 26.8: Fix a crash when a materialized view reads its source table through a `Buffer` over a `Distributed` table
PedroTadim added a commit that referenced this pull request Nov 12, 2026
Cherry pick #125990 to 26.9: Fix a crash when a materialized view reads its source table through a `Buffer` over a `Distributed` table
PedroTadim added a commit that referenced this pull request Nov 12, 2026
Cherry pick #125990 to 26.10: Fix a crash when a materialized view reads its source table through a `Buffer` over a `Distributed` table
robot-clickhouse added a commit that referenced this pull request Nov 12, 2026
…its source table through a `Buffer` over a `Distributed` table
robot-clickhouse added a commit that referenced this pull request Nov 12, 2026
…its source table through a `Buffer` over a `Distributed` table
robot-clickhouse added a commit that referenced this pull request Nov 12, 2026
… its source table through a `Buffer` over a `Distributed` table
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 12, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 12, 2026
Backport #125990 to 26.10: Fix a crash when a materialized view reads its source table through a `Buffer` over a `Distributed` table
leshikus pushed a commit that referenced this pull request Nov 13, 2026
… its source table through a `Buffer` over a `Distributed` table
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 14, 2026
…s Distributed

A `Distributed` destination plans the query it ships: after inlining `ALIAS`
columns, `buildQueryTreeForShard` replaces every constant whose name is longer
than `optimize_const_name_size` (256 by default) with `__getScalar('<hash>')`.
So `SELECT countIf(s = repeat('x', 1000)), count() FROM buf` named the column
`countIf(equals(__table1.s, __getScalar('...')))` on the destination side and
`countIf(equals(__table1.s, _CAST(<value>, 'String')))` on the buffers side, and
the by-name union conversion in `StorageBuffer::read` threw THERE_IS_NO_COLUMN.

The buffers replan, which already mirrors `inlineAliasColumns`, now also mirrors
the scalar rewrite: it is exposed from `buildQueryTreeForShard.cpp` as
`replaceLongConstantsWithScalars` and used by both callers, so the guard and the
threshold stay in one place. The replanned shipped query is analyzed with
`ignoreASTOptimizations`, as `createLocalPlan` analyzes the local shard of the
same query: an initiator names a folded `__getScalar` constant by its value,
a shard by its source expression, and the destination header uses the latter.
The gate, the adopt-only-if-covered fallback and the access exemption are unchanged.

Also merged master to resolve the conflict with ClickHouse#129143 and ClickHouse#125990 in
`StorageBuffer::read` (master's column kinds and `view_source_in_subqueries`
are kept inside the `plan_buffers` lambda).

Co-Authored-By: Claude Opus 5.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 comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

merge under MV: source child's IN subquery reads the table, not the block

6 participants