Repository navigation
Make fallback decision reach nested plans (sets, views, scalars) - #119986
Conversation
|
Workflow [PR], commit [be52e17] Summary: ✅
AI ReviewSummaryThis PR propagates the PR Metadata
Findings❌ Blockers
Final Verdict❌ Changes requested - the LLVM Coverage ReportMeasured on commit be52e17.
Changed lines: Changed C/C++ lines covered: 87/88 (98.86%) · Uncovered code |
groeneai
left a comment
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units1142 translation units recompiled, 7664 s compile time in total, 1142 of them have a recent master baseline. |
|
@groeneai thanks, all four addressed (in the next push).
|
|
Checked the counter chain and your call stands. On the second point, agreed: with the hunk dropped, the pruning gap on that I verified the rest on 1b97263: the gtest is back to master, the |
1919bf0 to
b2418ff
Compare
| 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). |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
| 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; } |
There was a problem hiding this comment.
I would add some regular checker name like didFallBackToLocal or haveFallenBackToLocal.
There was a problem hiding this comment.
I will integrate this comment
|
|
||
| void InterpreterSelectQueryAnalyzer::applyDistributedPlanFallbackIfNeeded() | ||
| { | ||
| if (!context->getSettingsRef()[Setting::make_distributed_plan]) |
There was a problem hiding this comment.
To me it looks like we are checking the same condition in applyDistributedPlanFallbackToLocal
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
@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
- 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:ClickHouse/src/Planner/Planner.cpp
Line 2761 in c3db813
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.
- 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.
- 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]) |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
| 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; } |
There was a problem hiding this comment.
I will integrate this comment
c3db813 to
440b362
Compare
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:
The query consists of two main
QueryPlans (outer and scalar subqueries), each with its own 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,
FutureSetFromSubquerywhich would be built from that TableNode's tree would then be built withmake_distributed_plan=1.This PR fixes it by collecting all contexts in
QueryPlanResourceHolderand 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):
Improves #116487
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a case where
make_distributed_planfell back to local execution for the outer query but stillbuilt inner
IN-subquery sets as distributed plans inside views, scalar subqueries,GLOBAL INsubqueries,
Distributedshard plans, materialized CTEs andTimeSeriesreads.Workflow [PR]
Sync PR [sync-upstream/pr/119986]
Version info
26.10.1.449-master(included in26.10and later)