Skip to content

Fix LOGICAL_ERROR on lambda over an Array(Tuple(...)) - #122345

Merged
Ergus merged 8 commits into
ClickHouse:masterfrom
Ergus:Fix_CI_2055
Oct 1, 2026
Merged

Ergus merged 8 commits into
ClickHouse:masterfrom
Ergus:Fix_CI_2055

Conversation

@Ergus

@Ergus Ergus commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Related: #109747

The query of a materialized view is analyzed per pushed block. The analyzer resolved the source table through the catalog and swapped in the StorageValues holding the block only after the passes, so the tree was typed by the table's current metadata while the data kept the type from the start of the INSERT. An ALTER ... MODIFY COLUMN committed in between made a lambda capture a column of another type.

IdentifierResolver::tryResolveTableIdentifier now resolves the view source directly, so the view query is typed by the block it processes.

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 LOGICAL_ERROR Cannot capture column N because it has incompatible type when a materialized view with a lambda over an Array(Tuple(...)) column receives a block while the source table's column type is being changed by ALTER TABLE ... MODIFY COLUMN.


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

Version info

  • Merged into: 26.10.1.1164-master (included in 26.10 and later)
  • Backported to: 26.9.8.11, 26.8.15.24, 26.7.20.24, 26.3.41.4

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [73e4ef0]

Summary: ✅


AI Review

Summary

This PR fixes the main analyzer bug behind LOGICAL_ERROR during materialized-view inserts by binding the source table to the pushed block earlier, then carving out ordinary-view and local-shard cases that must still read the real table. The direct substitutions look mostly correct now, but one correctness hole remains in the new local-shard path: clearing view_source alone does not isolate the copied context from scalar subqueries that were already cached against the inserted block.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/DistributedCreateLocalPlan.cpp:33] Clearing view_source does not clear inherited scalar-subquery caches, so the initiator-local re-analysis can still reuse a scalar that was already folded against the inserted block. Context::createCopy preserves both scalars and the shared query_context, and evaluateScalarSubqueryIfNeeded starts trusting that global cache again as soon as getViewSource() is null. A remote/Distributed local plan that contains a nested scalar like SELECT (SELECT count() FROM src WHERE ...) ... can therefore still observe the block-local result instead of the table state.
    Suggested fix: either drop or bypass inherited scalar caches when creating the local-plan context, or carry enough provenance so evaluateScalarSubqueryIfNeeded keeps those subqueries on the local-cache path when the parent analysis originally had a view_source.
Final Verdict

Changes requested — the new clearViewSource path still allows stale scalar-subquery results to bleed from the inserted-block analysis into the local-shard re-analysis.

LLVM Coverage Report

Measured on commit 73e4ef0.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 48/51 (94.12%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 25, 2026
@Ergus Ergus changed the title Fix ci 2055 Fix LOGICAL_ERROR on lambda over an Array(Tuple(...)) Sep 25, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 73e4ef033 with master 253f06071 (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

83 object files changed (+91.44 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/InterpreterSelectQueryAnalyzer.cpp.o 217.75 KiB 246.33 KiB +28.59 KiB (+13.13%)
src/CMakeFiles/dbms.dir/Analyzer/Resolve/IdentifierResolver.cpp.o 434.88 KiB 456.82 KiB +21.94 KiB (+5.05%)
src/CMakeFiles/dbms.dir/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp.o 257.30 KiB 276.45 KiB +19.14 KiB (+7.44%)
src/CMakeFiles/dbms.dir/Analyzer/Resolve/resolveFunction.cpp.o 1.02 MiB 1.03 MiB +18.41 KiB (+1.77%)

716 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

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

Job report

@watson-ch

watson-ch Bot commented Sep 26, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2055

Labels added:

  • v26.4-must-backport

These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels.

@alexey-milovidov alexey-milovidov self-assigned this Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
@alexey-milovidov alexey-milovidov added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 26, 2026
@george-larionov
george-larionov removed this pull request from the merge queue due to a manual request Sep 26, 2026
@george-larionov

Copy link
Copy Markdown
Member

I think there is a problem with this fix, it is too general and affects regular views as well, which then only see the currently pushed block. See the following pastila: https://pastila.clickhouse.com/?0565bd58/f5725cb24012675a170ff5a8d5c59081#MDg0dc6STAU7lDH0pmlsQQ==GCM

@george-larionov george-larionov 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.

See my comment above. Also I'm not sure the test is very robust, since it relies on timing, but this test could be running slowly on a sanitizer run, claude has a proposal to fix it:

Fix: poll until SELECT count() FROM dst is at least 1 before running the ALTER, which guarantees the INSERT started with the old type. Also add enough blocks to leave margin after the ALTER, e.g. more rows or a longer sleepEachRow. Also
check that the test fails on master; there is no evidence of that in the PR.

Address review: resolving the view source during analysis applied to every
context carrying it, including the inner query of an ordinary `VIEW`
referenced from the materialized view query. Such a view then read only the
inserted block instead of the whole table. Skip the early resolution when
`isViewInnerQuery` is set, which matches how the inner query of a view
resolved the table before.

Add `05291_mv_ordinary_view_over_source_reads_table` for that case, and make
`05241_mv_insert_alter_source_column_during_insert` wait until the first block
has passed through the view before running the `ALTER`, with more blocks left
after it, so it does not depend on timing on slow builds. Without the fix the
test fails with `Cannot capture column 3 because it has incompatible type`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @george-larionov, thanks, both points were right. Fixed in 88420bb.

Regular views. Reproduced: with an ordinary VIEW v AS SELECT x FROM src used inside the materialized view query (as a scalar subquery or a CROSS JOIN), v saw only the pushed block. The early resolution in IdentifierResolver::tryResolveTableIdentifier is now skipped when context->isViewInnerQuery() is set, i.e. inside the inner query of a StorageView. That is the same scope as before this PR: the materialized view query's own references to the source (FROM, JOINs, IN and scalar subqueries) read the block, and ordinary views read the table. The new test 05291_mv_ordinary_view_over_source_reads_table covers this. It fails with the previous version of this PR and passes on master and with the fix.

Test robustness. 05241 no longer relies on a fixed sleep. It polls until the first block has reached dst before running the ALTER, so the INSERT has definitely started with the old type, and it now pushes 30 one-row blocks 0.2 s apart (about 6 s), which leaves plenty of blocks after the ALTER. Checked on a build of the current master without the fix: the test fails with Code: 49. Cannot capture column 3 because it has incompatible type: got Tuple(a UInt32), but Tuple(a UInt32, b Nullable(UInt32)) is expected. With the fix, both tests passed 5/5 locally (RelWithDebInfo), and the local MV test family showed no regressions (the only failures were environmental: missing clusters, Keeper and datasets).

@Ergus

Ergus commented Sep 28, 2026

Copy link
Copy Markdown
Member Author

@george-larionov

I will add a local fix for that, but this consideration makes the test much more complex than the initial quick fix because:

The initial version bound the view source through the Context, which every nested analysis shares, so views and other storages that analyze their own query saw the block too.

The binding must belong to the one analysis that received the storage. But there is not any per-analysis object carrying a storage. What I could do is to threaded through QueryTreePassManager -> QueryAnalysisPass -> QueryAnalyzer.

alexey-milovidov and others added 2 commits September 28, 2026 14:40
The `view_source` rewrites of the right-hand side of `IN`
(`resolveFunction`) and of scalar subqueries
(`evaluateScalarSubqueryIfNeeded`) now skip the inner query of an ordinary
view (`isViewInnerQuery`), like the table resolution in
`IdentifierResolver::tryResolveTableIdentifier`. Otherwise an ordinary
view referenced from a materialized view query saw only the pushed block
in those subqueries instead of the table.

Address review: ClickHouse#122345 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@george-larionov

Copy link
Copy Markdown
Member

What I could do is to threaded through QueryTreePassManager -> QueryAnalysisPass -> QueryAnalyzer.

I think this is the better fix, because currently we are playing whack-a-mole with isViewInnerQuery() and I think we are missing at least one (for a local shard of remote()/Distributed).

The issue is whether the proposed QueryAnalyzer fix can be backported?

…the table

With `analyzer_inline_views = 1`, `QueryAnalyzer::inlineViewSubqueryIfNeeded` resolves the
view body with `StorageView::getViewSubqueryContext`, which did not mark the context as the
inner query of a view, so the body inherited `view_source` and resolved the source table of a
materialized view to the inserted block. Mark that context with `setIsViewInnerQuery`, like
`getViewContext` does for a view that is not inlined.

`replaceStorageInQueryTree` also swapped the storage in every table reference of the join tree,
including those inside an inlined view body. It no longer descends into queries of a view that
is inlined into a query outside of views.

Address review: ClickHouse#122345 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed db55019 for the AI review Major (analyzer_inline_views = 1): StorageView::getViewSubqueryContext now marks the context as view-inner, and replaceStorageInQueryTree no longer descends into an inlined view body (it swapped the storage there after the passes as well). New test 05293_mv_ordinary_view_over_source_inlined.

@george-larionov, I confirmed the local shard case you suspected. On the current head, with a local server on port 19377:

CREATE TABLE src (x UInt64) ENGINE = MergeTree ORDER BY x;
INSERT INTO src SELECT number + 100 FROM numbers(10);
CREATE TABLE dst (block_rows UInt64, r UInt64) ENGINE = MergeTree ORDER BY tuple();
CREATE MATERIALIZED VIEW mv TO dst AS SELECT count() AS block_rows,
    (SELECT count() FROM remote('127.0.0.1:19377', currentDatabase(), src)) AS r FROM src;
INSERT INTO src VALUES (1), (2), (3);
SELECT * FROM dst; -- 3 3, the table has 13 rows

The local replica's plan is analyzed with a copy of the context that carries view_source, so src resolves to the block there too. Before this PR the swap ran only on the view query's own tree, so this read the table. I have not patched this one, because it is exactly the whack-a-mole you describe. Binding the source to the one analysis that receives the storage (QueryTreePassManager -> QueryAnalysisPass -> QueryAnalyzer, as @Ergus proposed) instead of the shared Context fixes every such case at once. Whether that is small enough to backport to 26.4 is for you and @Ergus to decide.

…a materialized view query

`Context::createCopy` preserves `view_source`, so `createLocalPlan` analyzed the local shard of a
`remote` or `Distributed` read inside a materialized view query with the inserted block standing in
for the source table: `(SELECT count() FROM remote('127.0.0.1', db, src))` counted the block, not
the table. Before the early resolution in `IdentifierResolver::tryResolveTableIdentifier`, the swap
was done only on the view query's own tree, so the local shard read the table, like the remote
shards do. Clear the view source in the local shard's context.

New test `05294_mv_source_remote_local_shard_reads_table`: without the fix it prints `0` rows
for both reads, with the fix `10`.

Addresses review: ClickHouse#122345 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Ergus

Ergus commented Sep 29, 2026

Copy link
Copy Markdown
Member Author

I actually agree about the per-analysis binding is better, but it is pretty big (I already have that in a local branch)

  1. The IN rewrite in resolveFunction and the scalar rewrite in evaluateScalarSubqueryIfNeeded are both context-based will have to move with it.
  2. An inlined view body (analyzer_inline_views) resolves inside the same analysis, so it still needs the view-inner check.
  3. In total those are more than 12 files touching the pass-manager and analyzer constructors, which will be hard to backport to all versions up to 26.4.

IMHO this version keeps the invariant simple:

  1. view_source binds only in the materialized view query's own analysis.
  2. Every re-analysis under a derived context is either marked view-inner (StorageView, inlined views) or clears the source (local shard).
  3. clearViewSource in createLocalPlan also fixes the pre-existing IN leak on the local shard and the tests pin each case.

So, What if we merge this for the incident and backport + to do the per-analysis binding as a follow-up on master, where it can replace these guards.

WDYT @george-larionov and @alexey-milovidov ?

@george-larionov

Copy link
Copy Markdown
Member

@Ergus I agree with your plan, let me do a final review of the new changes.

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 1, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 1, 2026
Backport #122345 to 26.9: Fix LOGICAL_ERROR on lambda over an `Array(Tuple(...))`
clickhouse-gh Bot added a commit that referenced this pull request Oct 1, 2026
Backport #122345 to 26.8: Fix LOGICAL_ERROR on lambda over an `Array(Tuple(...))`
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
@Algunenano

Copy link
Copy Markdown
Member

@Ergus Please beware of #123270. This PR is being backported but it introduced a bug

clickhouse-gh Bot added a commit that referenced this pull request Oct 2, 2026
Backport #122345 to 26.7: Fix LOGICAL_ERROR on lambda over an `Array(Tuple(...))`
robot-clickhouse added a commit that referenced this pull request Oct 3, 2026
Cherry pick #122345 to 26.3: Fix LOGICAL_ERROR on lambda over an `Array(Tuple(...))`
robot-clickhouse added a commit that referenced this pull request Oct 3, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 3, 2026
alexey-milovidov added a commit that referenced this pull request Oct 4, 2026
Backport #122345 to 26.3: Fix LOGICAL_ERROR on lambda over an `Array(Tuple(...))`
raimannma added a commit to raimannma/ClickHouse that referenced this pull request Oct 5, 2026
- `ANY INNER JOIN` keeps an arbitrary one of the matching rows, so `t.v` of the
  "ANY join" case differed between runs, and between the runs with and without
  the rewrite. Do not select it; the subquery value is the same for all of them.
- Since ClickHouse#122345, a materialized view
  resolves every reference to its source table, also in a subquery, to the
  inserted block. Update the reference: the results with and without the rewrite
  are still equal.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121848&sha=e46d7ff8b9d57742d8755c72bbbc6c3d0e0b5abc&name_0=PR
PR: ClickHouse#121848

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 9, 2026
alexey-milovidov pushed a commit to fastio/ClickHouse that referenced this pull request Oct 10, 2026
Since ClickHouse#123514, `tryResolveTableIdentifier` resolves every reference to the
source table of a materialized view, outside view inner queries, to the
catalog storage with the view source metadata (columns only, no primary
key), relying on `replaceStorageInQueryTree` to swap the view source in
after the passes. That swap only walked the join trees, so a reference in a
correlated subquery, as the right side of `IN` (`k IN src`), or in a
non-leftmost table of an `IN` subquery was planned as a `MergeTree` read
with that metadata, and `KeyCondition` dereferenced the missing primary key
expression: an INSERT into the source table crashed the server.

When the storage being swapped in is the context's view source, walk the
whole query tree, including subqueries in expressions, still stopping at
view inner queries and table function arguments. These references read the
pushed block again, as with ClickHouse#122345 and the old analyzer. Other callers
(Buffer, header computation) keep the join-tree walk.

Closes ClickHouse#124647

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 15, 2026
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]>
@watson-ch watson-ch Bot added v26.6-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Oct 16, 2026
@watson-ch

watson-ch Bot commented Oct 16, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2055

Labels added:

  • v26.6-must-backport

These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels.

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 16, 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 Oct 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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 Pull request should be backported intentionally. Use this label with great care! 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.4-must-backport v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants