Repository navigation
Add query plan cache for complex queries (views, joins, subqueries) - #107125
alexey-milovidov wants to merge 221 commits into
Conversation
…ries) A new experimental query plan cache for `SELECT` queries that, unlike the single-table design of #99309, supports complex queries: views (including nested views), joins, `UNION`, `IN` subqueries and multiple tables. Unlike the query result cache, a plan cache hit still executes the query against current data; only parsing, query analysis and logical planning are skipped. Design: instead of universalizing storage-bound steps after planning, the miss path builds the plan in the planner's existing `build_logical_plan` mode (battle-tested by distributed plan shipping), where leaf reads are storage-agnostic `ReadFromTable` placeholders for any engine. On every execution - both hit and miss - `QueryPlan::resolveStorages` re-binds the leaves to fresh storage snapshots, so cached plans are transactionally consistent. A new `SelectQueryOptions::cacheable_logical_plan` mode makes the logical plan self-contained: views are expanded at plan time (recursively in logical mode, propagated via `SelectQueryInfo::build_logical_plan` through `StorageView::readImpl`), and key-value direct-join lookup steps (`JoinStepLogicalLookup`), which bind live storages, fall back to regular joins. Distributed and parallel-replicas logical plans are unaffected. The cache key is the normalized AST hash, a hash of plan-affecting settings, the current database, the user and the sorted role set. Each entry stores a dependency fingerprint over every referenced storage - discovered from the plan's `ReadFromTable` leaves plus an AST closure through view bodies (which also catches tables referenced only from scalar subqueries) - with UUID, metadata version or schema content hash (including the view body), and the row policy hash. Every hit revalidates all dependencies and re-checks `SELECT` access; `DROP`/`CREATE`, `ALTER`, view redefinition (including nested views) and row policy changes invalidate transparently. Eligibility: non-deterministic functions anywhere (including expanded view bodies) make a query uncacheable; `arrayJoin` is exempt since it is pure. Scalar subqueries are evaluated during analysis and baked into the plan as constants, so they are gated behind the new opt-in setting `query_plan_cache_allow_scalar_subqueries`. Table functions, temporary tables, system tables (except `system.one`), remote/`Merge` storages and `SQL SECURITY DEFINER` views are rejected. Plans with unserializable steps (e.g. window functions) execute normally and are simply not stored. Also fixes a pre-existing gap in `ActionsDAG` serialization exposed by this work: lambda capture DAGs reference enclosing constants as input nodes carrying a constant column (`addInputConstantColumnIfNecessary`), but the serializer dropped columns for all input nodes, so functions requiring constant arguments (e.g. `tupleElement` in `arrayMap(t -> t.2, ...)`) failed to re-resolve on deserialization. Input-node constant columns are now serialized; the format change is self-describing via the per-node flag. Cacheable plans are built with `compile_expressions = 0` because JIT-fused function nodes cannot be serialized; the JIT still applies when pipelines are built from the plan. User interface: settings `allow_experimental_query_plan_cache`, `enable_query_plan_cache`, `query_plan_cache_allow_scalar_subqueries`, `query_plan_cache_size_in_bytes_quota`; server settings `query_plan_cache.max_size_in_bytes` and `query_plan_cache.max_entries`; `SYSTEM DROP QUERY PLAN CACHE`; profile events `QueryPlanCacheHits` (counted only when a cached plan is actually used), `QueryPlanCacheMisses`, `QueryPlanCacheValidationMisses`, `QueryPlanCacheStaleMisses`; metrics `QueryPlanCacheBytes`, `QueryPlanCacheEntries`. Proven on DOOMbench (clickhouse/doombench, a raycasting engine in pure SQL whose `screen` view is a deep chain of views over joins, unions, array joins and scalar subqueries; planning dominated its render cost). Local server, single connection, 64x32 map, 128x64 viewport: render (frame) cache OFF: 551-577 ms median render (frame) cache ON: 227-246 ms median (2.4x) render cache ON, max_threads=4: 148-176 ms median (3.3x) with frames byte-identical between cache off/miss/hit, state mutations from the game tick visible on every cached render (HTAP freshness), nested view redefinition picked up immediately, and `rand()` inside a view body refusing to cache. The remaining hit-side cost is dominated by actual execution (aggregation of the pixel grid), not planning: the analyzer/tree-hash storm visible in profiles before (25.8k samples in `IQueryTreeNode::getTreeHash`) drops to noise (174 samples). Related: #99309 Co-Authored-By: Claude Fable 5 <[email protected]>
3629ad4 to
9d3a72e
Compare
|
Workflow [PR], commit [ff62398] Summary: ❌
AI ReviewSummaryAdds an experimental cache of serialized logical plans for complex Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Fix the scalar-subquery privilege bypass and preserve plan-log capture, with the focused regressions above. |
…n setting Two related fixes to query plan cache eligibility and keying for scalar subqueries: - `query_plan_cache_allow_scalar_subqueries` is no longer ignored when computing the cache key. An entry stored while it was enabled could otherwise be reused by a later execution that explicitly disabled it, reusing a stale baked scalar value. The setting now participates in the key, so the two modes do not share an entry. - In the view-body eligibility walk (`ASTDependencyCollector`), only the right-hand argument of `x IN (subquery)` is the set (re-executed on every run). The left operand is an ordinary expression, so a subquery there is a scalar subquery folded into a constant and must be gated like any other scalar subquery. Previously every child of a set function was marked set-position, which let a left-operand scalar subquery escape the `query_plan_cache_allow_scalar_subqueries` gate inside view bodies. Also remove the unused `QueryPlanCacheHits` event extern in `QueryPlanCache.cpp` (the event is incremented by the caller in `executeQuery.cpp`), which the style check flagged as defined but not used. Adds `04337_query_plan_cache_scalar_subquery_gating`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…naffected `StorageView::readImpl` derived `options.cacheable_logical_plan` from `query_info.build_logical_plan`, but `build_logical_plan` is also set for the existing distributed and parallel-replica logical-plan paths. That made view subqueries use the cacheable mode (recursive view expansion, no storage-bound `JoinStepLogicalLookup`) even outside the experimental query plan cache, changing behavior for those paths. Propagate a separate `cacheable_logical_plan` bit through `SelectQueryInfo`, set it only on the cache path in `buildQueryPlanForTableExpression`, and read it in `StorageView::readImpl`. Distributed and parallel-replica logical plans set `build_logical_plan` but not `cacheable_logical_plan`, so their view expansion keeps its previous, non-cacheable behavior. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The query plan cache is a single, server-wide cache. `04324` and `04337` inspect it through the global `SYSTEM DROP QUERY PLAN CACHE` and assert exact `QueryPlanCacheHits` counts between two runs of the same query. That only holds when the test runs in isolation: concurrent queries (including the flaky check, which runs several copies of the same test in parallel) drop or evict the shared entries, turning an expected hit into a miss. The same assertions depend on the exact logical plan, so random plan-affecting settings change whether a query is cacheable, and the cache only engages with the analyzer. Tag both tests `no-parallel`, `no-random-settings`, `no-random-merge-tree-settings` and `no-old-analyzer`. This fixes the `Server died` failures in the flaky checks (the flaky check aborted after `--max-failures` and force-killed the running test processes, which is reported as `Server died`), the old-analyzer result diff, and the random-settings result diffs in the regular runs. #107125 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The requested `QueryProcessingStage` was not part of the cache key, but the cache could be used for any stage the client requests. A non-`Complete` stage such as `with_mergeable_state` changes the logical plan contract and the output header (intermediate aggregate states vs. finalized values), so an entry first cached under one stage could be reused for an identical query later executed under another, returning a plan built for the wrong contract. Only enable the query plan cache when `stage == QueryProcessingStage::Complete`. #107125 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
After merging master, prefixes 04324 and 04337 collide with tests added on master (the 04324_* and 04337_* groups). Renamed the query plan cache tests to the next free prefixes: - 04324_query_plan_cache_complex_queries -> 04356_query_plan_cache_complex_queries - 04337_query_plan_cache_scalar_subquery_gating -> 04357_query_plan_cache_scalar_subquery_gating #107125 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
After merging master, the query plan cache tests `04356`/`04357` collided with new tests added on master at those prefixes (master now reaches `04408`). Renumber them to the next free prefixes so they no longer clash. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ProfileEvents conflict (keep both sides' events)
…story.cpp The `26.6` release was cut, so `02995_new_settings_history` now compares the current settings against the `02995_settings_26_6_1.tsv` reference and requires every setting added after `26.6.1` to be recorded under a version block greater than `26.6`. The four query plan cache settings (`allow_experimental_query_plan_cache`, `enable_query_plan_cache`, `query_plan_cache_allow_scalar_subqueries`, `query_plan_cache_size_in_bytes_quota`) were still under the `26.6` block, so the `Fast test` job reported `PLEASE ADD THE NEW SETTING TO SettingsChangesHistory.cpp: ... WAS ADDED`. Move them to the `26.7` block. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107125&sha=fd0fd283b9bbf13a6e90f4e68627c5f95628650e&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…opped exempting `system.one` from result limits #129418 made a single read of `system.one` ignore only quotas, not result limits. The query plan cache follows normal execution, so both the miss and the hit now reject the result with `TOO_MANY_ROWS_OR_BYTES`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107125&sha=ac33f9a13fab50100f873f73b406f0ded58d6e32&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20sequential%29 PR: #107125 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…or the query plan cache - With `analyzer_inline_views = 0` a view body is analyzed by its own interpreter in `StorageView::readImpl`, so the eligibility check of the caller's query tree did not see a non-deterministic function folded inside it (`now` without parentheses, `CURRENT_TIMESTAMP`, an `ALIAS` column). Check the analyzed body there and keep such a plan off the cache. - With `analyzer_inline_views = 1` the analyzer replaces the view by its body, so the planner never recorded the view and its dependency was pruned. Record the view's identity, from the snapshot and row-policy filter used to inline it, in `QueryAnalyzer::inlineViewSubqueryIfNeeded`, so a hit revalidates its definition, row policy and the `SELECT` grant on it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed 55ca406: merged current
|
# Conflicts: # src/Common/FailPoint.cpp
…lan cache eligibility
The row-policy filter is analyzed in `buildRowPolicyFilterIfNeeded`, separately from the query
tree checked by `queryTreeIsEligibleForPlanCache`, and the AST walk in `fillDependency` missed
what the raw policy text does not show: niladic functions spelled without parentheses
(`currentRequestURL IN ('')`, `now`) and the expressions of `ALIAS` columns read only by the
policy (`cutoff DateTime ALIAS now`). Run `queryTreeIsEligibleForPlanCache` on the resolved filter
tree and mark the plan ineligible through `PlanCacheStorageIdentities::markIneligible`, the same
way `StorageView::readImpl` does for expanded view bodies.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`05498_query_plan_cache_min_execution_speed`: since `sum` can be answered from part statistics (`use_statistics_for_sum_avg_aggregation`), the queries read nothing and `TOO_SLOW` is never raised. Disable the setting in the test. `05620_query_plan_cache_row_policy_niladic_functions`: the `query_log` entry of an HTTP query is written after the response is sent, so wait for the entry of the HTTP run by its `query_id` in a retry loop (style check, see #84364). https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107125&sha=2125f20e7cd11bbfe392fe362d04ded1dc99a48a&name_0=PR&name_1=Fast%20test #107125 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…w-policy filter Master added the `view_source_in_subqueries` argument to `buildFilterQueryTree`; the row-policy filter built for the query plan cache eligibility check now passes it as `buildFilterInfo` does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed 169ee6a: merged current
I compiled |
|
🕵 Pushed cce4de1: merged current |
…mplex Conflicts: kept both new executable UDFs in `tests/config/test_function.xml`, kept the PR's cacheable-plan window reshuffle logic in `Planner.cpp` and the PR's accessors in `TableExpressionData.h` / `ReadFromTableStep.h` with master's `[[nodiscard]]`. Adapted the `getEffectiveMaxThreads` calls to its new `const Context &` signature. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he eligibility The constraint-based optimizations (`convert_query_to_cnf`, `optimize_using_constraints`, `optimize_substitute_columns`) analyze the table constraints in `ConstraintsDescription::getQueryTreeData` and fold them into the rewritten predicate, so they never appear in the query tree checked by `queryTreeIsEligibleForPlanCache`. The store path only checked the raw constraint AST (`constraintsContainFunctionsUnsafeForQueryPlanCache`), which does not show niladic functions spelled without parentheses or the expressions of `ALIAS` columns. Check the resolved constraint tree too and mark the plan ineligible through `PlanCacheStorageIdentities::markIneligible`, the same way `buildRowPolicyFilterIfNeeded` does for row-policy filters. The two carriers named in the review (`ASSUME d <= today`, and `ASSUME ts < cutoff` with `cutoff DateTime ALIAS now`) are currently rejected by the constraint validation of `CREATE` and `ALTER` (`UNKNOWN_IDENTIFIER`: constraints are validated against physical columns only), so this is defense in depth. The new test checks that a deterministic constraint stays cacheable under the resolved-tree check, and a non-deterministic one is not cached. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mplex Master moved the planner steps from `Planner.cpp` to `PlannerSteps.cpp`; the PR's change of `addWindowSteps` (taking `SelectQueryOptions` to keep the window reshuffle in cacheable logical plans) is ported there, and the preliminary `DISTINCT` change in `buildPlanForUnionNode` is re-applied on top of master's unbounded-stream condition.
Fixes the `modernize-use-nodiscard` clang-tidy error in the `arm_tidy` build. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed
The merged tree builds. Locally, 67 of the 69 |
|
|
||
| /// A folded call of a function that checks access rights when it is created would | ||
| /// lose that check on a hit (see `isFunctionCheckingAccessOnCreate`). | ||
| if (isFunctionCheckingAccessOnCreate(function_node->getFunctionName())) |
There was a problem hiding this comment.
[Blocker] Preserve aggregate privilege checks when caching folded wrapper calls
Checking the outer ordinary-function name misses access-sensitive aggregates selected by a string argument. For example, with both cache flags and allow_introspection_functions = 1, warm this query as a user with SELECT on a one-row local Memory table t and the INTROSPECTION grant:
SELECT arrayReduce('flameGraph', [[toUInt64(1)]]) FROM t;arrayReduce folds this into a plain array constant: its determinism and constant-folding properties delegate to the aggregate, and flameGraph inherits the default deterministic property. The eligibility walk sees only arrayReduce, so the plan is admitted. Revoke only INTROSPECTION, keep the same user, roles and settings, and repeat the query: a hit rechecks table SELECT and returns the constant without either of the introspection checks in AggregateFunctionFlameGraph.cpp. Fresh analysis instead rejects the query in createAggregateFunctionFlameGraph. This does not require the scalar-subquery opt-in.
Please preserve/replay the aggregate's access requirements, or exclude access-sensitive aggregates through every carrier, including arrayReduceInRanges, initializeAggregation, combinators and folded scalar subqueries. Add a warm/revoke/repeat regression. This finding is based on source tracing; I could not run it locally.
There was a problem hiding this comment.
🕵 Fixed in 22dfc29. The eligibility checks now reject a call of an aggregate function that checks access on creation (flameGraph, also with combinators such as flameGraphIf), and any constant string that names it. The string check covers arrayReduce, arrayReduceInRanges, initializeAggregation, a computed name (concat('flame', 'Graph')) and a cast to AggregateFunction(flameGraph, ...). flameGraph is the only aggregate function with an access check in src/AggregateFunctions. New test 05843_query_plan_cache_folded_aggregate_access_checks does warm / repeat / revoke / repeat for each carrier and passes locally.
There was a problem hiding this comment.
[Blocker] The scalar-subquery carrier is still uncovered after 22dfc2913939. At src/Interpreters/Cache/QueryPlanCacheUtils.cpp:1310-1315, enabling scalar subqueries skips their entire QUERY/UNION source. src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp:211-230 runs passes with fresh default options and then uses the query-tree interpreter constructor, so the new pre-optimization eligibility hook does not check this tree either.
With both cache flags, query_plan_cache_allow_scalar_subqueries = 1, and allow_introspection_functions = 1, use a one-row local Memory table t and warm:
SELECT (SELECT length(arrayReduce(concat('flame', 'Graph'), [[toUInt64(1)]])) FROM t) FROM t;Then revoke only INTROSPECTION and repeat the identical query. The raw AST contains only the separate name fragments, while the outer resolved value is a numeric constant whose query source is skipped. A hit can therefore return it without recreating the aggregate or checking the revoked privilege; fresh analysis rejects it. Check scalar trees before evaluation/optimization loses this evidence, and extend the grant-revocation regression to this carrier. This is a source trace; no server binary is available in this job.
…mplex Conflicts: - `src/Planner/PlannerContext.cpp`: keep `is_building_cacheable_logical_plan` and take master's `mayShipPlanFragment` / `building_distributed_plan` condition. - `src/Planner/PlannerSteps.cpp`: `addWindowSteps` keeps taking `SelectQueryOptions`, plus master's `setWindowSorting`. - `tests/queries/0_stateless/01271_show_privileges.reference`: master added a column; the `SYSTEM DROP QUERY PLAN CACHE` row gets it too. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…passes
The query tree optimization passes can remove the expression that makes a plan ineligible for the query plan cache. `IfConstantConditionPass` replaces `if(currentRequestURL IN (''), id, id + 100)` with the selected branch and drops the folded condition together with its source expression, so `queryTreeIsEligibleForPlanCache`, which ran on the optimized tree, saw only `id`. A plan warmed over the native protocol was then served to an HTTP request, for which the other branch is the right one.
`buildQueryTreeAndRunPasses` now checks the resolved tree before the optimizations and records the result in `PlanCacheStorageIdentities`. This covers the query itself and the bodies of the views expanded while it is planned.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ecking access
`flameGraph` checks the `INTROSPECTION` grant when it is created. `arrayReduce('flameGraph', ...)`, `arrayReduceInRanges` and `initializeAggregation` take the name of the aggregate function as a string and are folded into a constant when the other arguments are constant, so a query plan cache hit did not create the function again and kept serving the value after the grant was revoked.
The eligibility checks now reject a call of such an aggregate function (also with combinators) and a constant string that names it, which also covers a computed name and the data type `AggregateFunction(flameGraph, ...)`.
Also mark `isCacheable` and `findCTE` as `[[nodiscard]]` to fix the `modernize-use-nodiscard` errors of the `arm_tidy` build:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107125&sha=d8ea51ed4ccc62cc8fe4deb06b8deb705c70605f&name_0=PR&name_1=Build%20%28arm_tidy%2C%203%2F4%29
Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Pushed
The merged tree builds. Locally all 71 |
…mplex Conflicts: - `src/Core/Settings.cpp`: master made `iceberg_compaction_commit_batch_size` obsolete, so its declaration next to the query plan cache settings is dropped. The query plan cache settings are kept, and their history records move to `26.12`, the current version. - `src/Interpreters/InterpreterSelectQueryAnalyzer.cpp`: kept both `query_plan_cache_allow_scalar_subqueries` and master's `parallel_replicas_plan_based`. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…y check Master renamed `FunctionNode::isOrdinaryFunction` to `isOrdinaryCall` (commit f7c43a1), so the merged tree did not compile. Co-Authored-By: Claude Fable 5.2 <[email protected]>
The style check rejects `std::map` here. All users go through the alias, so no conversions are added. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107125&sha=22dfc291393988ea9ab15b1f624d946e6a6500e8&name_0=PR&name_1=Style%20check #107125 Co-Authored-By: Claude Fable 5.2 <[email protected]>
… to the shared spill threshold trace line Master commit 7eb6988 replaced the `Adjusting memory limit before external aggregation` trace line with the shared `Adjusting spill threshold with ...` line of `getMaxBytesBeforeExternalProcessing`, which names the ratio setting. The test now looks for that line. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Pushed
The merged tree builds. Locally all 71 |
|
|
||
| query_plan.setConcurrencyControl(context->getSettingsRef()[Setting::use_concurrency_control]); | ||
|
|
||
| auto pipeline_builder = std::move(*query_plan.buildQueryPipeline(optimization_settings, build_pipeline_settings)); |
There was a problem hiding this comment.
[Major] Preserve log_query_plans for cache-enabled executions
executeQuery enables a QueryPlanLogCapture and calls setPlanLogCapture on this interpreter, but InterpreterSelectQueryFromPlan inherits the no-op base implementation and this call supplies no capture to buildQueryPipeline. Consequently, both a cacheable cold run and a cache hit leave system.query_log.query_plan empty even with log_query_plans = 1: the plan structure and step profiler are installed only when that capture argument is non-null.
Please retain the capture in this interpreter and forward it through pipeline construction, matching InterpreterSelectQueryAnalyzer (including query_plan_max_step_description_length). Add a focused stateless test checking a populated query_plan for both the storing run and the hit.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add an experimental query plan cache supporting complex
SELECTqueries: views (including nested views), joins,UNION,INsubqueries and multiple tables over supported local table engines. Whenallow_experimental_query_plan_cache = 1andenable_query_plan_cache = 1, repeated identical queries skip query analysis and logical planning (the query is still parsed) while still executing against current data.SYSTEM DROP QUERY PLAN CACHEclears the cache; eventsQueryPlanCacheHits/QueryPlanCacheMisses/QueryPlanCacheValidationMisses/QueryPlanCacheStaleMissesand metricsQueryPlanCacheBytes/QueryPlanCacheEntriesprovide observability.Documentation entry for user-facing changes
Description
An experimental query plan cache for
SELECTqueries that supports complex queries — views (including nested views), joins,UNION,INsubqueries and multiple tables over supported local table engines. It complements #99309, which covers single-tableMergeTreequeries with a universalize/materialize design; this PR takes a different approach to reach query shapes where planning cost is actually concentrated (deep view chains, many joins).Unlike the query result cache, a plan cache hit still executes the query: only query analysis and logical planning are skipped (the query is still parsed, since the cache key is built from the parsed AST), so hits are transactionally consistent and always see current data.
Design
On a miss, the plan is built in the planner's existing
build_logical_planmode (the machinery used by distributed plan shipping), with a newSelectQueryOptions::cacheable_logical_planmode that makes the logical plan self-contained:ReadFromTableplaceholders for any eligible local engine.StorageView; a materialized view stays a leaf and is read from its target table like an ordinary table), recursively in logical mode (propagated throughStorageView::readImplviaSelectQueryInfo::build_logical_plan), so the cached plan embeds the analyzed view bodies instead of deferring the expensive expansion to execution.JoinStepLogicalLookup), which bind live storages into the plan, are not used; a regular join is planned instead and the physical join algorithm is chosen at materialization. Distributed and parallel-replicas logical plans do not set this mode and are unaffected.compile_expressions = 0(JIT-fused function nodes cannot be serialized; the JIT still applies when pipelines are built from the plan).Both hits and misses execute through
QueryPlan::resolveStorages, which re-binds every leaf to a fresh storage snapshot.Cache key and invalidation
The key is the normalized AST hash, a hash of plan-affecting settings, the current database, the user and the sorted role set. Each entry stores a dependency fingerprint over every referenced storage, discovered from the plan's
ReadFromTableleaves plus an AST closure through view definitions (which also catches tables referenced only from scalar subqueries): UUID, metadata version (or a schema content hash including the view body), and the row policy hash. Every hit revalidates all dependencies and re-checksSELECTaccess, soDROP/CREATE,ALTER, view redefinition (including nested views), row policy changes and permission revocation are handled transparently.Eligibility
arrayJoinis exempt: it is multi-valued but pure).query_plan_cache_allow_scalar_subqueries.system.one), remote/Mergestorages and views whose SQL security is notINVOKER(DEFINERandNONE) are rejected.Performance, proven on DOOMbench
DOOMbench is a DOOM-like raycasting engine implemented entirely in SQL; its
screenquery renders a frame through a deep chain of views over joins, unions, array joins and scalar subqueries. Ported to ClickHouse SQL, the workload is query-analysis-bound: profiling showedIQueryTreeNode::getTreeHashand analyzer resolution dominating, andSELECT ... LIMIT 0was as slow as the full query. With the plan cache (local server, single connection):max_threads = 4On hits the analyzer cost disappears from profiles (
getTreeHash: 25.8k samples → 174); the remaining time is genuine execution. Correctness validated on the same workload: frames are byte-identical between cache off/miss/hit, game-state mutations are visible on every cached render (HTAP freshness), nested view redefinition is picked up immediately, andrand()inside a view body refuses to cache.Notes
ActionsDAGinput-constant serialization fix Preserve constant columns ofActionsDAGinput nodes in serialization #107124 as its first commit; it will be rebased once that PR is merged.count()) are not applied to cache-enabled queries.Related: #99309
Related: #107124
Workflow [PR]
Sync PR [sync-upstream/pr/107125]