Skip to content

Make fallback decision reach nested plans (sets, views, scalars) - #119986

Merged
antoniofilipovic merged 16 commits into
masterfrom
afilipovic-proper-fallback-full-plan
Sep 22, 2026
Merged

antoniofilipovic merged 16 commits into
masterfrom
afilipovic-proper-fallback-full-plan

Conversation

@antoniofilipovic

@antoniofilipovic antoniofilipovic commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

Closes: #119466

Before the fix we have decided on QueryPlan level as a unit whether to distribute or not. One query can have many QueryPlans built during preparation of the plan. However, when we decide that we will fallback for a certain plan, its sets could still distribute (IN ...) due to wrong decision propagation through contexts.

Example here:

SELECT (SELECT count() FROM t WHERE x IN (SELECT x FROM t2 WHERE x < 60000));

The query consists of two main QueryPlans (outer and scalar subqueries), each with its own decision:

outer plan            SELECT (<constant>)                      -> falls back: ReadFromSystemOne
   |
   | evaluated during analysis, result becomes a constant
   v
scalar plan           SELECT count() FROM t WHERE x IN (...)   -> falls back: global GROUP BY limit
   |
   | x IN (subquery): the set is built when the scalar plan runs, by a separate plan
   v
  [IN set source plan]    SELECT x FROM t2 WHERE x < 60000         -> part of the scalar plan (child plan under its
                                                                  DelayedCreatingSets step), covered by the scalar's decision

IN set source plan would be still distributed although decision on scalar subquery QueryPlan level would be not to distribute: SELECT count() FROM t WHERE x IN (SELECT x FROM t2 WHERE x < 60000).
This is mostly a semantic issue, but somehow in the PR it was decided that fallback decision should reach the nested plans, however it was not properly implemented.
Later when we introduce some CBO to decide whether we should execute (i.e. IN sets) as distributed inside query plans, we might go back to something more flexible, with proper decision propagation.

Bug stems from the fallback decision which was written on interpreter's context and we traversed QueryTreeNodePtr tree to apply fallback to all other contexts to force whole plan to fallback to local decision. However, during the build of some query plans which contains subplan, interpreters which build such subplans make the copy of the main interpreter's context. After the build, QueryNodeTree is destroyed, the plan is extracted in the steps and context cannot be reached through walk of QueryNodeTreePtr alone. Examples contain following trees: executeSubqueryNode (GLOBAL IN), the scalar subquery evaluator, StorageView::readImpl.

In such cases, when fallback decision is applied on main plan, we could not flip back context for subplan on QueryNodeTreePtr. In the example of subquery, FutureSetFromSubquery which would be built from that TableNode's tree would then be built with make_distributed_plan=1.

This PR fixes it by collecting all contexts in QueryPlanResourceHolder and iterating over all contexts on the fallback and flipping the flag for each of those during the build of QueryPlan.

One fix could be to traverse the steps as steps also hold those contexts. But due to some other cases, where additional context's are made along the way and not accessible through the steps, we decided to go this route.

Changelog category (leave one):

  • Bug-fix

Improves #116487

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

Fixed a case where make_distributed_plan fell back to local execution for the outer query but still
built inner IN-subquery sets as distributed plans inside views, scalar subqueries, GLOBAL IN
subqueries, Distributed shard plans, materialized CTEs and TimeSeries reads.


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

Version info

  • Merged into: 26.10.1.449-master (included in 26.10 and later)

@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [be52e17]

Summary: ✅


AI Review

Summary

This PR propagates the make_distributed_plan fallback verdict into more nested subplans so queries that already fell back to local execution do not later rebuild inner IN subqueries as distributed plans. The planner-owned parked-plan cases in the diff look addressed, but ReadFromMerge still has a remaining child-local carrier where the fallback is only memoized on the child QueryPlan and is not written back to the copied contexts that later source-step analysis still reads.

PR Metadata
  • Changelog category is not using a template value. Replace - Bug-fix with - Bug Fix.
  • Changelog entry is required for Bug Fix, and the current text is specific and user-readable; no content change is needed there.
Findings

❌ Blockers

  • [src/Storages/StorageMerge.cpp:829-855] getChildPlanOptimizationSettings now replays the child verdict from QueryPlan::distributed_plan_decision, but the child's copied contexts are still not registered as distributed-plan decision contexts. createChildrenPlans builds children on modified_context (src/Storages/StorageMerge.cpp:1181-1199), direct reads capture that context in their source steps (src/Storages/StorageMerge.cpp:1873-1880), and later filter/index analysis still consults the live step context when it builds sets (src/Processors/QueryPlan/ReadFromMergeTree.cpp:3247-3268, src/Storages/VirtualColumnUtils.cpp:72-109). When a child falls back on its own unsupported shape, child_plan.applyDistributedPlanFallbackToLocal records FellBack but never flips that captured modified_context, so a child-owned nested IN or row-policy set can still re-enter convertSetSourceForDistributedPlan after the child has already gone local. Suggested fix: register each child's modified_context with addDistributedPlanDecisionContext when the child plan is created, and add a regression where a Merge child falls back while the child itself owns the nested set carrier.
Final Verdict

❌ Changes requested - the StorageMerge child path can still read make_distributed_plan = 1 from its copied contexts after the child has already fallen back, so the PR does not yet enforce a consistent local-only verdict across that full plan shape.

LLVM Coverage Report

Measured on commit be52e17.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 87/88 (98.86%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 14, 2026
Comment thread src/Processors/QueryPlan/QueryPlan.h Resolved

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The mechanism reads right to me: registering the mutable contexts on the plan and handing them over at every site where a subplan is kept aside instead of united (Planner.cpp:2181, CollectMaterializedCTE.cpp:185, PlannerCorrelatedSubqueries.cpp:1288/1336, resolveStorages.cpp:341, StorageTimeSeries.cpp:747) is much more robust than the query-tree walk it replaces. Four things I would want before merge.

1. Nothing exercises the new path. The loop that writes the decision runs only on the fallback branch, right after distributed_plan_decision = DistributedPlanDecision::FellBack. The two new gtest lines pin the opposite branch:

query_plan.applyDistributedPlanFallbackToLocal(optimization_settings);
ASSERT_TRUE(optimization_settings.make_distributed_plan);

ASSERT_TRUE passing means the plan was accepted, so the call returned before the loop. And the gtest builds its plan by hand, never calling addDistributedPlanDecisionContext, so resources.distributed_plan_decision_contexts is empty there in either branch: deleting the whole loop from applyDistributedPlanFallbackToLocal keeps this test green. The PR also has no file under tests/queries/ (0 of 13 changed files), so none of the carriers from #119466 is pinned.

An oracle for it already exists in the tree: tests/queries/0_stateless/05045_distributed_plan_fallback_to_local.sql asserts max(ProfileEvents['DistributedPlanLocalExecution']) = 0 on the query's own query_log row, keyed by log_comment, and that event is incremented once per distributed plan executed in process (DistributedPlanExecutor.cpp:2065, the no-host-map branch of createDistributedQueryExecutor). So with make_distributed_plan = 1, distributed_plan_execute_locally = 1, your reproducer from #119466 plus one query per carrier (view, scalar subquery, GLOBAL IN, Distributed local shard, materialized CTE) should read > 0 while the inner set still builds as a distributed plan, and = 0 once the decision reaches it. I have not run it, so worth confirming each case reddens without the src changes: that way a regression in one carrier fails on its own row instead of all of them leaning on the outer decision.

2. The StorageDistributed::getFilterFromQuery hunk is on an unrelated path. It is reached only from distributedWriteFromClusterStorage, i.e. INSERT INTO <Distributed> SELECT FROM <*Cluster> under parallel_distributed_insert_select, which takes no fallback decision. What does that plan do today with make_distributed_plan = 1? QueryPlan::optimize returns early before addStepsToBuildSets / resolveMaterializingCTEs in that case, so I would expect either a missing filter (no shard pruning on that INSERT SELECT) or the Found multiple source steps for query logical error just below. If it is user reachable it deserves a case of its own and makes this more than an improvement; if it is not, the comment saying why is worth more than the current wording.

3. The new QueryPlan::optimize comment promises a throw I cannot find: "otherwise this throws a logical error, unless the plan already contains logical exchanges". optimize has no such throw. With make_distributed_plan set it early-returns, and the planContainsLogicalExchange guard I found (optimizeTree.cpp:647) gates materializeConstantsForSetOperationBranches, not a throw. If it comes from a cascades or exchange pass, naming that pass helps; otherwise the observable consequence is the silent skip of set and CTE expansion, which is the more useful thing to state.

4. Two small ones. addDistributedPlanDecisionContext's parameter is marked [[maybe_unused]] while the body uses it (leftover from an earlier version?). And #include <ranges> in QueryPlan.cpp has no ranges:: or views:: user in the file; both added includes also sit inside the project-header block rather than with the other system and fmt includes.

@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing be52e173e with master 3c973e961 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 06ecf6925; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

1142 translation units recompiled, 7664 s compile time in total, 1142 of them have a recent master baseline.

Job report

@antoniofilipovic

antoniofilipovic commented Sep 15, 2026 •

Copy link
Copy Markdown
Member Author

@groeneai thanks, all four addressed (in the next push).

  1. Test: 05185_distributed_plan_fallback_contexts_stress.sql, one row per carrier, tasks summed over the query family because a shard-side set build lands on the shard's own query_log row. Each row also prints the reasons the initiator and the shard queries logged when they fell back, from system.text_log. Built once with master src plus the test: 10 of 27 rows red (view 9, scalar 9, scalar in view 9, Distributed local shard 18, serialized shard plan 18, shard query text 9, nested set in a serialized plan 18, GLOBAL IN 9, GLOBAL IN over a view 9, TimeSeries filter set 9). The nested set source, CTE and correlated rows stay green on master because the old tree walk reached them; they guard the hand-over sites that replace the walk. The gtest hunks are reverted.

    DistributedPlanLocalExecution cannot serve here: it is incremented only in the !task_to_host_map branch, which distributed_plan_execute_locally selects (QueryPlan.cpp:1015). 05045 sets that to 1 in every query, this test does not, so the counter would read 0 for a real leak and the positive controls would prove nothing. The EXPLAIN rows are covered only by "did not throw", all counters fire at execution.

  2. Dropped. The hunk was there for the same uncommitted guard.

  3. Reworded. optimize throws nothing; a plan that skipped the decision keeps its Delayed* steps and fails at pipeline build (CreatingSetsStep.cpp:331).

  4. Both fixed. <fmt/ranges.h> kept for fmt::join at QueryPlan.cpp:968, moved to the third-party group.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-improvement Pull request with some product improvements labels Sep 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Checked the counter chain and your call stands. TaskToHostMap has a single construction site, the execute_locally ? nullptr : ... ternary you cite, and that pointer is the only one reaching createDistributedQueryExecutor (ReadFromDistributedPlanSource.cpp:50), whose !task_to_host_map branch holds the single increment. So with the setting at its default DistributedPlanLocalExecution cannot fire at all: 0 for a leak and 0 for a correct fallback. Summing DistributedPlanRemoteTasks over the query family is the right oracle for a test that keeps the real dispatch path, and 10 rows red on master with real task counts answers the liveness point I raised. For the rows that stay green on master the printed fallback reasons carry content of their own, so nothing is outstanding on my first point.

On the second point, agreed: with the hunk dropped, the pruning gap on that INSERT ... SELECT path is pre-existing and I am not asking for anything there.

I verified the rest on 1b97263: the gtest is back to master, the optimize comment now names the pipeline-build failure instead of a throw, [[maybe_unused]] and <ranges> are gone, and <fmt/ranges.h> is in its own group. Nothing further from me.

@antoniofilipovic antoniofilipovic changed the title Apply fallback decision on full plan instead only on part of it Make fallback decision propagate through QueryPlan's caputured contexts Sep 15, 2026
@antoniofilipovic antoniofilipovic changed the title Make fallback decision propagate through QueryPlan's caputured contexts Make fallback decision propagate onto QueryPlan's sets Sep 15, 2026
@antoniofilipovic antoniofilipovic changed the title Make fallback decision propagate onto QueryPlan's sets Make fallback decision reach nested plans (sets, views, scalars) Sep 15, 2026
Comment thread src/Planner/Planner.cpp Resolved
@antoniofilipovic
antoniofilipovic marked this pull request as ready for review September 15, 2026 15:55
Comment thread src/Storages/StorageMerge.cpp Outdated
return optimization_settings;

/// The child's verdict lives on the plan, not in the context these settings come from (call 2
/// above). An undecided child decides now, on the setting of its own context (call 1).

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 now memoizes the child verdict on child_plan, but the child's own copied context is still never registered for fallback. createChildrenPlans builds each child on modified_context (src/Storages/StorageMerge.cpp:1860-1864 / 1891-1898), then only does child.plan.addInterpreterContext(modified_context) at line 1401 before calling this helper at line 1422. If applyDistributedPlanFallbackToLocal rejects the child here, modified_context still keeps make_distributed_plan = 1.

That leaks through exactly the path this PR is trying to close: second-pass index analysis and child-owned delayed sets still read the flag live from that copied context. A concrete carrier is the row-policy path: RowPolicyData::addFilterTransform adds its own DelayedCreatingSetsStep at src/Storages/StorageMerge.cpp:1997, so a Merge child that falls back on its own unsupported reason can still re-enter distributed set planning while building that child-owned IN set.

The new tests do not hit this shape: 05185_dpc_08_merge_table forces children local via queryHasSubquerySets, while 05218 7 keeps the child distributed. I think the child needs the same treatment as the top-level interpreter path: register modified_context as a distributed-plan decision context when the child plan is created, and add a regression where the child itself falls back and owns the IN set.

@alesapin alesapin left a comment

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.

It looks like we are adding context into distributed_plan_decision_contexts very conservatively, I suspect there can be multiple copies of the same context.

Comment thread src/Processors/QueryPlan/QueryPlan.h Outdated
bool staysDistributed() const { return distributed_plan_decision == DistributedPlanDecision::Distributed; }

/// True once `applyDistributedPlanFallbackToLocal` rejected this plan, which then runs locally.
bool fellBackToLocal() const { return distributed_plan_decision == DistributedPlanDecision::FellBack; }

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.

I would add some regular checker name like didFallBackToLocal or haveFallenBackToLocal.

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.

I will integrate this comment


void InterpreterSelectQueryAnalyzer::applyDistributedPlanFallbackIfNeeded()
{
if (!context->getSettingsRef()[Setting::make_distributed_plan])

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.

To me it looks like we are checking the same condition in applyDistributedPlanFallbackToLocal

@antoniofilipovic antoniofilipovic Sep 22, 2026 •

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.

applyDistributedPlanFallbackToLocal can be called from buildQueryPipeline, so it needs same check for make_distributed_plan as this one. The difference is that applyDistributedPlanFallbackToLocal records the decision on QueryPlan and on the contexts it captures.

/// The child's verdict lives on the plan, not in the context these settings come from (call 2
/// above). An undecided child decides now, on the setting of its own context (call 1).
if (child_plan.staysDistributed())
optimization_settings.make_distributed_plan = true;

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.

TBH I don't understand why we have this if/elseif/else and why everything cannot be resolved inside applyDistributedPlanFallbackToLocal. Maybe it make sense to add more clear context.

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.

I see. The problem is that the function getChildPlanOptimizationSettings is called with two different contexts, and I am not confident enough to patch the whole fix here, hence this small workaround. Basically, when the child plan is created in StorageMerge.cpp it uses modified_context, copy of outer plan's context. At that point make_distributed_plan can still be set to 1, as we did not call yet on outer plan applyDistributedPlanFallbackToLocal.

Since the child of ReadFromMerge uses at this point make_distributed_plan=1 to create a query plan and apply fallback for that child plan on its own, it can insert Gather/Exchange operators as it can rightfully distribute. However, the outer plan does fallback, and now when the function getChildPlanOptimizationSettings is called second time, then it is called with context of outer plan (bug in my opinion), but it has prerecorded decision of distributing that child plan. So in this case, we need to reapply that decision here.

I tried to make comment above getChildPlanOptimizationSettings to explain what is happening here. the proper fix might be to just store the modified_Context in the ChildPlan struct and use it from that point on. However, I would like to keep the two fixes at least in a different PRs so I know what broke what and I do not have to revert this whole PR which is protected behind make_distributed_plan flag.

NB: distribution of child plan is okay to happen while outer plan falls back and Sasha Gololobov asserted that behavior in one test, so it is normal to happen.

@antoniofilipovic antoniofilipovic left a comment

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.

@alesapin thanks for review. I figure this is a bit complex to follow but the idea is the following.
We want to keep the contexts of outer plan and child plans it creates which carry the decision of whether or not to fallback to local inside the outer plan. Once the outer plan decides to fallback, we can easily propagate that decision to child plans in that case

There are 3 different paths for this

  1. Child plan is created and then we call outer_plan = std::move(child_plan). In that case child plan is integrated in the main plan, and the QueryPlanResourceHolder::append collects all child plans contexts.
    Example:
    query_plan = std::move(join_tree_query_plan.query_plan);

Covered by this alone: views, a scalar subquery inside a view, Buffer, the local shard of a Distributed table, Merge children built through an interpreter, UNION branches, both sides of a JOIN, subqueries in FROM. That is why the PR touches so few files for so many shapes.

  1. The child plan is never moved into the parent's node list. They sit inside a FutureSetFromSubquery, a MaterializedCTE, or a ReadFromTimeSeriesStep. So the resources do not travel. These are the sites that got one explicit line, takeContextsFrom.

The kept-aside plans are only touched during optimize, by DelayedCreatingSetsStep::makePlansForSets and DelayedMaterializingCTEsStep::optimizePlans, or at execution by buildSetInplace. By then the fallback is decided and we can be confident that the context for that child plan carries the correct decision due to taking contexts from them.

  1. The child is a root of its own. Examples include, the scalar subquery which is executed during analysis, executeSubqueryNode which runs the GLOBAL IN body, each Merge child takes its own verdict. Each is a separate decision.

I could not prove that this is exhaustive list, but I forced claude to write as many tests as possible to enumerate it, hopefully covering majority of them for now.

The way the feature is designed it would unfortunately be whack-a-mole because we do not run a plan from start once we decide the fallback, but decide on fallback mid plan and then need to propagate the decision.


void InterpreterSelectQueryAnalyzer::applyDistributedPlanFallbackIfNeeded()
{
if (!context->getSettingsRef()[Setting::make_distributed_plan])

@antoniofilipovic antoniofilipovic Sep 22, 2026 •

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.

applyDistributedPlanFallbackToLocal can be called from buildQueryPipeline, so it needs same check for make_distributed_plan as this one. The difference is that applyDistributedPlanFallbackToLocal records the decision on QueryPlan and on the contexts it captures.

/// The child's verdict lives on the plan, not in the context these settings come from (call 2
/// above). An undecided child decides now, on the setting of its own context (call 1).
if (child_plan.staysDistributed())
optimization_settings.make_distributed_plan = true;

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.

I see. The problem is that the function getChildPlanOptimizationSettings is called with two different contexts, and I am not confident enough to patch the whole fix here, hence this small workaround. Basically, when the child plan is created in StorageMerge.cpp it uses modified_context, copy of outer plan's context. At that point make_distributed_plan can still be set to 1, as we did not call yet on outer plan applyDistributedPlanFallbackToLocal.

Since the child of ReadFromMerge uses at this point make_distributed_plan=1 to create a query plan and apply fallback for that child plan on its own, it can insert Gather/Exchange operators as it can rightfully distribute. However, the outer plan does fallback, and now when the function getChildPlanOptimizationSettings is called second time, then it is called with context of outer plan (bug in my opinion), but it has prerecorded decision of distributing that child plan. So in this case, we need to reapply that decision here.

I tried to make comment above getChildPlanOptimizationSettings to explain what is happening here. the proper fix might be to just store the modified_Context in the ChildPlan struct and use it from that point on. However, I would like to keep the two fixes at least in a different PRs so I know what broke what and I do not have to revert this whole PR which is protected behind make_distributed_plan flag.

NB: distribution of child plan is okay to happen while outer plan falls back and Sasha Gololobov asserted that behavior in one test, so it is normal to happen.

Comment thread src/Processors/QueryPlan/QueryPlan.h Outdated
bool staysDistributed() const { return distributed_plan_decision == DistributedPlanDecision::Distributed; }

/// True once `applyDistributedPlanFallbackToLocal` rejected this plan, which then runs locally.
bool fellBackToLocal() const { return distributed_plan_decision == DistributedPlanDecision::FellBack; }

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.

I will integrate this comment

@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-proper-fallback-full-plan branch from c3db813 to 440b362 Compare September 22, 2026 10:00
@alesapin alesapin self-assigned this Sep 22, 2026
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-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fallback to local execution can have inner query execute as distributed plan

4 participants