Repository navigation
Evaluate a materialized view's scalar subquery per inserted block when a row policy of a table it reads has a subquery - #125610
Conversation
… and `executable` under a materialized view Inside a materialized view query, `tryResolveTableIdentifier` (ClickHouse#123514) types every reference to the view source table by the view source metadata (`StorageValues`, no primary key) while keeping the catalog storage, and relies on `replaceStorageInQueryTree` to swap the view source in after the passes. That swap only happens for an interpreter given the view source as its storage. Three reads re-analyze an AST under a copy of the push context without one: a `Merge` child planned by a nested interpreter (a `Distributed` sibling raises the read above `FetchColumns`), the inner query of `loop`, and the input queries of `executable`. The catalog `MergeTree` was then planned with key-less metadata and `KeyCondition` dereferenced a null primary key expression (SIGSEGV, STID 1288-3bd5). Pass the view source as the interpreter's storage at these three sites, as `interpretSubquery` and `ExecuteScalarSubqueriesVisitor` already do. The nested re-analysis reads the inserted block again, as before ClickHouse#123514 and as the old interpreter did. The context is unchanged, so row-policy subqueries of a `Merge` child keep reading the inserted block (05321), the local shard of a `Distributed` read keeps reading the table (05294) and ordinary view inner queries are unaffected. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 1 finding; one full pass).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261013-112800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20261013-103900 |
|
Workflow [PR], commit [e701af1] Summary: ❌
AI ReviewSummaryThis 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 Findings
Tests
Missing context / blind spots
Final VerdictStatus: |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units2171 translation units recompiled, 7305 s compile time in total, 2171 of them have a recent master baseline. |
`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]>
CI finish ledger - 95659a4Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All four jobs started at 22:43Z in the wave in which Session id: cron:our-pr-ci-monitor:20261014-040009 |
…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]>
CI finish ledger - fc76187Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261014-203009 |
…_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]>
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.
Severity: ❌ blocker / |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20261014-225100 |
|
@alexey-milovidov this is too large for me to review |
merge, loop or executableClickHouse#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]>
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.
Severity: ❌ blocker / |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20261016-010800 |
`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]>
CI finish ledger - cd40ffbEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261016-110007 |
…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]>
|
Merged The only red check, No code changes to the PR itself. |
|
@groeneai master is merged ( |
|
The thread still applies to This PR dropped the CI on |
…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]>
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]>
… 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]>
|
|
||
| if (storage | ||
| && (storage->mayReadViewSource(current_context) | ||
| || hiddenFilterMayReadTable(*storage, node->getOriginalAlias(), current_context))) |
There was a problem hiding this comment.
[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.
CI finish ledger - e701af1Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The other CIDB Session id: cron:our-pr-ci-monitor:20261119-090028 |
Closes: #125385
Related: #125990
Related: #129497
Changelog category (leave one):
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
loopor as a child of aMergetable (also one read throughloop,executable,Alias,Bufferor a materialized view), has a row policy oradditional_table_filtersentry with a subquery, or when the subquery reads the source table throughloop. FixedScalar ... doesn't existfor anArrayorTuplescalar subquery in the row policy of aMergechild under a materialized view, andCANNOT_CONVERT_TYPEfor one whose result contains aVariant.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)ont, a materialized view onsrcwith(SELECT max(x) FROM t)writes the first block's value for every inserted block. The same read under aCROSS JOINis 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_filtersare 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 aMergethey read (IStorage::mayReadViewSource, forwarded byAlias,Buffer, materialized views, table function tables andloop;executablewith an input query stays conservative). Any subquery counts, even one not reading the source, so such a scalar then runs once per block, like theCROSS JOINform. Forloopit also counts the view source itself, whichloopreads since #129338, and the filters its inner query applies as a top-level query,additional_result_filterincluded. 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-blockArrayscalar in aMergechild's policy threwScalar ... doesn't exist(#125385), and the analyzer bound it through the query context all blocks of anINSERTshare, 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 aVariantorDynamicvalue (aVariantscalar in aMergechild's policy threwCANNOT_CONVERT_TYPEeven 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]