Skip to content

Add query plan cache for complex queries (views, joins, subqueries) - #107125

Open
alexey-milovidov wants to merge 221 commits into
masterfrom
query-plan-cache-complex
Open

alexey-milovidov wants to merge 221 commits into
masterfrom
query-plan-cache-complex

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 11, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add an experimental query plan cache supporting complex SELECT queries: views (including nested views), joins, UNION, IN subqueries and multiple tables over supported local table engines. When allow_experimental_query_plan_cache = 1 and enable_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 CACHE clears the cache; events QueryPlanCacheHits/QueryPlanCacheMisses/QueryPlanCacheValidationMisses/QueryPlanCacheStaleMisses and metrics QueryPlanCacheBytes/QueryPlanCacheEntries provide observability.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Description

An experimental query plan cache for SELECT queries that supports complex queries — views (including nested views), joins, UNION, IN subqueries and multiple tables over supported local table engines. It complements #99309, which covers single-table MergeTree queries 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_plan mode (the machinery used by distributed plan shipping), with a new SelectQueryOptions::cacheable_logical_plan mode that makes the logical plan self-contained:

  • Leaf reads are storage-agnostic ReadFromTable placeholders for any eligible local engine.
  • Views are expanded at plan time (only StorageView; a materialized view stays a leaf and is read from its target table like an ordinary table), recursively in logical mode (propagated through StorageView::readImpl via SelectQueryInfo::build_logical_plan), so the cached plan embeds the analyzed view bodies instead of deferring the expensive expansion to execution.
  • Key-value direct-join lookup steps (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.
  • The plan is serialized with the standard query plan serialization and built with 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 ReadFromTable leaves 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-checks SELECT access, so DROP/CREATE, ALTER, view redefinition (including nested views), row policy changes and permission revocation are handled transparently.

Eligibility

  • Non-deterministic functions anywhere — including inside expanded view bodies — make a query uncacheable (arrayJoin is exempt: it is multi-valued but pure).
  • Scalar subqueries are evaluated during analysis and baked into the plan as constants, so they are gated behind the opt-in setting query_plan_cache_allow_scalar_subqueries.
  • Table functions, temporary tables, system tables (except system.one), remote/Merge storages and views whose SQL security is not INVOKER (DEFINER and NONE) are rejected.
  • Plans containing steps without serialization support (e.g. window functions) execute normally and are simply not stored.

Performance, proven on DOOMbench

DOOMbench is a DOOM-like raycasting engine implemented entirely in SQL; its screen query 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 showed IQueryTreeNode::getTreeHash and analyzer resolution dominating, and SELECT ... LIMIT 0 was as slow as the full query. With the plan cache (local server, single connection):

DOOMbench frame render median speedup
cache off 551-577 ms —
cache on (hit) 227-246 ms 2.4x
cache on, max_threads = 4 148-176 ms 3.3x

On 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, and rand() inside a view body refuses to cache.

Notes

  • This PR includes the ActionsDAG input-constant serialization fix Preserve constant columns of ActionsDAG input nodes in serialization #107124 as its first commit; it will be rebased once that PR is merged.
  • The miss path executes through the same logical-plan machinery as hits, so hit and miss behavior is identical by construction; storage-specific planning shortcuts (e.g. trivial count()) are not applied to cache-enabled queries.

Related: #99309
Related: #107124


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

…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]>
@alexey-milovidov
alexey-milovidov force-pushed the query-plan-cache-complex branch from 3629ad4 to 9d3a72e Compare June 12, 2026 19:50
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ff62398]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Adds an experimental cache of serialized logical plans for complex SELECT queries, with dependency validation and fresh runtime table reads. Reviewed the current diff and all prior discussion. Two open findings remain: a scalar-subquery privilege bypass and missing plan logging. An acknowledged row-policy race also remains. No new inline findings were identified.

Missing context / blind spots
  • ⚠️ No server binary is available in this job; the remaining findings are based on current source traces. The latest Praktika report has successful fast tests and tidy builds, but the full test jobs have no results yet. Focused regressions below would close the remaining evidence gaps.
Findings

❌ Blockers

  • src/Interpreters/Cache/QueryPlanCacheUtils.cpp:1310 — Allowed scalar subqueries skip the aggregate privilege guard. With both cache flags, query_plan_cache_allow_scalar_subqueries = 1, and allow_introspection_functions = 1, warm the following as a user with SELECT on a one-row local Memory table t and the INTROSPECTION grant:

    SELECT (SELECT length(arrayReduce(concat('flame', 'Graph'), [[toUInt64(1)]])) FROM t) FROM t;

    Revoke only INTROSPECTION and repeat. The raw AST has only separate name fragments; the outer resolved tree has a numeric constant whose scalar source is skipped. Scalar evaluation runs optimization passes without the cache eligibility hook, so a hit can return the constant without recreating flameGraph or checking the revoked grant. Fresh analysis denies it. Check resolved scalar trees before evaluation/optimization discards this evidence. Existing open thread; its latest reply already documents the remaining carrier, so no duplicate comment was posted.

  • src/Interpreters/Cache/QueryPlanCacheUtils.cpp:268 — A dropped higher-order UDF can leave an invalid row policy cached. [dismissed by author -- https://github.com/Add query plan cache for complex queries (views, joins, subqueries) #107125#discussion_r3752378732] The author explicitly acknowledged this residual race. It remains real because getFunctionPassedByName consults the current factory after the policy has already been analyzed, while the policy fingerprint hashes only its unchanged AST. For USING arrayExists(f, [id]), dropping deterministic f after logical planning makes its identifier look like an ordinary column during admission; the cached filter retains its old body and keeps validating, although fresh analysis fails. Record the UDF reference or cache ineligibility when analysis resolves it. This accepted deferral is retained here only; the author-resolved thread was left unchanged.

⚠️ Majors

  • src/Interpreters/InterpreterSelectQueryFromPlan.cpp:36 — Cache-enabled execution discards log_query_plans capture. executeQuery calls setPlanLogCapture, but this interpreter inherits the no-op base implementation and supplies no capture to buildQueryPipeline. Both an admitted cold execution and a hit consequently leave system.query_log.query_plan empty despite log_query_plans = 1. Retain and forward the capture, including query_plan_max_step_description_length, as the analyzer interpreter does. Existing open thread; no duplicate comment was posted.
Tests
  • ⚠️ Extend 05843_query_plan_cache_folded_aggregate_access_checks with the computed-name scalar-subquery warm/revoke/repeat case above; require ACCESS_DENIED after revocation.
  • ⚠️ Add a focused check that log_query_plans = 1 populates query_plan on both the storing execution and a cache hit.
  • ⚠️ The acknowledged UDF-drop race can be reproduced using the existing query_plan_cache_pause_after_logical_plan failpoint: pause a policy-filtered query, drop the referenced UDF, resume, and verify that no reusable entry survives.
Final Verdict

Status: ❌ Block

Fix the scalar-subquery privilege bypass and preserve plan-log capture, with the focused regressions above.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jun 12, 2026
Comment thread src/Storages/StorageView.cpp Resolved
alexey-milovidov and others added 3 commits June 13, 2026 07:32
…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]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 4 commits June 17, 2026 13:14
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]>
alexey-milovidov and others added 2 commits June 24, 2026 19:10
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]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
…ProfileEvents conflict (keep both sides' events)
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
alexey-milovidov and others added 2 commits June 26, 2026 15:30
…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]>
alexey-milovidov and others added 3 commits November 9, 2026 22:18
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 55ca406: merged current master and fixed the red CI.

  • 05395_query_plan_cache_planner_derived_state failed everywhere because Apply result limits to queries without FROM #129418 stopped exempting system.one from result limits (quotas only). The cache follows normal execution, so the test now expects TOO_MANY_ROWS_OR_BYTES on both the miss and the hit (5db5d62).
  • Addressed both open review blockers (55ca406): expanded view bodies are now checked for eligibility in StorageView::readImpl, and views inlined by analyzer_inline_views are recorded as analyzed dependencies. New test 05616_query_plan_cache_view_body_eligibility; all query_plan_cache tests pass locally, apart from 5 tests that need parts of the CI server config (MySQL port, transactions, processors_profile_log, WebAssembly UDFs) that the minimal local server doesn't have.

alexey-milovidov and others added 5 commits November 11, 2026 05:34
# 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 169ee6a: merged current master and fixed the red CI.

  • 05498_query_plan_cache_min_execution_speed (Fast test) failed even with the cache off, because master now answers sum from per-part statistics (use_statistics_for_sum_avg_aggregation, 5a0dc9147ab5), so nothing is read and TOO_SLOW never fires. The test disables that setting.
  • Style check: 05620_query_plan_cache_row_policy_niladic_functions now waits for the query_log entry of its HTTP run by query_id in a retry loop (02423_insert_stats_behaviour is flaky #84364).
  • The master merge changed the signature of buildFilterQueryTree (new view_source_in_subqueries argument). The row-policy eligibility check now passes planner_context->isViewSourceInSubqueries(), the same as buildFilterInfo.

I compiled PlannerJoinTree.cpp locally. I could not link a full binary because the build host is overloaded. I checked the cause of the 05498 failure on a recent binary: with the setting on, the query does not throw; with it off, it throws TOO_SLOW.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed cce4de1: merged current master. The only conflict was in the failpoint declarations in src/Interpreters/executeQuery.cpp (segfault_read_access/segfault_write_access from master next to the query plan cache failpoints), and I kept both sets. The merged tree builds, and 65 of the 68 query_plan_cache stateless tests pass locally. The other three fail only because the local test server has no MySQL port, no transactions and no WebAssembly. The previous red CI was the six Performance Comparison shards, and those were infrastructure failures: test selection hit GitHub API 403 rate limit exceeded, so no performance tests ran. There are no unresolved review threads.

alexey-milovidov and others added 4 commits November 16, 2026 05:55
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed d8ea51ed4ccc:

  • Merged current master (d1e8e1a0cc7c). Master moved the planner steps from Planner.cpp to PlannerSteps.cpp, so the PR's addWindowSteps change (taking SelectQueryOptions and keeping 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 new unbounded-stream condition. Context.h kept both PlanCacheStorageIdentities and master's SQLSecurityOverriddenBody.
  • Fixed the red Build (arm_tidy) jobs: PlannerContext::isBuildingCacheableLogicalPlan is now [[nodiscard]] (modernize-use-nodiscard).

The merged tree builds. Locally, 67 of the 69 query_plan_cache stateless tests ran and 65 passed, including 05409_query_plan_cache_window_max_threads and 05499_query_plan_cache_max_threads_union, which cover the ported code. The two failures are only because the local server has no transactions (05457) and no WebAssembly (04665). There are no unresolved review threads.


/// 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()))

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.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 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.

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.

[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.

Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 3 commits November 21, 2026 20:14
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 22dfc2913939:

  • Merged current master (a2126dbc1467). Conflicts: PlannerContext.cpp (kept is_building_cacheable_logical_plan, took master's mayShipPlanFragment / building_distributed_plan condition), PlannerSteps.cpp (addWindowSteps keeps taking SelectQueryOptions, plus master's setWindowSorting), and 01271_show_privileges.reference (master added a column; the SYSTEM DROP QUERY PLAN CACHE row has it too).
  • Fixed the red Build (arm_tidy, 3/4): isCacheable and findCTE are now [[nodiscard]].
  • Addressed both open review blockers: eligibility is now checked before the query tree optimization passes (30060831f66b), and plans that fold an access-checking aggregate function named by a string are not cached (22dfc2913939). Each has a new regression test.

The merged tree builds. Locally all 71 query_plan_cache stateless tests ran and 68 passed, plus 01271_show_privileges. The three failures are 05500, 05457 and 04665, which need a MySQL port, transactions and WebAssembly that my local server does not have.

alexey-milovidov and others added 4 commits November 24, 2026 17:30
…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]>
… 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 9589bb67a4a0:

  • Merged current master (cfbd3f8bef20). Conflicts: src/Core/Settings.cpp (master made iceberg_compaction_commit_batch_size obsolete, so its old declaration is dropped; the query plan cache settings are kept) and the Setting declarations in InterpreterSelectQueryAnalyzer.cpp (kept both sides).
  • Fixed the red Style check: the history records of the four query plan cache settings moved from 26.11 to 26.12, and QueryPlan::ExpectedStorageIdentities is now a MapWithMemoryTracking.
  • Adapted to two master changes that merged cleanly but broke the PR: FunctionNode::isOrdinaryFunction was renamed to isOrdinaryCall (compile error), and 05510_query_plan_cache_aggregation_spill_threshold_recomputed looked for a trace line that master replaced with Adjusting spill threshold with ....

The merged tree builds. Locally all 71 query_plan_cache stateless tests ran and 69 passed, plus 01271_show_privileges. The two failures are 05500 and 04665, which need a MySQL port and WebAssembly that my local server does not have. There are no unresolved review threads.


query_plan.setConcurrencyControl(context->getSettingsRef()[Setting::use_concurrency_control]);

auto pipeline_builder = std::move(*query_plan.buildQueryPipeline(optimization_settings, build_pipeline_settings));

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] 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.

This branch was successfully deployed

1 active deployment
staging - docs — ff62398c Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants