Repository navigation
Conversation
`buildSelectQueryInfo` eagerly called `queryNodeToSelectQuery(query_tree)`, which invokes `QueryNode::toAST` to recursively rebuild a full parallel AST. On the analyzer path this AST is mostly unused: it is read only to build the query result cache key and the aggregation hash-table stats key, and by a few storages (`StorageMerge`, `StorageDistributed`) that rebuild it from the query tree themselves. The eager rebuild also runs once per query node, so a nested subquery's AST is rebuilt at the outer level and again when that subquery is planned. Defer it: `SelectQueryInfo::query` is now materialized lazily from the stored `query_tree` on first access. The public field is replaced by `getQuery` / `setQuery` accessors (with a non-const `getQuery` overload for the legacy `TreeRewriter::analyzeSelect` path that rewrites the AST in place), and a `query_is_lazy` flag scopes lazy materialization to `buildSelectQueryInfo` so `getQuery` returns null in exactly the cases the old code did. In `Planner`, the cache-key AST is materialized only when the query result cache may be used. For the common case (a plain `MergeTree` `SELECT` without the query result cache) the parallel AST is now never built. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nfo-ast Resolve conflict in src/Interpreters/ConcurrentHashJoin.cpp: master removed the preCalculateCacheKey / calculateCacheKey(TableJoin) helpers (unused join cache key); the .query->getQuery() migration there was moot, so master's deletion is taken. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [3ce599f] Summary: ✅
AI ReviewSummaryThis PR defers Findings
Tests
Final VerdictStatus: Minimum required actions: avoid the remaining unnecessary lazy-AST materialization in cache-subquery and |
| if (local_can_use_cache) | ||
| { | ||
| settings_copy = settings; | ||
| ast = select_query_info.getQuery(); |
There was a problem hiding this comment.
This still forces queryNodeToSelectQuery for subqueries that will not use the planner-level query cache. A concrete path is an outer query with use_query_cache = 1 and the default query_cache_for_subqueries = 0: executeQuery sets Context::getCanUseQueryResultCache, so each subquery planner gets can_use_query_result_cache = true; shouldUseQueryCacheForSubquery then correctly returns false, but local_can_use_cache remains true and this line materializes the AST anyway. The later read/write cache blocks are both gated by should_cache, so the AST is not used after paying the rebuild cost. Please gate the settings_copy/ast initialization on should_cache (or otherwise avoid calling getQuery when only the outer query cache flag is set).
Replace the `query_is_lazy` flag with a `std::function<ASTPtr()> query_ast_builder`. `getQuery` materializes the AST by invoking the builder on first access; `setQuery` clears it; `setLazyQuery` installs it. `buildSelectQueryInfo` installs a builder that captures `query_tree` by value and calls `queryNodeToSelectQuery`. This removes the `Storages -> Planner` dependency: SelectQueryInfo.cpp no longer includes Planner/Utils.h or calls queryNodeToSelectQuery directly. Behavior is unchanged (null-semantics, copyability, and lazy timing are all preserved). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| select_query_info.query_tree = query_tree; | ||
| /// Defer `queryNodeToSelectQuery(query_tree)` (an expensive full AST rebuild) until the AST is | ||
| /// actually needed. `getQuery` materializes it on first access from `query_tree`. | ||
| select_query_info.setLazyQuery([query_tree] { return queryNodeToSelectQuery(query_tree); }); |
There was a problem hiding this comment.
This PR is categorized as a Performance Improvement, but the available description/report only explains why deferring queryNodeToSelectQuery should help; it does not show a before/after measurement or a focused benchmark for the promised common case. Please attach numbers from an appropriate query/planner benchmark (or add a performance test) that demonstrates the intended reduction, especially because several paths still call getQuery and materialize the AST.
…alyzer path On the analyzer path the AST built by queryNodeToDistributedSelectQuery is unused: ClusterProxy::executeQuery clones query_tree, SelectStreamFactory::createForShard rebuilds the per-shard AST from the tree, and the no-shards cases return early. Install it via setLazyQuery so the toAST rebuild + recursive alias dedup runs only if a consumer (e.g. the legacy path) actually calls getQuery(). Behavior is unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| ASTPtr & SelectQueryInfo::getQuery() | ||
| { | ||
| if (!query_ast && query_ast_builder) | ||
| query_ast = query_ast_builder(); |
There was a problem hiding this comment.
Maybe make query_ast_builder mutable and drop after the first call?
…er path ReadFromMergeTree's constructor calls query_info.isFinal() unconditionally. For a plain analyzer MergeTree read (e.g. SELECT * FROM mt) table_expression_modifiers is nullopt, so isFinal() fell through to getQuery() and materialized the AST via queryNodeToSelectQuery - defeating the lazy-AST optimization on the main common case. On the analyzer path FINAL and SAMPLE are carried by table_expression_modifiers (the AST's final/sample_size/sample_offset are derived from them in addTableExpressionInSelectQuery), so their absence means no FINAL/SAMPLE. Answer from query-tree state (query_tree is set only on the analyzer path) instead of materializing the AST, in SelectQueryInfo::isFinal, MergeTreeDataSelectExecutor sampling setup, and ReadFromMergeTree::isQueryWithSampling. The legacy path (no query_tree) still reads the AST. Behavior is unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
StorageMerge::createPlanForTable forces FINAL for storages with needRewriteQueryWithFinal (e.g. nested ReplacingMergeTree of MaterializedPostgreSQL/MaterializedMySQL) by calling setFinal() on the materialized AST, while table_expression_modifiers stayed nullopt. Since SelectQueryInfo::isFinal now answers from modifiers on the analyzer path (and no longer consults the AST), the forced FINAL was invisible to the nested read, which then ran non-FINAL and could return duplicate/stale rows. Also set table_expression_modifiers with has_final=true here, mirroring the needRewriteQueryWithFinal handling in PlannerJoinTree, preserving any existing SAMPLE ratios. This is the canonical analyzer source of truth for FINAL. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Per review feedback: remove the added doc comments in src/Storages/SelectQueryInfo.h, collapse the remaining added comments to one line each, and avoid the ; symbol in them. Comments only, no logic change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| /// | ||
| /// And for this we need to return FetchColumns. | ||
| if (const auto * select = query_info.query->as<ASTSelectQuery>(); select && (hasJoin(*select) || hasArrayJoin(*select))) | ||
| if (const auto * select = query_info.getQuery()->as<ASTSelectQuery>(); select && (hasJoin(*select) || hasArrayJoin(*select))) |
There was a problem hiding this comment.
This still materializes the parent query AST for every analyzer StorageMerge read. PlannerJoinTree calls getQueryProcessingStage with the lazy SelectQueryInfo, so this getQuery runs queryNodeToSelectQuery just to check JOIN / ARRAY JOIN; later getModifiedQueryInfo rebuilds per-child ASTs from the query tree anyway. The same eager parent AST is then also reused by the sampling precheck below. That leaves StorageMerge outside the deferred-materialization contract even though this PR calls it out as a storage that rebuilds the AST itself. Please answer these checks from query_tree / analyzer state on the analyzer path, and keep the AST fallback only for the legacy path.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 192/229 (83.84%) · Uncovered code |
|
Dear @KochetovNicolai, 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. |
|
Before/after numbers: on current master, skipping the query AST saves about 1.5% on a 10000-key UInt64 The branch last merged master on 2026-06-30, so I measured with a minimal stand-in (patch below): The conversion cost is dominated by large constants, so the test uses long literal
The x86 column differs in host as well as base; its two For the rebase: on current master, Stand-in patch (measurement only)diff --git a/src/Planner/Planner.cpp b/src/Planner/Planner.cpp
index ec7d67bbe2c..861ad775757 100644
--- a/src/Planner/Planner.cpp
+++ b/src/Planner/Planner.cpp
@@ -867,6 +867,10 @@ void Planner::buildPlanForQueryNode()
if (should_cache && !query_result_cache)
should_cache = false;
+ /// `buildSelectQueryInfo` skips the query AST when no storage reads it; the cache key needs it.
+ if (should_cache && !ast)
+ ast = queryNodeToSelectQuery(query_tree);
+
/// For explicit per-subquery opt-in, we track cache eligibility locally
/// without mutating the shared query context (which would leak to the outer query).
bool local_can_use_cache = can_use_query_result_cache || should_cache;
diff --git a/src/Planner/Utils.cpp b/src/Planner/Utils.cpp
index 3085ffba556..ced9f4e6262 100644
--- a/src/Planner/Utils.cpp
+++ b/src/Planner/Utils.cpp
@@ -564,14 +564,41 @@ QueryTreeNodePtr replaceTableExpressionsWithDummyTables(
return query_node->cloneAndReplace(replacement_map);
}
+namespace
+{
+
+/// `SelectQueryInfo::query` is read only by storages that forward or rewrite the query (Distributed, Merge,
+/// cluster table functions, external databases, `numbers`-like sources) and by `SelectQueryInfo::isFinal`
+/// when the query-level `FINAL` applies to all joined tables. Building it converts every node of the query
+/// tree, including the whole value of each constant (a long literal `IN` list is materialized again from its
+/// column), so it is skipped when only `MergeTree` tables are read.
+bool needsQueryAST(const QueryTreeNodePtr & query_tree, bool apply_query_level_final_if_no_modifiers)
+{
+ if (apply_query_level_final_if_no_modifiers)
+ return true;
+
+ const auto & query_node = query_tree->as<const QueryNode &>();
+ for (const auto & table_expression : extractTableExpressions(query_node.getJoinTreeNodeTyped()))
+ {
+ const auto * table_node = table_expression->as<TableNode>();
+ if (!table_node || !table_node->getStorage()->isMergeTree())
+ return true;
+ }
+
+ return false;
+}
+
+}
+
SelectQueryInfo buildSelectQueryInfo(const QueryTreeNodePtr & query_tree, const PlannerContextPtr & planner_context)
{
SelectQueryInfo select_query_info;
- select_query_info.query = queryNodeToSelectQuery(query_tree);
select_query_info.query_tree = query_tree;
select_query_info.planner_context = planner_context;
select_query_info.apply_query_level_final_if_no_modifiers
= planner_context->getQueryContext()->getSettingsRef()[Setting::analyzer_compatibility_apply_final_to_all_joined_tables];
+ if (needsQueryAST(query_tree, select_query_info.apply_query_level_final_if_no_modifiers))
+ select_query_info.query = queryNodeToSelectQuery(query_tree);
return select_query_info;
}
Method and checks
|
buildSelectQueryInfoeagerly rebuilt a full AST from the query tree viaQueryNode::toAST, but on the analyzer path that AST is mostly unused (query result cache key, aggregation stats key, and a few storages that rebuild it themselves), and it was rebuilt once per query node.SelectQueryInfo::queryis now materialized lazily fromquery_treeon first access (getQuery/setQuery), so a plainMergeTreeSELECTnever builds it.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Defer materialization of the query AST in the analyzer's query planner.
buildSelectQueryInfono longer eagerly rebuilds the full AST from the query tree viaQueryNode::toAST; it is reconstructed lazily only when needed (e.g. the query result cache key), so a plainSELECTfrom aMergeTreetable no longer pays for an AST it does not use.