Repository navigation
Conversation
|
Workflow [PR], commit [e96f475] Summary: ❌
AI Review
|
|
Hi team, could someone please help trigger the CI pipeline? Thanks! |
|
The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix. |
|
The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158 |
…repeated SELECT queries, avoiding redundant planning overhead.
0ebe34b to
26a7a53
Compare
|
Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
…cache Conflict resolutions: - `QueryResultCache`: keep `astContainsNonDeterministicFunctions` and `astContainsSubqueries` exported for the query plan cache; take master's `checkCanWriteQueryResultCache` signature with the on-disk backend and its rename of `canWriteToQueryResultCache` to `canWriteToQueryResultCacheInMemory`. - `executeQuery`: keep both the query plan cache eligibility and master's on-disk query result cache resolution; pass master's `positionalArgumentsAlreadyResolved` through the PR's `select_query_options`; keep both fuzzer settings. - `Planner`: keep the PR's window sort decision that does not depend on the effective `max_threads`, so a cached plan does not depend on it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…EAM` modifier The stream settings (cursor, watermark) are not serialized, so a deserialized step would silently read the table as a plain non-streaming table. Throw `NOT_IMPLEMENTED` instead; the query plan cache treats it as "this plan cannot be cached". Co-Authored-By: Claude Opus 5.5 <[email protected]>
`TableExpressionData::getAccessCheckedColumnsNames` holds the columns that the planner resolves away (an `ALIAS` column inlined into `PREWHERE`, `indexHint` arguments). Persist them in the cache entry, include them in the dependencies (so a changed `ALIAS` expression invalidates the entry) and recheck the SELECT privilege on them on a hit (so `REVOKE` is respected). Also use `getEffectiveMaxThreads`, which master now uses to plan queries, when deciding whether the thread limit of a cached plan follows the settings and when recomputing it on a hit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `settings_changes_history` style check requires new settings to be recorded under the current version (`26.11`). https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99309&sha=19c14a1977fe648e2c628338a09f2e4cf9d67a36&name_0=PR&name_1=Style%20check ClickHouse#99309 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Interpreters/executeQuery.cpp
- Use the query plan cache only for `QueryProcessingStage::Complete`: the requested stage is not a part of the key, so a plan warmed with `--stage fetch_columns` was reused by a normal query and vice versa. - Reject plans whose analyzed query tree contains nondeterministic functions that are not visible in the AST: the `CURRENT_USER` identifier and `ALIAS` columns such as `currentUser` or `now64`. Their folded constants were stored in the plan and shared with other users. - Stop ignoring `output_format_*` settings in the key: functions such as `toJSONString` capture them during analysis. - Check `isSerializablePlan` on the original plan before cloning it, and clone inside the cache-admission error boundary, so `SELECT count()` with the default `optimize_trivial_count_query` (a `ReadFromPreparedSource` leaf without `clone`) is executed instead of failing with `NOT_IMPLEMENTED`. - Exclude targets of refreshable materialized views: a cache hit bypassed `RefreshTask::getAndLockTargetTable`, which synchronizes a newly observed target table before reading it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
# Conflicts: # src/Interpreters/executeQuery.cpp
…payloads only into query plan cache entries The PREWHERE, row-level filter and node-name mapping payloads were gated on the global plan serialization version (`>= 1`, `>= 2`), but that version is now 21 and ordinary server-to-server streams carry it. So the legacy parallel-replicas byte was omitted for formats 1..21 and the mapping (now supplied for ordinary logical plans by `PlannerJoinTree`) was written to peers that cannot read it. Add a `for_query_plan_cache` flag to `QueryPlan::SerializationFlags` and to the step (de)serialization contexts, set only by `serializeForQueryPlanCache` / `deserializeForQueryPlanCache`. `ReadFromTableStep` always writes the original layout (including the legacy byte) and adds the extra payloads only in cache entries, which never leave the process. A reader refuses these payloads outside of a cache entry. Address review: ClickHouse#99309 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a new column can shadow 1. An `ALIAS` column expanded only to compute another one (`z ALIAS y + 1`, `y ALIAS a + 1`) was neither selected nor read, so a changed definition of `y` was not detected and a hit replayed the old expression. Add the transitive closure of the columns referenced by `ALIAS` columns to the dependencies; each is validated by its own definition. 2. A new table column can change identifier resolution without a wildcard: with `prefer_column_name_to_alias`, `ADD COLUMN b` makes `WITH 100 AS b SELECT b` read the column. Record every identifier name of the query in the lookup context and capture the table columns with those names, so such an `ADD COLUMN` invalidates the entry while an unrelated one does not. Address review: ClickHouse#99309 (comment) ClickHouse#99309 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y-data scope `AggregatingStep::deserialize` gave the aggregator the root temporary-data scope of the global context, so external aggregation of a deserialized plan (a query plan cache hit, or a plan received by a replica) bypassed the query and user limits such as `max_temporary_data_on_disk_size_for_query`. Use a child of the query context's scope with `temporary_files_buffer_size` and `temporary_files_codec`, as the planner does. Add a stateless test for this and for the dependency fixes of the previous commit. Address review: ClickHouse#99309 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
…cache Conflict resolutions and adaptations to the latest master: - `Planner.cpp`: master moved the planner steps to `PlannerSteps.cpp`; ported the PR's change of `addWindowSteps` (do not depend on `max_threads` when deciding whether to re-sort) there. - `executeQuery.cpp`: kept the query plan cache lookup/insert, added master's `enablePlanLogCapture` before it and master's `quota_ignored` logic after it. - `getEffectiveMaxThreads` now takes a `Context`, and `getMaxThreadsForAvailableMemory` was removed: use `getEffectiveMaxThreads(*context)` in `executeQuery.cpp`, `resolveStorages.cpp` and `MergingAggregatedStep::deserialize`; dropped the PR's change of `QueryPlanOptimizationSettings`, which now follows master. - `buildNodeNameToInputNodeColumn` returns `UnorderedMapWithMemoryTracking`: switched the PR's maps in `SelectQueryInfo` and `ReadFromTableStep` to it. - `resolveStorages.cpp`: use `StackWithMemoryTracking` as on master. - `QueryPlan.h`, `enableAllExperimentalSettings.cpp`: kept both sides. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ndomized settings Only a two-level aggregation spills to disk. With a randomized `group_by_two_level_threshold` above the 200000 keys of the table (e.g. 759534 or 1000000), neither the miss nor the hit spilled, so the expected `TOO_MANY_ROWS_OR_BYTES` was not raised. Fix the threshold in the queries. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99309&sha=57e47e1d1f16e23be2a904bce141398a5c81edb6&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 PR: ClickHouse#99309 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d plan The planner derives `max_bytes_before_external_group_by` of `Aggregator::Params` from the memory available at planning time (`max_bytes_ratio_before_external_group_by`). A plan from the query plan cache kept the absolute threshold of the query that warmed the cache, so with less memory available the hit waited too long to spill. `AggregatingStep::deserialize` now computes it again from the current settings and memory when the plan comes from the query plan cache. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…esult column origins on a plan cache hit - A function that the analyzer folds into a constant, e.g. from an `ALIAS` column, is not visible in the AST or the cached plan, so the access rights it needs (`demangle`, `addressToSymbol`, ...) were not checked on a hit. The entry now stores the ordinary functions of the analyzed query tree, including the source expressions of constants, and a hit creates them again with `FunctionFactory`, which checks the rights for the current user. A plan with a function that is not in `FunctionFactory` is not cached. - The result column origins (`InterpreterSelectQueryAnalyzer::getResultColumnOrigins`) are computed during analysis, which a hit skips, so the MySQL protocol reported different column definitions for a hit, e.g. at `COM_STMT_EXECUTE` after `COM_STMT_PREPARE`. They are now stored in the entry. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
|
||
| ASTPtr normalized_ast = normalizeASTForQueryPlanCache(ast); | ||
|
|
||
| QueryPlanCacheKey key; |
There was a problem hiding this comment.
[Blocker] __getScalar is still outside the cache contract here. The key only sees the normalized SQL, current database, and semantic settings, but analysis constant-folds __getScalar('name') from the per-query scalar packets before the plan is serialized. Warm SELECT ... WHERE a < __getScalar('threshold') + 1 with one scalar value, then run the same SQL with a different threshold: the hit reuses the old folded constant and returns stale results. Please either hash the relevant scalar payloads into the key or make any query that depends on query-context scalars bypass the plan cache.
| const Names & selected_columns, | ||
| const Names & access_checked_columns) | ||
| { | ||
| if (selected_columns.empty() && metadata_snapshot && !metadata_snapshot->getColumns().empty()) |
There was a problem hiding this comment.
[Major] This hit-side recheck still does not mirror Planner::checkAccessRights. The miss path normalizes selected names through getColumnNamesForSelectAccessCheck and uses getColumnsSelectableByTrivialQuery when selected_columns is empty, so grants on a parent column or an explicitly granted subcolumn are handled correctly. Here we check raw selected_columns and only top-level metadata columns instead, so a query can succeed before the cache is warmed and then fail with ACCESS_DENIED on a hit (for example SELECT json.a under GRANT SELECT(json), or SELECT count() under only GRANT SELECT(json.a)). Please reuse the same helper path as the miss-side access check.
| table_expression_query_info.table_expression_modifiers.value_or(TableExpressionModifiers{}), | ||
| false, | ||
| nullptr, | ||
| nullptr, |
There was a problem hiding this comment.
[Blocker] build_logical_plan still drops an in-read row policy here. Above, the planner can keep a pushed policy in table_expression_query_info.row_level_filter for storages like MergeTree (the build_logical_plan special-case only lifts it into a filter step when supportedPrewhereColumns() is present), but this ReadFromTableStep is always built with row_level_filter = nullptr. On shard-side plan shipping (serialize_query_plan = 1, non-local parallel replicas) resolveStorages therefore rebuilds the read without the policy and can return rows the policy should hide. Please either serialize row_level_filter for ordinary shipped plans too, or fail closed and avoid plan shipping whenever the logical plan still relies on an in-read row policy.
| flags |= FLAG_HAS_PREWHERE; | ||
| if (row_level_filter && ctx.for_query_plan_cache) | ||
| flags |= FLAG_HAS_ROW_LEVEL_FILTER; | ||
| if (!node_name_to_input_node_column.empty() && ctx.for_query_plan_cache) |
There was a problem hiding this comment.
[Major] The new build_logical_plan path now populates node_name_to_input_node_column, but this serializer still emits that map only for for_query_plan_cache. Ordinary plan shipping therefore round-trips ReadFromTableStep with an empty mapping, so resolveStorages / ReadFromMergeTree::applyFilters can no longer translate analyzer names like __table1.id back to storage columns. The shard falls back from PK/skip-index/query-condition-cache/automatic PREWHERE pushdown to a pipeline FilterStep or full scan. Please serialize the mapping for non-cache plans too, or reject shipped logical plans that still depend on storage-side filter pushdown.
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 for
SELECTqueries over a single localMergeTree-family table. Withenable_query_plan_cache = 1, a repeated query can reuse the previously builtQueryPlanafter its table dependencies and the access rights of the current user are revalidated.SYSTEM DROP QUERY PLAN CACHEclears the cache; metrics and events areQueryPlanCacheBytes,QueryPlanCacheEntries,QueryPlanCacheHits,QueryPlanCacheMisses,QueryPlanCacheValidationMisses.Documentation entry for user-facing changes
Description
This PR introduces an experimental Query Plan Cache. Unlike the Query Cache, which caches query results, the Query Plan Cache caches the plan: every cache hit still executes the query and reads the current data.
Two-stage design so cached plans survive table snapshot changes:
ReadFromMergeTreeis replaced with a storage-independentReadFromTableStepcarrying the table name, the columns to read,FINAL/SAMPLEmodifiers and an explicitPREWHERE. Parts, marks and other snapshot state are stripped before serialization.resolveStoragesrebinds eachReadFromTableStepto the current storage snapshot, with the thread count derived from the current free memory.Cache key
ast_identity), so queries differing only in aliases do not collide.isSettingIgnoredInQueryPlanCachefor the excluded ones;extremes,max_rows_to_sort,max_bytes_to_sortare not excluded because they are baked into plan steps).The key has no user or role: plans are shared between users.
Validation on every hit
PREWHERE) its type, default kind and expression. For queries with a wildcard (*,COLUMNS(...)) the names and kinds of all table columns are compared as well. A mismatch is a validation miss and the query is re-planned.SELECTaccess is checked again for the current user; a revoked grant surfaces asACCESS_DENIED.Eligibility (all must hold)
SELECTfrom exactly one direct, local, non-systemMergeTree-family table (noJOIN,UNION, views, table functions, subqueries,IN <table>,CREATE ... AS SELECT).additional_table_filters/additional_result_filter, no parallel replicas, no non-deterministic functions.Relation to plan serialization
This PR builds on
QueryPlan::serialize/deserialize(used for distributed plans and parallel replicas).universalizePlan/materializePlanadd the storage-independent layer needed to reuse a plan across snapshots. Cross-link: RFC #93812, plan-v3 part 2 #97261.Files of interest
src/Interpreters/Cache/QueryPlanCache.{h,cpp}— cache, key, dependency structuressrc/Interpreters/Cache/QueryPlanCacheUtils.{h,cpp}— eligibility, key construction, dependency capture and validation, access check on hitsrc/Interpreters/{universalize,materialize}Plan.{h,cpp}— pre-serialization / post-deserialization passessrc/Interpreters/executeQuery.cpp— lookup and insertiondocs/concepts/features/performance/caches/query-plan-cache.mdx— user-facing documentationNote
Medium Risk
Introduces a new cross-query cache that injects serialized plans into
executeQuery, touching planning/execution, access checks, and query plan serialization; while gated behind an experimental setting, cache-key/invalidations and plan materialization could cause subtle correctness or security regressions if wrong.Overview
Adds an experimental query plan cache for eligible
SELECTqueries that reuses a previously builtQueryPlanto skip repeated planning, with new settings (allow_experimental_query_plan_cache, per-userquery_plan_cache_size_in_bytes_quota) and server config knobs (query_plan_cache.*).Integrates the cache into
executeQueryby building a cache key (AST + semantic settings hash + table schema version/hash + user/roles + row-policy hash), rejecting nondeterministic queries/subqueries/system tables/views/remote tables, revalidatingSELECTaccess on cache hits, and serializing/universalizing plans on misses for storage.Extends query plan serialization to pass version through step (de)serialization, updates
ReadFromTableStepto persist explicitPREWHERE, adds new metrics/events andSYSTEM DROP QUERY PLAN CACHEprivilege/command, and includes unit/integration/stateless tests covering hits/misses, invalidation, ACL revocation, and runtime config reload behavior.Reviewed by Cursor Bugbot for commit 3d2780c. Bugbot is set up for automated code reviews on this repo. Configure here.
Workflow [PR]
Sync PR [sync-upstream/pr/99309]