Skip to content

Evaluate a materialized view's scalar subquery per inserted block when a row policy of a table it reads has a subquery - #125610

Open
groeneai wants to merge 20 commits into
ClickHouse:masterfrom
groeneai:mv-source-read-by-merge-loop-executable
Open

groeneai wants to merge 20 commits into
ClickHouse:masterfrom
groeneai:mv-source-read-by-merge-loop-executable

Conversation

@groeneai

@groeneai groeneai commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125385
Related: #125990
Related: #129497

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 writing the first inserted block's value of a scalar subquery for every block when a table the subquery reads, directly, through loop or as a child of a Merge table (also one read through loop, executable, Alias, Buffer or a materialized view), has a row policy or additional_table_filters entry with a subquery, or when the subquery reads the source table through loop. Fixed Scalar ... doesn't exist for an Array or Tuple scalar subquery in the row policy of a Merge child under a materialized view, and CANNOT_CONVERT_TYPE for one whose result contains a Variant.

Description

On 26.3.42.3, 26.8.18.2 and 26.9.9.28, with a row policy x IN (SELECT x FROM src) on t, a materialized view on src with (SELECT max(x) FROM t) writes the first block's value for every inserted block. The same read under a CROSS JOIN is evaluated per block.

The scalar cache decides from the subquery's tree whether it may read the inserted block, but row policies and additional_table_filters are added at planning, and their subqueries may read it. The check now also counts those filters, for the tables in the tree and for the children of a Merge they read (IStorage::mayReadViewSource, forwarded by Alias, Buffer, materialized views, table function tables and loop; executable with an input query stays conservative). Any subquery counts, even one not reading the source, so such a scalar then runs once per block, like the CROSS JOIN form. For loop it also counts the view source itself, which loop reads since #129338, and the filters its inner query applies as a top-level query, additional_result_filter included. A filter subquery is also found in a SQL UDF named without a call (arrayExists(f, [x]), f | g) and in a scalar nested in another scalar. A per-block Array scalar in a Merge child's policy threw Scalar ... doesn't exist (#125385), and the analyzer bound it through the query context all blocks of an INSERT share, so a parallel block could get another block's value; both evaluators now inline a local scalar as a constant, keeping the member type of a Variant or Dynamic value (a Variant scalar in a Merge child's policy threw CANNOT_CONVERT_TYPE even outside a view).

Validation: two new tests with one-row blocks fail without the fix (stale value or #125385) and pass with it, also randomized; removing each check reddens its cases.

🤖 Generated with Claude Code


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

… 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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 13, 2026
@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; one full pass).

# Sev Finding Verdict Evidence / action
1 💡 Use Critical Bug Fix instead of Bug Fix, since the PR fixes a SIGSEGV DISAGREE I do not self-assign Critical Bug Fix; that is the maintainers' call. Bug Fix fits: v26.9.16.11-stable and the 26.8 build of the failing job crash on a plain INSERT, and v26.8.18.2 does not.

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

Session id: cron:clickhouse-review-slot-8:20261013-112800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test SIGSEGVs pristine master on every run (server for the merge and loop arms, clickhouse local for executable), with the CI frames. The official 26.8 build of the failing job and v26.9.16.11-stable crash the same way.
b Root cause explained? Since #123514 a reference to the view source table is typed by the view source metadata (no primary key), and only an interpreter given the view source as its storage swaps it in. A Merge child planned by a nested interpreter, the inner query of loop and the input queries of executable re-analyze without it, so KeyCondition reads a null key expression.
c Fix matches root cause? Yes. The three sites pass the view source as the interpreter's storage, the idiom interpretSubquery and ExecuteScalarSubqueriesVisitor already use. No guard in KeyCondition.
d Test intent preserved / new tests added? New test 05388_mv_source_read_by_merge_loop_executable, one arm per site.
e Both directions demonstrated? Yes. Master: crash. Fix: passes (50/50 randomized, also with a Replicated database). Reverting any one site alone re-crashes its arm.
f Fix is general across code paths? Every InterpreterSelectQueryAnalyzer built from an AST was checked. The three that crash are fixed. The local shard of Distributed, view inner queries, analyzer IN/scalar subqueries and the view root already handle the view source. Buffer over Distributed was probed and does not crash.
g Fix generalizes across inputs (params/datatypes/wrappers)? Merge engine and merge() share the changed code; loop over a table or a table function too. Randomized settings include prefer_localhost_replica both ways and automatic_parallel_replicas_mode = 2. Column types play no role (the defect is table resolution).
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. These reads see the inserted block again, as before #123514 and as v26.8.18.2 does.
i Invariants and contracts preserved? Only table nodes named like the view source are replaced, keeping alias and modifiers. The context is unchanged, so row-policy subqueries (05321) and the Distributed local shard (05294) behave as before. Outside a materialized view push the call is identical to before. Inside a view inner query, null is passed (#124875).

Session id: cron:clickhouse-impl-slot-4:20261013-103900

@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e701af1]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) FAIL
05493_unique_key_disk_without_append FAIL cidb
05829_autopr_skip_index_on_read_in_subquery FAIL cidb
05829_autopr_skip_index_on_read_in_subquery FAIL cidb
05829_autopr_skip_index_on_read_in_subquery FAIL cidb
04353_text_index_explicit_tokenizer_argument NOT_FAILED cidb
05034_lazy_materialization_column_function_set_capture NOT_FAILED cidb
05033_lazy_materialization_column_function_structure_equals NOT_FAILED cidb
01710_projection_with_mixed_pipeline NOT_FAILED cidb

AI Review

Summary

This PR makes materialized-view scalar subqueries block-local when hidden filters or nested storage reads can depend on the inserted block, and preserves local scalar values without sharing them through the query context. The previous correctness findings are addressed. One existing Major remains: source-independent filter subqueries unnecessarily disable the scalar cache. For the constant representation change, the consumers traced were PlannerActionsVisitor (typed constant columns), CollectSets (constant columns and types), ConstantNode::toASTImpl (typed AST serialization), and TreeRewriter/ExpressionAnalyzer (cast ASTs).

Findings

⚠️ Majors

  • src/Analyzer/Utils.cpp:152: Keep source-independent scalars eligible for the global cache. hiddenFilterMayReadTable checks whether a filter contains any subquery, rather than whether it can read the view source. Thus a policy such as x IN (SELECT x FROM whitelist) forces (SELECT sum(x) FROM t) to scan t again for every inserted block, although its value is independent of that block. A local probe with 128 one-row blocks and a 100,000-row Memory table recorded 128 scalar-cache misses and no global hits, versus one miss and 127 global hits for the equivalent policy x IN range(1024). The corresponding inserts took approximately 0.321 seconds and 0.128 seconds. This supports the existing inline finding; no duplicate comment was posted. Preserve caching when resolved filter dependencies do not reach the view source, while retaining per-block evaluation for dependent filters.
Tests
  • ⚠️ Add focused coverage that a scalar over a source-independent subquery policy is evaluated once per INSERT, alongside the existing tests requiring dependent policies to evaluate per block.
Missing context / blind spots
  • ⚠️ The head build and targeted CI were still running when checked. Local probes used the available PR CI binary 5e36832c60c71cf89017986fdb5fe28334b53413; the cache-classification predicate exercised above is unchanged at head e701af1ebe78be49ba6e2f5d547ed99ddb7c8d38. Completed head CI would validate the latest regression-test additions.
Final Verdict

Status: ⚠️ Request changes. Preserve global caching for source-independent hidden-filter subqueries and add a focused regression assertion. No new inline findings; the existing Major thread remains applicable.

@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 Oct 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e701af1eb with master 92fdcb78e (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

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

Job report

@PedroTadim PedroTadim self-assigned this Oct 13, 2026
`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 `05388_mv_source_read_by_merge_loop_executable`).
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

CI finish ledger - 95659a4

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (amd_compat) / (no test row) infra, not from this PR: the self-hosted runner was lost about 20 min into the job (no step finished, no log), never re-run a fix task is created (fixing-PR link to follow here)
Build (riscv64) / (no test row) infra, not from this PR: the same lost runner, about 20 min into the job, never re-run a fix task is created (fixing-PR link to follow here)
Build (wasm64) / (no test row) infra, not from this PR: the same lost runner, about 20 min into the job, never re-run a fix task is created (fixing-PR link to follow here)
Stateless tests (arm_asan_ubsan, azure, parallel) / (no test row) infra, not from this PR: the host Docker daemon died at 22:55:27Z (error waiting for container: unexpected EOF, exit code 125) before any test result was written, never re-run a fix task is created (fixing-PR link to follow here)

All four jobs started at 22:43Z in the wave in which Fast test and Build jobs errored on dozens of PRs. The automatic retry re-ran other jobs of this run (it reached attempt 3) but not these four. Mergeable Check and PR are the rollups of these rows.

Session id: cron:our-pr-ci-monitor:20261014-040009

groeneai and others added 3 commits October 14, 2026 13:18
…s the source through `merge`, `loop` or `executable`

Under a materialized view, the nested query of `merge`, `loop` or `executable` reads the
block pushed to the view, but `subtreeHasViewSource` recognized only a direct `TableNode`
of the source. Such a scalar subquery qualified for the query-wide scalar cache, so the
value computed for the first block was reused for every following block of the same INSERT
(e.g. `(SELECT max(x) FROM (SELECT x FROM loop(db, src) LIMIT 1))` gave 1, 1, 1 instead of
1, 2, 3 for three one-row blocks). The same result is returned by 26.3, 26.8.18.2 and
26.9.9.28, where these sites read the block too.

`IStorage::mayReadViewSource` answers for the storages that read a table through a nested
query analyzed in the reader's context: `Merge` (a matching child, recursively), `Loop`
(its inner table, recursively), `Executable` with input queries (conservatively), and
`StorageProxy` forwards it. `Distributed` does not need it: its local plan clears the view
source. A `merge` over unrelated tables still uses the cache across blocks.

The test now pushes one block per row in each arm.

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

These storages read their target or destination in the caller's context, so
a scalar subquery over them in a materialized view query depends on the
inserted block whenever the target reads the view source (for example an
`Executable` table whose input query reads it). The scalar cache treated such
a subquery as block-independent and reused the first block's value for every
later block. Each wrapper now answers for the table it forwards to.

The wrappers do not report their target being the view source itself: their
`read` calls the catalog storage directly, so that read returns the table, not
the inserted block. Ordinary views analyze their inner query as a view inner
query and keep reading the table.

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

`ExecuteScalarSubqueriesVisitor` evaluates the scalar subqueries of standalone
expressions, such as the row policy of a `Merge` child. Under a materialized
view it only kept a scalar out of the query-wide cache when the view source
appeared directly in the subquery, so a scalar over `loop`, `merge` or
`executable` of the source was computed for the first inserted block and
reused for every later one. Move the analyzer's check to `subtreeMayReadViewSource`
in `Analyzer/Utils` and use it in both evaluators.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMerge.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fc76187

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05059_autopr_settings_in_select_settings_clause flaky, not reachable from this diff (it changes the materialized view scalar cache, not automatic parallel replicas): query_1 reports pr_used 0 instead of 1 because the cost gate flips on a well-compressed read; 2/48 same-settings reruns failed, and the same failure is on master and 9 other PRs since 2026-10-12 #125544 (mine, open)
Mergeable Check, PR (rollup statuses) derived, they mirror the red job above #125544 (mine, open)

CH Inc sync is green at this head.

Session id: cron:our-pr-ci-monitor:20261014-203009

groeneai and others added 3 commits October 14, 2026 22:15
…_table_filters of a table it reads has a subquery

Under a materialized view push, a scalar subquery goes to the query-wide scalar cache unless
`subtreeMayReadViewSource` sees a read of the view source. It looked only at the tables in the
subquery tree (and what `merge`, `loop`, `executable` and wrappers read). Row policies and
`additional_table_filters` are attached later, when the read is planned, and their subqueries are
analyzed in the reader's context, where the source table is the inserted block. So
`(SELECT max(x) FROM t)` over a table with `ROW POLICY ... USING x IN (SELECT x FROM src)` gave
every block the first block's value, while the same read in a CROSS JOIN was per block.
Reproduced on 26.3.42.3, 26.8.18.2, 26.9.9.28 and master.

The predicate now also returns true for a read whose row policy or `additional_table_filters`
entry has a subquery:

- `Planner/Utils`: `astContainsSubquery` moves here from `PlannerJoinTree.cpp` and also counts a
  bare SELECT (a policy `USING (SELECT ...)`) and SQL UDF bodies; `parseAdditionalTableFilter` is
  the planner's own matching and parsing of `additional_table_filters` (only the matching entry is
  parsed, as before); `hiddenFilterMayReadTable` combines both with `getEffectiveRowPolicyFilter`.
- `IStorage::mayReadViewSource` takes the reader's context. `Merge` children and the `loop` inner
  table are checked for both (a `Merge` child planned by a nested interpreter gets its own
  `additional_table_filters` entry); `Alias`, `Buffer`, materialized views and `StorageProxy`
  forward the context.
- `subtreeMayReadViewSource` takes the context, and checks each nested query in its own context,
  since a `SELECT ... SETTINGS additional_table_filters = ...` nested in the scalar applies its own
  filters.

"Has a subquery" is deliberately conservative: deciding whether a filter's subquery reads the source
would mean resolving its tables outside the analyzer. A false positive only evaluates the scalar once
per pushed block instead of once per INSERT. Nothing changes outside a view push.

The test gets arms for a policy with IN, a policy via a SQL UDF, a `merge` child policy, a `loop`
policy, a policy chain through the standalone-expression evaluator, `additional_table_filters` on the
INSERT (also on a `merge` child next to a `Distributed` table) and in a nested query's SETTINGS.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`ExecuteScalarSubqueriesVisitor` emitted `__getScalar` for a scalar whose type is not worth a literal
(`Array`, `Tuple`, ...), but `TreeRewriter` saves only global scalars in the query context, where
`__getScalar` looks them up. A local one (it may read the inserted block of a materialized view)
therefore threw `Scalar ... doesn't exist`, e.g. an `Array` scalar in the row policy of a `Merge`
child. A local scalar is now always a literal. The previous commits make more scalars local, so this
is needed for them too.

Closes ClickHouse#125385.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the docs of subtreeMayReadViewSource, IStorage::mayReadViewSource and the Planner/Utils helpers; drop two comments narrating the new code.

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; 2 findings over three passes, the last one clean) and my own review.

# Sev Finding Verdict Evidence / action
1 ❌ A Merge child planned by a nested interpreter (a Distributed sibling) gets its additional_table_filters entry, so a subquery there can read the inserted block while the scalar-cache check ignores child filters AGREE Fixed: child filters are checked like any table's; new merge filters arm.
2 ❌ A local Array/Tuple scalar of the standalone-expression evaluator (a Merge child's row policy) is emitted as __getScalar but never saved where it is looked up, so the INSERT throws Scalar ... doesn't exist (#125385); this PR makes more scalars local AGREE Fixed: a local scalar is always inlined as a literal; new merge array policy arm.
3 💡 Merge and loop repeat the same three-term child predicate noted Not blocking.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A materialized view with (SELECT max(x) FROM t) where t has a row policy x IN (SELECT x FROM src), one block per row: every block gets the first block's value, on every run (also 26.3.42.3, 26.8.18.2, 26.9.9.28). An Array scalar over the source in a Merge child's row policy throws Scalar ... doesn't exist on every run (#125385).
b Root cause explained? The scalar cache decides "may depend on the inserted block" from the tables in the subquery tree only. Row policies and additional_table_filters are attached later, at planning time, and their subqueries read the inserted block under a view push, so the value was cached for the whole INSERT. Separately, the standalone-expression evaluator emitted __getScalar for a local non-literal scalar, which only the query context can resolve and which never receives local scalars.
c Fix matches root cause? Yes. The shared predicate (subtreeMayReadViewSource, IStorage::mayReadViewSource) now counts those filters, using the planner's own filter lookup and subquery detector. No cache disabling, no setting. A local scalar of the standalone evaluator is now a literal, as when there is no query context.
d Test intent preserved / new tests added? 9 new arms in 05388: policy with IN, policy via SQL UDF, merge child policy, an Array scalar in a merge child policy, loop policy, a policy chain through the standalone-expression evaluator, additional_table_filters on the INSERT (also on a merge child next to a Distributed table), and in a nested query's SETTINGS.
e Both directions demonstrated? Yes. Without the cache change exactly the 8 cache arms fail; without the literal change the Array arm throws Scalar ... doesn't exist; with both all pass (50/50 randomized, also DatabaseReplicated and parallel replicas). Removing each code site reddens its arms.
f Fix is general across code paths? Both scalar evaluators, tables and table functions, Merge children and the loop inner table (row policy and additional_table_filters), wrappers, and each nested query's own settings; a local scalar of any type in the standalone evaluator.
g Fix generalizes across inputs (params/datatypes/wrappers)? Filters with IN or scalar subqueries, bare SELECT, IN table, IN table_function(...), SQL UDF bodies; additional_table_filters keyed by alias, name or full name; local Array, Tuple and LowCardinality scalars.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; outside a view push nothing changes. Under one, such a scalar is evaluated per block instead of once per INSERT, and a local non-literal scalar is inlined as the same literal enable_scalar_subquery_optimization = 0 produces.
i Invariants and contracts preserved? additional_table_filters parsing is the planner's own code, only the matching entry is parsed, and its no-op-when-no-match behaviour is kept. A local scalar stays in the per-analysis cache, never in the query context.

Session id: cron:clickhouse-impl-self-slot-57:20261014-225100

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov this is too large for me to review

@PedroTadim PedroTadim removed their assignment Oct 15, 2026
@groeneai groeneai changed the title Fix a crash on INSERT when a materialized view reads its source table through merge, loop or executable Evaluate a materialized view's scalar subquery per inserted block when it reads the source indirectly or through a row policy Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The crash fix is now #125990; this PR keeps only the per-block scalar-cache part. #125990 needs the can be tested label to run CI.

groeneai and others added 4 commits October 15, 2026 22:14
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]>
`allow_experimental_alias_table_engine` is obsolete.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A scalar subquery that may read the inserted block of a materialized view is evaluated per block, but an
`Array`, `Tuple`, ... result was published in the query context under the subquery's hash and bound through
`__getScalar`. All blocks of an `INSERT` share that context, and with `parallel_view_processing` and
`max_insert_threads` they are analyzed concurrently, so a block could bind another block's value. A local scalar
is now a constant, as in `ExecuteScalarSubqueriesVisitor`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Evaluate a materialized view's scalar subquery per inserted block when it reads the source indirectly or through a row policy Evaluate a materialized view's scalar subquery per inserted block when a row policy of a table it reads has a subquery Oct 16, 2026
@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; 7 findings over five passes) and my own review.

# Sev Finding Verdict Evidence / action
1 ❌ A Merge child planned by a nested interpreter (a Distributed sibling) gets its additional_table_filters entry, so a subquery there can read the inserted block while the scalar-cache check ignores child filters AGREE Fixed: child filters are checked like any table's; new merge filters arm.
2 ❌ A local Array/Tuple scalar of the standalone-expression evaluator (a Merge child's row policy) is emitted as __getScalar but never saved where it is looked up, so the INSERT throws Scalar ... doesn't exist (#125385); this PR makes more scalars local AGREE Fixed: a local scalar is always inlined as a literal; new merge array policy arm.
3 ❌ A local Array/Tuple scalar of the analyzer is bound through the query context, which concurrently processed blocks of one INSERT share, so a block can get another block's value AGREE Fixed: measured first (7 to 59 of 2000/20000 rows took another block's array), now a local scalar is a constant; new parallel array policy arm.
4 ⚠️ The loop / executable arms stay green if their checks are removed (both forms read 105) DISAGREE Inside loop/executable the Merge child's policy reads the inserted block, so both forms give the block's value; removing either check reddens exactly its arm (measured).
5 💡 Merge and loop repeat the same child predicate noted Not blocking (superseded: loop now only forwards).
6 💡 The test sets the obsolete allow_experimental_alias_table_engine AGREE Removed.
7 ❌ A row policy of a plain table that loop (or TimeSeries) reads directly is not checked, so the scalar keeps the first block's value DISAGREE With #125990 that policy reads the source table, not the block (measured with #125990 applied: 105 on every block for both), so the query-wide value is right; without #125990 the result equals master's. TimeSeries is private preview.
8 ⚠️ The parallel array policy arm passes if the blocks happen not to overlap DISAGREE Without the fix the test failed 3 of 3 runs (9 to 21 bad rows of 2000); a deterministic interleaving would need pausing a pipeline worker.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A materialized view with (SELECT max(x) FROM t) where t has a row policy x IN (SELECT x FROM src), one block per row: every block gets the first block's value, on every run (also 26.3.42.3, 26.8.18.2, 26.9.9.28). An Array scalar over the source in a Merge child's row policy throws Scalar ... doesn't exist on every run (#125385). With 2000 blocks pushed concurrently, an Array scalar over a policy table gets another block's value in some rows on every run.
b Root cause explained? The scalar cache decides "may depend on the inserted block" from the tables in the subquery tree only. Row policies and additional_table_filters are attached at planning, and their subqueries read the inserted block under a view push, so the value was cached for the whole INSERT. Separately, a local non-literal scalar was bound through __getScalar, which reads the query context shared by all blocks of the INSERT: the standalone-expression evaluator never put it there (Scalar ... doesn't exist), and the analyzer did, so concurrently analyzed blocks could overwrite each other's value.
c Fix matches root cause? Yes. The shared predicate (subtreeMayReadViewSource, IStorage::mayReadViewSource) counts those filters, using the planner's own filter lookup and subquery detector. No cache disabling, no setting. A local non-literal scalar is a literal in both evaluators, as when there is no query context.
d Test intent preserved / new tests added? 05388_mv_scalar_subquery_row_policy_per_block: 12 value arms (policy with IN, via a SQL UDF, a policy chain, an Array scalar in a Merge child policy, Merge child policy direct and through Alias, Buffer, a materialized view and a table function table, additional_table_filters on the INSERT, on a Merge child next to a Distributed table and in a nested query's SETTINGS), 2 arms comparing the scalar with the same read joined per block, for loop and executable over a Merge with a policy child, and 1 arm pushing 2000 blocks concurrently (parallel_view_processing, 16 insert threads) that counts rows whose Array scalar is not their own block's.
e Both directions demonstrated? Yes. On master and on #125990 every value arm repeats the first block's value and both comparison arms differ, and the Array arm throws Scalar ... doesn't exist; with the fix all pass (50/50 randomized, also DatabaseReplicated and parallel replicas). Disabling the Merge, forwarder, loop, executable or tree-filter check each reddens exactly its arms; without the analyzer's local-literal change only the concurrent arm fails (9-21 of 2000 rows; 1997 on master).
f Fix is general across code paths? Both scalar evaluators, each also inlining a local non-literal scalar; tables and table functions; Merge children (direct read and nested interpreter); Alias, Buffer, materialized view and table function forwarders; loop and executable over a Merge; each nested query's own settings. Engines that run their own query over a plain table (loop, TimeSeries) read the table with #125990, which fixes them once.
g Fix generalizes across inputs (params/datatypes/wrappers)? Filters with IN or scalar subqueries, bare SELECT, IN table, IN table_function(...), SQL UDF bodies; additional_table_filters keyed by alias, name or full name; local Array, Tuple and LowCardinality scalars in both evaluators, also with blocks analyzed concurrently.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; outside a view push nothing changes. Under one, such a scalar is evaluated per block instead of once per INSERT, and a local non-literal scalar is inlined as the same literal enable_scalar_subquery_optimization = 0 produces.
i Invariants and contracts preserved? additional_table_filters parsing is the planner's own code, only the matching entry is parsed, and its no-op-when-no-match behaviour is kept. A local scalar stays in the per-analysis cache, never in the query context, in both evaluators. The per-site interpreter changes of #125990's first design are reverted, so the two PRs share only the identical clickhouse-local race fix.

Session id: cron:clickhouse-impl-self-slot-57:20261016-010800

groeneai and others added 2 commits October 16, 2026 05:14
`ExecuteScalarSubqueriesVisitor` built the literal from the result's `Field`, which drops the active member type of a
`Variant` and of a `Dynamic`: `_CAST([1], 'Array(Variant(String, UInt64))')` failed with `CANNOT_CONVERT_TYPE`, and an
`Array(Dynamic)` element came back as `UInt8`. Since 37956ba a local scalar of a materialized view push (for example in
the row policy of a `Merge` child) takes this path for every type; a global one already did for a top-level `Variant`
or a `Map` result, which failed the same way.

Build the literal with `columnConstantToExactLiteralAST` when the type needs it, as `ConstantNode` does for remote
queries. `date_time_as_numbers` is set because the outer cast re-applies the declared type, and only then is the member
of a `Dynamic` named.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The arm pushed 2000 single-row blocks through the view with 16 insert threads, about 90% of the
test's CPU. In the flaky check, where nproc - 1 workers run copies of the same test, one run took
190-450 s, over the 180 s limit.

It now pushes 25 blocks with 8 threads, and the view query has 32 copies of the scalar. Each copy
is resolved on its own, and with "Inline a local scalar subquery result of the analyzer as a
constant" reverted each one publishes the value into the shared query context and binds it from
there, so a block binds another block's value far more often. With that change reverted the arm
still fails on every run (10/10 alone, 20/20 with 16 concurrent copies, 1-12 of 25 rows wrong); with
it the arm passes. In a debug build it costs ~0.12 s of CPU instead of ~6 s.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cd40ffb

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy, 3/4) / Build ClickHouse not from this PR: unit_tests_dbms does not compile on master since af19343b2516 (src/Functions/tests/gtest_functions_stress.cpp:2367: StackTrace::tryResolveAddress no longer returns an optional); the same build fails on 24 other PRs since 09:18 UTC. This failure stopped the workflow, so most test jobs did not run on this head #126269 (external, open)
Finish Workflow / Post Hooks Bugfix validation was dropped because of the row above #126269 (external, open)
Mergeable Check, PR rollups of the rows above #126269 (external, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261016-110007

groeneai added a commit to groeneai/ClickHouse that referenced this pull request 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]>
@fm4v

fm4v commented Nov 18, 2026

Copy link
Copy Markdown
Member

Merged origin/master into the branch (merge commit 5e36832c60c, no conflicts). The branch was last updated 2026-11-02.

The only red check, Build (arm_tidy, 3/4), was not caused by this PR: the 9 clang-tidy errors are in src/Functions/tests/gtest_functions_stress.cpp (lines 2367-2371, resolved->kind on a const ResolvedAddress), a file this PR does not touch. It was a master-side mismatch with the StackTrace::tryResolveAddress change that CI picked up while merging master. Current master already uses resolved.kind, so the merge fixes it. Finish Workflow was red only because the Bugfix validation jobs were dropped after that build failure.

No code changes to the PR itself.

@fm4v

fm4v commented Nov 18, 2026

Copy link
Copy Markdown
Member

@groeneai master is merged (5e36832c60c), but the AI review on the new head opened a P1 thread on src/Processors/QueryPlan/ReadFromLoopStep.cpp: "Keep wrapper scalar results local to each inserted block". It now blocks the Review Threads gate, so the full CI does not run. Please fix it (or explain why it does not apply and resolve the thread), then report the CI result on the new head.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The thread still applies to 5e36832c60c. With this head's CI binary, its first case, a scalar over loop(d, src) where src is the view source, still returns (1,1), (2,1), (3,1), while the same read under a CROSS JOIN returns (1,1), (2,2), (3,3). Its follow-up case (an Alias over an executable table whose input query reads the source) is fixed here by 58a83d1: (1,1), (2,2), (3,3) on this head, (1,1), (2,1), (3,1) on master.

This PR dropped the loop case (4a1429d) when the crash fix was split out into #125990, and #129497 picked it up later. I will move that check (StorageLoop::mayReadViewSource is also true when the inner table is the view source) and its test into this PR, and close #129497, whose change this PR then contains.

CI on 5e36832c60c ran in full: the gate skipped no job, no test failed, and apart from the private CH Inc sync the only red is the Review Threads verdict in Finish Workflow (Mergeable Check: Failed: review threads only). I will report the CI result of the new head here. The thread was opened by clickhouse-gh, which resolves its own threads once its review accepts the fix, so I leave it to the bot (@ Algunenano asked me not to resolve those).

…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]>
Comment thread src/Planner/Utils.cpp Resolved
groeneai and others added 2 commits November 19, 2026 01:10
The analyzer turns a SQL UDF named as the first argument of a
higher-order function (`arrayExists(f, arr)`) or as an operand of
the `|` composition operator into a call of that function, so its body
is part of the filter just like a called UDF. `astContainsSubquery`
looked up UDF bodies only for function calls, so a row policy
`USING arrayExists(f, [x])` with `f` reading the view source was not
seen, and a scalar subquery over that table reused the first inserted
block's value for the whole INSERT. Look the name up for a short
identifier too. A column that happens to share a UDF's name only makes
the check conservative (the scalar is evaluated per block).
The lookups run under `SuppressQueryFactoriesInfoScope`, so such a
column is not reported in `query_log.used_sql_user_defined_functions`.

Found by the AI review on ClickHouse#125610 (thread r4622263109).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The analyzer folds a scalar subquery into a `ConstantNode` that keeps
the subquery only as its source expression, not as a child, so
`subtreeMayReadViewSource` did not see a view source read by a scalar
nested in another one. A `Merge` child's row policy
`x <= (SELECT (SELECT max(x) FROM src))` is analyzed as a standalone
expression, where the outer scalar was then classified as global and
reused for every inserted block, even in the `CROSS JOIN` form of the
view query.

Found by the second-model review of the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageLoop.cpp Resolved
… source

`loop` plans its inner query as a top-level query in the caller's context and gives it the view source, so the
inner table's row policy and `additional_table_filters` entry, and the `additional_result_filter`, are applied
there and their subqueries read the inserted block. `StorageLoop::mayReadViewSource` did not count them, so a
scalar subquery over `loop(db, t)` with such a filter was cached for the whole `INSERT` and every later block got
the first block's value, while the same read under a `CROSS JOIN` is per block. Count them the way
`StorageMerge::mayReadViewSource` counts the filters of its children.

The same `additional_result_filter` in a query over the plain table, or over a `Merge` table, is not applied to
the nested read, so those reads are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Analyzer/Utils.cpp

if (storage
&& (storage->mayReadViewSource(current_context)
|| hiddenFilterMayReadTable(*storage, node->getOriginalAlias(), current_context)))

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.

[Major] This treats any hidden-filter subquery as block-dependent, even when the filter never touches the view source.

A row policy or additional_table_filters entry like x IN (SELECT x FROM whitelist) is query-global in a materialized view over src: (SELECT max(x) FROM t) has the same value for every inserted block, so caching it once per INSERT is still correct. hiddenFilterMayReadTable only answers "does the hidden filter contain a subquery?", so this branch now forces such scalars to be re-analyzed and re-executed once per block. With max_block_size = 1 that turns one evaluation into O(rows) work.

Please classify the hidden filter after resolving it in the current context (for example via buildFilterQueryTree + subtreeMayReadViewSource), instead of downgrading every hidden-filter subquery to a local scalar.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e701af1

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) / 05829_autopr_skip_index_on_read_in_subquery not from this PR (it changes only how a scalar subquery of a materialized view is evaluated under a row policy): a deterministic red of this test under the plan-based parallel replicas job. Automatic parallel replicas collects no statistics for its queries there (#131450), so 05829_apply is 0 instead of 1. Same red on 12 master commits of this job since 2026-11-19 00:41Z (master report) and on 57 other PRs #132867 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) / 05493_unique_key_disk_without_append not from this PR: SELECT count() FROM t_s3 on a UNIQUE KEY table throws distributed query plan is not supported on UNIQUE KEY tables (SUPPORT_IS_DISABLED) in the plan-based parallel replicas job whenever the runner draws optimize_trivial_count_query = 0 (the runner's diagnosis names that setting). Also red on 2 other PRs #132872 (mine, open)
PR praktika rollup of the rows above #132867, #132872 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

The other CIDB FAIL row on this head is Finish Workflow / Post Hooks of the earlier run that the review-threads gate limited. Mergeable Check is red only because of the rows above.

Session id: cron:our-pr-ci-monitor:20261119-090028

This branch has not been deployed

No deployments
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. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Local scalar left as __getScalar is never registered: MV INSERT throws

3 participants