Skip to content

Make SelectQueryInfo query AST lazy (deferred materialization) - #107743

Open
novikd wants to merge 12 commits into
masterfrom
lazy-select-query-info-ast
Open

novikd wants to merge 12 commits into
masterfrom
lazy-select-query-info-ast

Conversation

@novikd

@novikd novikd commented Jun 17, 2026

Copy link
Copy Markdown
Member

buildSelectQueryInfo eagerly rebuilt a full AST from the query tree via QueryNode::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::query is now materialized lazily from query_tree on first access (getQuery/setQuery), so a plain MergeTree SELECT never builds it.

Changelog category (leave one):

  • Performance Improvement

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. buildSelectQueryInfo no longer eagerly rebuilds the full AST from the query tree via QueryNode::toAST; it is reconstructed lazily only when needed (e.g. the query result cache key), so a plain SELECT from a MergeTree table no longer pays for an AST it does not use.

novikd and others added 2 commits June 17, 2026 15:49
`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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3ce599f]

Summary: ✅


AI Review

Summary

This PR defers SelectQueryInfo AST materialization behind getQuery / setLazyQuery. The main lazy path for plain MergeTree reads now looks fixed, including analyzer FINAL / SAMPLE handling, but the performance contract is still not fully met in cache-subquery and StorageMerge paths, and there is still no before/after evidence for a Performance Improvement.

Findings

⚠️ Majors

  • [src/Planner/Planner.cpp:2155] buildPlanForQueryNode still materializes select_query_info for subqueries that will not use the planner query cache. With outer use_query_cache = 1 and default query_cache_for_subqueries = 0, should_cache is false but local_can_use_cache remains true, so this getQuery pays the queryNodeToSelectQuery rebuild even though the read/write cache blocks are gated by should_cache.
    Suggested fix: initialize settings_copy and ast only when should_cache is true, or otherwise split "outer context may use cache" from "this query node needs a cache key".

  • [src/Storages/StorageMerge.cpp:395], [src/Storages/StorageMerge.cpp:721] StorageMerge still forces parent AST materialization on the analyzer path before it knows it needs the AST: getQueryProcessingStage calls getQuery just to check JOIN / ARRAY JOIN, and child planning calls it again for the sampling precheck before using table_expression_modifiers. This leaves StorageMerge outside the lazy-materialization contract the PR describes.
    Suggested fix: answer the JOIN / ARRAY JOIN and SAMPLE checks from query_tree / table_expression_modifiers on the analyzer path, preserving the AST fallback for the legacy path.

Tests
  • ⚠️ The PR is categorized as Performance Improvement, but neither the PR description nor the current discussion / CI summary includes before/after planner or query benchmark numbers for the promised common case. The local performance helper could not run because clickhouse-local is not available on PATH. Please attach a focused benchmark or CI performance report demonstrating reduced AST rebuild work.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: avoid the remaining unnecessary lazy-AST materialization in cache-subquery and StorageMerge paths, and provide performance evidence for the claimed improvement.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 19, 2026
Comment thread src/Planner/Planner.cpp
if (local_can_use_cache)
{
settings_copy = settings;
ast = select_query_info.getQuery();

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.

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]>
Comment thread src/Planner/Utils.cpp
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); });

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.

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]>
Comment thread src/Storages/SelectQueryInfo.cpp Resolved
ASTPtr & SelectQueryInfo::getQuery()
{
if (!query_ast && query_ast_builder)
query_ast = query_ast_builder();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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]>
Comment thread src/Storages/SelectQueryInfo.cpp Resolved
novikd and others added 5 commits June 24, 2026 12:16
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)))

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 192/229 (83.84%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

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.

@abashkeev abashkeev added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
@snelheidai

Copy link
Copy Markdown

Before/after numbers: on current master, skipping the query AST saves about 1.5% on a 10000-key UInt64 IN list, is within noise for String keys, and lowers peak memory by 0.5–0.8 MiB per query. With #132247 and #132285 also applied, the same patch measured up to 7% on x86 (String keys, use_statistics = 0). 10- and 100-key lists, a scan without IN, and INSERT ... SELECT FROM numbers (a path that still builds the AST) showed no significant change on either host.

The branch last merged master on 2026-06-30, so I measured with a minimal stand-in (patch below): buildSelectQueryInfo skips queryNodeToSelectQuery when every table expression is a MergeTree table and analyzer_compatibility_apply_final_to_all_joined_tables is off, and the Planner builds the subquery result-cache key on demand.

The conversion cost is dominated by large constants, so the test uses long literal IN lists: SELECT count() FROM t WHERE k IN (<10000 literals>) AND v > 10 AND s != '' on a 4M-row MergeTree ORDER BY k. Server time from system.query_log, base → stand-in, geometric mean of 60 paired ratios with 95% CI:

Query arm64, master 2a2f574 x86-64, master 5720d28 + #132247 + #132285
10000 UInt64 keys 54.0 → 53.0 ms, 0.983 [0.972, 0.994] 24.5 → 23.8 ms, 0.985 [0.953, 1.019]
10000 UInt64 keys, use_statistics = 0 45.6 → 44.9 ms, 0.986 [0.969, 1.003] 16.2 → 15.7 ms, 0.949 [0.908, 0.991]
10000 String keys 63.6 → 63.3 ms, 0.992 [0.973, 1.011] 28.5 → 27.1 ms, 0.960 [0.925, 0.996]
10000 String keys, use_statistics = 0 53.9 → 53.6 ms, 1.003 [0.982, 1.025] 19.6 → 18.7 ms, 0.931 [0.903, 0.959]
Peak memory per query −0.5 to −0.8 MiB −1.1 MiB (−5.0 MiB for String keys with statistics)

The x86 column differs in host as well as base; its two use_statistics = 0 rows were re-run with 80 pairs: 0.932 (String) and 0.966 (UInt64).

For the rebase: on current master, SelectQueryInfo::isFinal and the SAMPLE getters already return early when query_tree is set (only isFinal with analyzer_compatibility_apply_final_to_all_joined_tables = 1 still reads the AST), and I found no reader of SelectQueryInfo::query on the plain MergeTree read path (MergeTreeDataSelectExecutor, ReadFromMergeTree, MergeTreeWhereOptimizer, optimizeReadInOrder). The remaining readers I found are StorageDistributed, StorageMerge, IStorageCluster::read, transformQueryForExternalDatabase, the limit pushdown for numbers-like sources, getHeaderForProcessingStage for stages after FetchColumns, and the Planner subquery result-cache key.

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
  • arm64: 4-vCPU VM, Release build without LTO. Base master 2a2f574 (2026-11-21); src/Planner, src/Analyzer and src/Parsers are unchanged on current master 903285f. Candidate = base + the patch above.
  • x86-64: base master 5720d28 + Build the source AST of a literal IN set only when a remote filter reads it #132247 (0c924b0) + Parse numbers and strings in long literal lists without keyword probes and per-element ASTs #132285 (e0d8b6b); candidate = base + the same patch.
  • Tables: t_u64 (k UInt64, v UInt32, s String) with k = number * 3, and t_str with k = concat('k', toString(number * 3)), 4M rows each, OPTIMIZE FINAL. On arm64 each list holds 10000 distinct existing keys in random order.
  • Two servers, interleaved runs with the order alternated every repetition, then repeated with the binaries swapped (30 + 30 pairs). Each arm runs a fresh copy of its binary, and query results are compared before timing.
  • A 172-line script gave identical output on both binaries on both hosts. It covers FINAL with and without analyzer_compatibility_apply_final_to_all_joined_tables, remote, merge, Merge, Buffer, views, numbers, and subquery query-cache keys with query_cache_for_subqueries. On x86, 225 sampled MergeTree stateless tests also matched, apart from the order of one remote connection error.

This branch has not been deployed

No deployments
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-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants