Skip to content

Evaluate a materialized view's scalar subquery per block when it reads the source through loop, merge or executable - #129497

Closed
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:mv-scalar-cache-nested-view-source
Closed

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:mv-scalar-cache-nested-view-source

Conversation

@groeneai

@groeneai groeneai commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129338
Related: #125610

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 materialized view storing the first inserted block's value of a scalar subquery for every block of an INSERT when the subquery reads the view's source table through loop or executable, directly or through a Merge, Alias or table function table, and an Array or Tuple scalar subquery over the source table storing another block's value with parallel_view_processing.

Description

Stacked on #129338; follow-up of this review finding.

On v26.8.18.2-lts and v26.3.42.3-lts a materialized view with (SELECT max(x) FROM (SELECT x FROM loop(db, src) LIMIT 10)) AS seen stores (1,1),(2,1),(3,1) for three one-row blocks inserted into src instead of (1,1),(2,2),(3,3). executable with an input query over src behaves the same, and on v26.8.18.2-lts so do merge, Alias and CREATE TABLE ... AS loop(...) tables. With parallel_view_processing = 1, an Array or Tuple scalar over src (direct or through loop) stores another block's value for about 5% of the blocks (v26.8.34.13, v26.3.60.2, master).

Root cause. Under a view source, a scalar subquery skips the query-wide scalar cache only if subtreeHasViewSource finds a TableNode of the source. The nested queries of loop, executable input queries and Merge children read the inserted block without one, so the first block's value is kept. An Array or Tuple scalar is bound through __getScalar, which reads a query context entry shared by all blocks.

Change. New IStorage::mayReadViewSource, consulted by subtreeHasViewSource for each table and table function node of the scalar: Loop when its inner table is the view source or may read it, Executable when it has input queries, Merge when a child may; StorageProxy and Alias forward. Only such scalars lose the query-wide cache; they are bound as constants. Price: an executable scalar with an input query runs once per block even if its input query does not read the source, and a merge scalar enumerates its children once per block. A row policy reading the source hides the same read; that case is #125610.

Validation. New test (multi-block INSERT, APPEND refreshable view into src, refreshable view reading src, all six shapes; parallel INSERT with Array and Tuple scalars): fails on #129338's head; reverting any override or the constant binding reddens its arms; 50/50 randomized.


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

groeneai and others added 3 commits November 4, 2026 16:49
… 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]>
…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]>
…s the source through `loop`, `merge` or `executable`

Under a materialized view each inserted block is the view source. A scalar subquery is kept out of the
query-wide scalar cache only when `subtreeHasViewSource` finds a `TableNode` of the source table in it.
The nested queries planned by `loop`, by the input queries of `executable` and by `Merge` children are
given the view source, so they read the inserted block, but none of them shows the source as a
`TableNode`: `loop(db, src)` is a table function node, `executable`'s input queries are not analyzed,
and `merge`'s children are not in the tree. The first block's value was then stored in the query
context and reused for every later block of the same INSERT.

Add `IStorage::mayReadViewSource`, consulted by `subtreeHasViewSource` for the storage of every table
and table function node of the scalar. `Loop` answers true when its inner table is the view source or
may read it, `Executable` when it has input queries, `Merge` when a child may read it, and the `Proxy`
and `Alias` wrappers forward to the table they read. Only scalars under a view source that read
through these engines lose the query-wide cache.

Stacked on ClickHouse#129338, which gives these nested reads the inserted block.

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

groeneai commented Nov 5, 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; 5 findings over two passes on the same head).

# Sev Finding Verdict Evidence / action
1 ❌ A row policy of a Merge child whose condition reads the source keeps the scalar cached DISAGREE (separate PR) Row-policy class, handled by #125610; stated in the description
2 ❌ Row-policy scalar subqueries go through the AST evaluator, which does not see these storages DISAGREE (separate PR) Needs a row policy with a scalar subquery, same class as 1 (#125610)
3 ⚠️ Executable with any input query now runs its script once per block DISAGREE Deliberate: input queries are not analyzed in the scalar's tree, a name scan misses loop/merge indirections; the view query is already rebuilt per block; price stated in the description
4 ⚠️ Per-block Merge child enumeration cost needs a measurement DISAGREE 100 tables, 10000 one-row blocks: 30.35 / 29.46 / 34.07 s before, 26.67 / 31.85 / 37.69 s after (debug build)
5 ❌ Clearing the view source for the source child of Merge changes its row policy's semantics DISAGREE (not this diff) That hunk is #129338's; this PR does not touch ReadFromMerge::createPlanForTable

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

Session id: cron:clickhouse-review-slot-9:20261105-132400

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Three one-row blocks (max_block_size = 1, min_insert_block_size_* = 0) into src with an MV scalar (SELECT max(x) FROM (SELECT x FROM loop(db, src) LIMIT 10)): #129338's head stores (1,1),(2,1),(3,1) every time; v26.8.18.2 and v26.3.42.3 do the same. The new test fails 20/20 randomized on #129338's head.
b Root cause explained? can_use_global_scalars is decided by subtreeHasViewSource, which only matched a TableNode named like the view source. loop(db, src) is a table function node, executable input queries are not analyzed, and merge children are not in the tree, while their nested reads do read the inserted block; so block 1's value is stored in the query context and reused by later blocks.
c Fix matches root cause? Yes. The cache decision now asks each table and table function storage of the scalar whether its read may read the view source (IStorage::mayReadViewSource), answered by the storages whose reads plan such a nested query. No setting, no blanket disabling of the cache.
d Test intent preserved / new tests added? New 05520_mv_scalar_subquery_nested_read_per_block: loop, a loop table, merge, Alias, executable, loop over an Executable table, each over a multi-block INSERT, an APPEND refresh into the source and a refreshable view reading the source.
e Both directions demonstrated? Fails on #129338's head (every insert/append_refresh row stale), passes with the fix. Reverting each override (Loop identity, Loop recursion, Merge, Alias, Proxy, Executable) or the analyzer check reddens its arms; Loop recursion, Merge and Alias share one build, their arms are disjoint. 50/50 randomized, 10/10 with --replicated-database.
f Fix is general across code paths? All three nested-read sites (ReadFromLoopStep, StorageExecutable::readImpl, ReadFromMerge non-source children) plus the wrappers that read them in the caller's context (StorageProxy table-function and lazy tables, Alias). Buffer/MaterializedView targets cannot be these engines (no writes), views and Distributed local plans do not get the view source. Row policies stay in #125610.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured both ways: loop(db, t), loop(t), loop(<table function>), merge with a plain and a loop child, Nullable scalar results. A plain-table scalar and a merge over a loop of another table keep the query-wide cache (same global hit count as before). executable without input queries answers false.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only scalars that returned the wrong value per block change.
i Invariants and contracts preserved? The check runs only under a view source and uses the scalar's own context, which the nested read inherits. StorageProxy forwarding may load a lazy table the scalar reads anyway, like its existing forwards; Alias with a missing target answers false.

Session id: cron:clickhouse-impl-slot-40:20261105-113500

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy, could you review this and add the can be tested label so CI runs? Only the last commit is new (the first two are #129338): subtreeHasViewSource now asks each table and table function storage of a scalar subquery whether its read may read the inserted block (IStorage::mayReadViewSource, answered by Loop, Executable, Merge, Alias and StorageProxy), so such a scalar is evaluated per block instead of reusing the first block's value from the query-wide cache.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Nov 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b05c7e8]

Summary: ✅


AI Review

Summary

Reviewed head b05c7e87d25b9afadbf524f7026a45e4273187ac. The change evaluates source-dependent scalar subqueries per inserted block through loop, merge, executable, and their wrappers, and binds local complex values as constants. No new actionable findings remain; the previously reported parallel Array/Tuple binding issue is fixed. Both added regressions pass in current-head fast CI. An additional local check covered seven read shapes and numeric, Array, Tuple, and aggregate-state scalars: 56 output rows, zero incorrect values.

Missing context / blind spots
  • ⚠️ Current-head sanitizer and stress CI were still pending at review time; their completed reports will close that validation gap.
Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-materialized-view Materialized views: insert-triggered MV pipeline, insert dependencies, deduplication. labels Nov 5, 2026
…f publishing it in the query context

A scalar subquery that reads the view source is evaluated per inserted block, but an `Array`, `Tuple`
(and the other `useless_literal_types`) result was still published under the subquery hash in the
INSERT-wide query context and bound through `__getScalar`, which reads that shared entry. With
parallel view branches (`parallel_view_processing = 1`, `max_insert_threads > 1`) one block can
overwrite the entry before another block binds it, so the row stores another block's value.

Measured with 10000 one-row blocks, 8 insert threads, a `Null` source and a `Memory` target:
`(SELECT groupArray(x) FROM (SELECT x FROM loop(db, src) LIMIT 1))` 477 wrong rows and a two-column
(`Tuple`) scalar 429 on the previous head; a scalar reading the source directly
(`(SELECT groupArray(x) FROM db.src)`) 466 on master, 584 on v26.8.34.13 and 539 on v26.3.60.2;
0 for all with `enable_scalar_subquery_optimization = 0` and 0 with this change.

Such a scalar is now bound as a `ConstantNode`, as it already is when the optimization is disabled.
The same change is part of ClickHouse#125610.

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

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b05c7e87d with master 117ffe67e (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.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -314.7 s (-5%) in total before that adjustment.

Job report

The flaky check runs nproc-1 copies of a new test at once with the thread fuzzer on, and there the
1000-block INSERT made every run take 215-279 s against the 180 s limit. It was 97% of the test's
server CPU (6.2 of 6.4 CPU-s per run, debug build).

With 200 blocks the binary without the Array/Tuple folding still fails the test in 60 of 60 runs
(10 of 10 through clickhouse-test with randomized settings), and the per-run cost under matched
concurrency (16 CPUs, 15 workers, 30 runs) drops from a 7.45 s to a 2.64 s median.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing: #125610 now contains this change (2050065 adds the loop check and this test; the rest was already there), as requested on that PR.

@groeneai groeneai closed this Nov 18, 2026
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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants