Skip to content

Fix the crash of merge, loop and executable reading a materialized view's source table on INSERT - #129338

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:mv-source-nested-read-view-source
Nov 5, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:mv-source-nested-read-view-source

Conversation

@groeneai

@groeneai groeneai commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125023
Related: #123514
Related: #125990

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 into the source table of a materialized view whose query reads that table again through merge (with a Distributed table among its tables), loop or executable, including the APPEND refresh of a refreshable materialized view into that table. Closes #125023.

Description

On v26.10.2.103-stable, v26.9.25.15-stable and v26.8.34.13-lts, this INSERT segfaults:

CREATE MATERIALIZED VIEW mv TO dst AS
    SELECT (SELECT max(x) FROM (SELECT x FROM loop(db, src) WHERE x > 0 LIMIT 25)) AS value FROM src;
INSERT INTO src VALUES (1); -- SIGSEGV in KeyCondition

executable crashes the same way; on master, so does merge with a Distributed table among its tables, also on the APPEND refresh of a refreshable view.

CI: Stress test (arm_debug) on 26.8 (STID 1288-3bd5), Stress test (amd_msan) (STID 2395-4d91).

Root cause. Since #123514, tryResolveTableIdentifier types the source table by the view source's key-less metadata and relies on replaceStorageInQueryTree, run only by an interpreter given the view source as storage, to swap it in. The nested interpreters of merge (with a Distributed sibling), loop and executable are not given it, so the catalog MergeTree is planned without its primary key.

Change. The nested interpreters of loop, executable and merge get isViewInnerQuery() ? nullptr : getViewSource() as storage, as in interpretSubquery, so loop and executable read the inserted block, as v26.8.18.2 did. A merge child that is the source table clears the view source instead, like the local shard in DistributedCreateLocalPlan, so it reads the table whatever its siblings are, as at FetchColumns, and so do subqueries in its own query; other children's row-policy and IN subqueries keep reading the block.

As on v26.8.18.2, a scalar subquery over loop or executable keeps the first block's value for the whole INSERT. A Buffer over a Distributed table read with x IN src still crashes; #125990, on top of this PR, covers it.

Validation. New test, one arm per site, a row policy on another merge child, refreshable views appending to and reading src: master crashes on it, reverting any one site crashes its arm, 30/30 randomized.

🤖 Generated with Claude Code


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

Version info

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

… 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).
The same holds for the `APPEND` refresh of a refreshable view into the source table.

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

groeneai commented Nov 4, 2026

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.

# Sev Finding Verdict Evidence / action
1 💡 Use Critical Bug Fix and a present-tense entry DISAGREE Bug Fix fits: released 26.8/26.9/26.10 segfault on a documented INSERT; Critical Bug Fix is left to maintainers. CHANGELOG.md uses Fixed ... in most entries

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

Session id: cron:clickhouse-review-slot-9:20261104-165700

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test crashes a master server (4f752f7) with SIGSEGV in KeyCondition on every run, and clickhouse local of master, v26.10.2.103, v26.9.25.15 and v26.8.34.13 exits 139.
b Root cause explained? Since #123514 the resolver types the source table by the view source's key-less metadata and relies on replaceStorageInQueryTree, which runs only in an interpreter given the view source as storage. The nested interpreters of merge, loop and executable were not, so the catalog MergeTree was planned without its primary key.
c Fix matches root cause? Yes. The three nested interpreters get the view source as storage, the idiom interpretSubquery and ExecuteScalarSubqueriesVisitor already use. No guard at the crash site.
d Test intent preserved / new tests added? New test 05507_mv_source_merge_loop_executable_crash: one arm per site, a refreshable view appending to the source table (crashes master on its own) and a refreshable view reading it.
e Both directions demonstrated? Master crashes, the fix passes; reverting any one site crashes only its own arm; a corrupted reference row fails the fixed build.
f Fix is general across code paths? A Buffer over Distributed read with x IN src still crashes (its replan uses its own block); #125990 covers it.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type-independent (storage choice). Checked: INSERT and refresh pushes, Atomic and Replicated databases, parallel replicas with both local-plan values, 50/50 randomized settings.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. The three reads return the inserted block as v26.8.18.2 did (same rows); outside a materialized view the storage is null, as before.
i Invariants and contracts preserved? View inner queries get nullptr, matching the resolver's own condition, so metadata and storage substitution agree. The context is unchanged: row-policy subqueries of a Merge child (05321) and the Distributed local shard (05294) keep their behavior.

Session id: cron:clickhouse-impl-slot-40:20261104-155800

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim, could you review this and add the can be tested label so CI runs? It is the small crash-only part of #125990: the nested interpreters of merge, loop and executable now get the view source as storage, so they read the inserted block instead of planning the source MergeTree with the key-less view-source metadata.

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d7987d7]

Summary: ✅


AI Review

Summary

The PR fixes null primary-key dereferences when nested merge, loop, and executable reads encounter a materialized view's source table. The revised merge path reads the source table while preserving inserted-block substitution for other children's subqueries. No new actionable findings. I withdraw the earlier scalar-cache finding as a regression finding: inspection of v26.8.18.2-lts confirms the same block substitution and cache-dependency limitation already existed. This does not claim that caching issue is fixed.

Missing context / blind spots
  • ⚠️ Validation of head d7987d7cbf8c5717e7f5b7859db0105aa9d0d85e is still pending, and no local build is available. The regression test passed 50/50 targeted ASan/UBSan runs on the preceding revision, c3f86b298b5e8567a886344a213d108877ee286e; the latest-head run should confirm the revised merge results and added row-policy case.
Final Verdict

Status: ✅ Approve for the scoped crash fix. No code changes requested; latest-head CI remains pending.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 4, 2026
@PedroTadim PedroTadim self-assigned this Nov 4, 2026
@PedroTadim PedroTadim added pr-must-backport Pull request should be backported intentionally. Use this label with great care! can be tested Allows running workflows for external contributors labels Nov 4, 2026
@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai

The loop and executable changes look right to me. They always plan their query in a nested interpreter, so passing the view source the way interpretSubquery does gives them the inserted block, which is what the description says v26.8.18.2 returned.

merge is different, because whether a child reaches the nested interpreter depends on the other tables. With this PR, the same view reads either the block or the table, depending on which other tables the regexp matches. On a master build (10746f6), with src holding 100..109 and INSERT INTO src VALUES (1), (2), (3):

view query value
(SELECT sum(x) FROM db.src) 6 (block)
(SELECT sum(x) FROM merge(db, '^src$')) 1051 (table)
(SELECT sum(x) FROM merge(db, '^(src|dist_target)$')), dist_target a MergeTree 1051 (table)
(SELECT sum(x) FROM merge(db, '^(src|dist)$')), dist a Distributed crashes; 6 (block) with this PR, as in the test's merge arm

Children planned at FetchColumns read the catalog storage. The nested interpreter in createPlanForTable runs only when a sibling such as Distributed raises the stage. So adding a Distributed table to the regexp changes what src returns, from the table to just the inserted rows.

DistributedCreateLocalPlan already calls clearViewSource() so that the local shard "reads the table itself, like the remote shards do". Doing the same in the merge branch should also avoid the crash, since the resolver would then type src by its own metadata, which has the key. Then src would read the table whatever its siblings are. Could the merge arm do that, or is there a reason it should read the block only when the stage is raised? Either way, please state the chosen behavior in the description, which currently says all three reads return the inserted block.

InterpreterSelectQueryAnalyzer interpreter(select_ast, context, options, column_names);
/// The analyzer substitutes the inserted block of a materialized view for its source table only when given it.
InterpreterSelectQueryAnalyzer interpreter(
select_ast, context, options, context->isViewInnerQuery() ? nullptr : context->getViewSource(), column_names);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ [P1] Keep these block-dependent reads out of the query-global scalar cache

Passing the view source makes the nested read depend on the current inserted block, but subtreeHasViewSource in evaluateScalarSubqueryIfNeeded.cpp recognizes only direct TableNode references. A scalar over loop, merge, or executable hides that dependency behind the table function, so can_use_global_scalars stays true and subsequent blocks reuse the first block's answer.

Reproduced with this commit's CI binary: a view selecting x AS inserted and (SELECT max(x) FROM (SELECT x FROM loop(db, src) WHERE x > 0 LIMIT 2)) AS seen, followed by INSERT INTO src SELECT number + 1 FROM numbers(3) SETTINGS max_threads=1, max_block_size=1, min_insert_block_size_rows=0, min_insert_block_size_bytes=0, min_insert_block_size_rows_for_materialized_views=0, min_insert_block_size_bytes_for_materialized_views=0, stores (1,1), (2,1), (3,1) instead of (1,1), (2,2), (3,3). The merge and executable scalar subqueries from the added test have the same failure; a direct source-table scalar returns the correct values.

Please propagate the block dependency to the scalar-cache decision, or otherwise prevent these results from being shared across inserted blocks, and add multi-block regression coverage for all three paths.

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.

@groeneai you should fix this in a followup PR

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acknowledged. I'll open a follow-up PR that keeps these reads out of the query-wide scalar cache, with multi-block tests for loop, merge and executable, and post its link here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The follow-up is #129497. Could you add the can be tested label there so its CI runs?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: I closed #129497. Its change is now part of #125610 (2050065), where a maintainer asked for the same loop fix and which already carried the rest of it.

@clickhouse-gh clickhouse-gh Bot added the comp-materialized-view Materialized views: insert-triggered MV pipeline, insert dependencies, deduplication. label Nov 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d7987d7cb with master 6e1a5e4e1 (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

6 object files changed (+60.05 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageExecutable.cpp.o 413.70 KiB 435.26 KiB +21.57 KiB (+5.21%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromLoopStep.cpp.o 168.12 KiB 189.26 KiB +21.14 KiB (+12.57%)
src/CMakeFiles/dbms.dir/Storages/StorageMerge.cpp.o 1.36 MiB 1.37 MiB +17.35 KiB (+1.25%)

719 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.

Compile time of recompiled translation units

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

Job report

…w source

A `Merge` child is planned by a nested interpreter only when a sibling such as
`Distributed` raises the stage above `FetchColumns`. Passing the view source to it made
the source table read the inserted block there and the table at `FetchColumns`, so the
same view read different data depending on which other tables the regexp matched.

When the child is the source table itself, clear the view source instead, as
`DistributedCreateLocalPlan` does for the local shard: the resolver then types the child
by its own metadata, which has the primary key, and the child reads the table, as do
subqueries in its own query. Other children keep the view source, so their row-policy
and `IN` subqueries keep reading the inserted block, as they do at `FetchColumns`;
clearing it for every child made a row policy reading the source table (the 05321 shape
with a `Distributed` sibling) read the table instead. `loop` and `executable` keep
reading the inserted block.

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

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks. Changed in d7987d7:

  • A merge child that is the source table now clears the view source, as DistributedCreateLocalPlan does, so it reads the table whatever its siblings are. Your last row gives 1051 now, and the test's merge arm reads the table.
  • I did not clear it for the other children. At FetchColumns their row-policy and IN subqueries read the block, and clearing it made them read the table once a Distributed sibling is present: the 05321 row-policy shape gave 0 0 instead of 2 5, and x IN (SELECT x FROM src) over another child gave 106 instead of 6. The test has an arm for the row policy now.
  • One difference remains: a subquery inside the source child's own query reads the table too. merge(db, '^(src|dist)$') WHERE x NOT IN (SELECT x FROM src) gives 0, while merge(db, '^src$') gives 1045. The previous head also gave 0. Matching it needs the resolver to type the child and its subqueries differently, so I kept it out of this PR.
  • The bot's scalar-cache finding: for loop and executable, v26.8.18.2 stores the same (1,1), (2,1), (3,1), so it predates Fix mv source engine checks #123514 and is not part of this crash fix. For merge it no longer applies, since that read is the table now.

The description now states this behavior.

@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai

Thanks, d7987d7 addresses my point: the source child of merge now reads the table whatever its siblings are, and the description says so.

One nit in ReadFromMerge::createPlanForTable: the source-table check compares getFullNameNotQuoted strings. Those collide for dotted names, e.g. database a.b with table c against database a with table b.c. StorageID::operator== compares UUIDs when both IDs have one, so view_source->getStorageID() == storage->getStorageID() would avoid that. subtreeHasViewSource in evaluateScalarSubqueryIfNeeded.cpp uses the same string comparison, so it is consistent with existing code; feel free to leave it if you prefer to keep both alike.

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks. I measured it and would keep the string comparison here, because the resolver (tryResolveTableIdentifier) and replaceStorageInQueryTree identify the view source by the same getFullNameNotQuoted string. With StorageID::operator== only in createPlanForTable, a colliding child is no longer cleared, so the nested resolver types it by the view source and replaceStorageInQueryTree swaps the inserted block in.

Source `p29`.`b.c` holding 1000..1004, another table `p29.b`.`c` holding 100..109, INSERT INTO `p29`.`b.c` VALUES (1), (2), (3):

view query master (39b9f2d) d7987d7 operator== in createPlanForTable
(SELECT sum(x) FROM merge('p29.b', '^(c|dist)$')), dist a Distributed crashes 1045 (table) 6 (inserted block of `p29`.`b.c`)
(SELECT sum(x) FROM `p29.b`.`c`) 6 6 6
(SELECT sum(x) FROM (SELECT x FROM loop('p29.b', 'c') LIMIT 10)) crashes 19 (block) 19 (block)

The second row shows the collision already exists on master for a direct reference, and the loop row shows this PR's loop change inherits it, since it passes the view source for any table. So it belongs to the identity check as a whole: switching to StorageID::operator== means changing the resolver, replaceStorageInQueryTree, subtreeHasViewSource, the two checks in FunctionToSubcolumnsPass and this one together. I would keep that out of this PR; I can send it as a separate one if you want it.

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 5, 2026
@PedroTadim PedroTadim added v26.8-must-backport and removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Nov 5, 2026
Merged via the queue into ClickHouse:master with commit 4d3a2ee Nov 5, 2026
185 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 5, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 5, 2026
PedroTadim added a commit that referenced this pull request Nov 5, 2026
Cherry pick #129338 to 26.9: Fix the crash of `merge`, `loop` and `executable` reading a materialized view's source table on INSERT
PedroTadim added a commit that referenced this pull request Nov 5, 2026
Cherry pick #129338 to 26.8: Fix the crash of `merge`, `loop` and `executable` reading a materialized view's source table on INSERT
robot-clickhouse added a commit that referenced this pull request Nov 5, 2026
…table` reading a materialized view's source table on INSERT
robot-clickhouse added a commit that referenced this pull request Nov 5, 2026
…table` reading a materialized view's source table on INSERT
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 5, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 5, 2026
Backport #129338 to 26.10: Fix the crash of `merge`, `loop` and `executable` reading a materialized view's source table on INSERT
clickhouse-gh Bot added a commit that referenced this pull request Nov 5, 2026
Backport #129338 to 26.8: Fix the crash of `merge`, `loop` and `executable` reading a materialized view's source table on INSERT
clickhouse-gh Bot added a commit that referenced this pull request Nov 5, 2026
Backport #129338 to 26.9: Fix the crash of `merge`, `loop` and `executable` reading a materialized view's source table on INSERT
antonio2368 added a commit that referenced this pull request Nov 6, 2026
…ough `merge` with a `Distributed` table"

This reverts commit 9696a8c, which came from
#129493. Its rule gave the metadata
of the inserted block only to analyses that swap it in, but nested analyses
that swap in subqueries got the catalog types:
#122603 (comment)
The crash is fixed in master by #129338.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 6, 2026
After ClickHouse#129338, a `merge` child that is the materialized view's source table and is
planned by the nested interpreter (a `Distributed` sibling raises the stage) cleared
the view source, so the IN subqueries of the view query pushed into that child read
the table, while at `FetchColumns` they read the inserted block. With the analyzer
typing the source table by the view source only when given it as storage, passing
no storage is enough for the child to read the table, and the view source stays for
the subqueries (`view_source_in_subqueries`). `merge(db, '^(src|dist)$') WHERE x NOT IN
(SELECT ... FROM src)` now gives the same rows as `merge(db, '^src$')`.

The `clearViewSource` in `createChildrenPlans` is dropped: `loop` and `executable` now
get the view source as storage, so no analysis that reads a `Merge` table carries the
view source without `view_source_in_subqueries`.

The test keeps only the shapes that differ from master: the `Buffer` over `Distributed`
crash (a table on the right of NOT IN, a JOIN) and the `merge` source child, each also
through a refreshable view appending to the source table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…table` reading a materialized view's source table on INSERT
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…table` reading a materialized view's source table on INSERT
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…utable` reading a materialized view's source table on INSERT
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 18, 2026
…w source

Since ClickHouse#129338, `loop(db, src)` inside a materialized view of `src` reads the
inserted block, but `StorageLoop::mayReadViewSource` only forwarded to the inner
table, so a scalar subquery over it went to the query-wide scalar cache and every
later block got the first block's value. This was the first case of the AI review
thread on `ReadFromLoopStep.cpp`; the PR dropped it in 4a1429d when the crash
fix was split out, and ClickHouse#129497 later picked it up. Count the inner table being the
view source, as ClickHouse#129497 does, and carry its test (without the `loop` table arms:
master no longer allows `CREATE TABLE ... AS loop(...)`).

The scalar form now equals the CROSS JOIN form, `(1,1),(2,2),(3,3)`, where the
head CI binary (5e36832) gave `(1,1),(2,1),(3,1)`.

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-materialized-view Materialized views: insert-triggered MV pipeline, insert dependencies, deduplication. 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.

Nested loop/executable reads of MV source never swapped: SIGSEGV on INSERT

4 participants