Repository navigation
Fix a crash when a materialized view reads its source table through a Buffer over a Distributed table - #125990
Conversation
… 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]>
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).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261015-093900 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20261015-091700 |
|
cc @alexey-milovidov, could you review this and add |
|
Workflow [PR], commit [ee5895e] Summary: ✅
AI ReviewSummaryThe PR fixes invalid source-table metadata during materialized-view query replanning and preserves inserted-block reads in Final VerdictStatus: ✅ Approve |
|
@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:
|
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]>
|
Both points are addressed in 2aaf5ae.
So the three reads get their pre-#122345 answer back. An IN subquery that 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. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes124 object files changed (-17.67 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units618 translation units recompiled, 5290 s compile time in total, 618 of them have a recent master baseline. |
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]>
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]>
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]>
|
#125610 is reworked for this design: it no longer contains this PR's crash fix (only the identical |
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]>
…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]>
|
Yes, sorry for the delay. I went through every 1. A missed hop cannot bring the crash back. The key-less types are taken only when Re-plans of the view query that get the flag:
Without it, reading the table on purpose: the local shard of 2. Yes, those sites are deliberate; none decides what a subquery reads:
|
… `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]>
… `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]>
… `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]>
Cherry pick #125990 to 26.8: Fix a crash when a materialized view reads its source table through a `Buffer` over a `Distributed` table
Cherry pick #125990 to 26.9: Fix a crash when a materialized view reads its source table through a `Buffer` over a `Distributed` table
Cherry pick #125990 to 26.10: Fix a crash when a materialized view reads its source table through a `Buffer` over a `Distributed` table
…its source table through a `Buffer` over a `Distributed` table
…its source table through a `Buffer` over a `Distributed` table
… its source table through a `Buffer` over a `Distributed` table
Backport #125990 to 26.10: Fix a crash when a materialized view reads its source table through a `Buffer` over a `Distributed` table
… its source table through a `Buffer` over a `Distributed` table
…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]>
Related: #129338
Related: #123514
Closes: #130103
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a crash on
INSERTwhen a materialized view reads its source table on the right ofINor in aJOINover aBufferof aDistributedtable. The IN subqueries of the view query now also read the inserted block when amergetable with aDistributedchild plans the query again for the source table.Description
On 26.8.34.13 and 26.10.2.103, this
INSERTcrashes the server (SIGSEGV inKeyCondition), also when a refreshable view appends tosrc:Same crash family as STID 1288-3bd5 and STID 2395-4d91, which #129338 fixed at
merge,loopandexecutable.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
BufferoverDistributedplans 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_subqueriesdecides whether IN, scalar and filter subqueries read the inserted block: set by the interpreter given the view source and passed on to theMergechild andBufferplans. Amergesource child then reads the table while the view query's IN subqueries keep the block, as without aDistributedchild; rows read throughDistributedare 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 (
Bufferwith NOT IN and JOIN,mergesource child, also with flushed rows and an inlined view; INSERT and refreshable views): master crashes; removing the resolver check, theMergeor theBufferoption fails it; 30/30 randomized, 10/10 in aReplicateddatabase.Workflow [PR]
Sync PR [sync-upstream/pr/125990]
Version info
26.11.1.2067-master(included in26.11and later)