Repository navigation
Add fallback to local execution when a plan step does not support distributed execution - #116487
antoniofilipovic merged 36 commits into
Conversation
groeneai
left a comment
There was a problem hiding this comment.
Read the whole diff. One thing blocks merge outright, one merge hazard would revert three merged features, and the setting does not yet cover the half of #113687 a user is most likely to hit. The move of the check before optimization itself looks sound, and I checked that rather than just asking.
1. The base predates WITH ROLLUP / WITH CUBE / GROUPING SETS support, and the rewritten predicates still reject all three
Merge base is e3da288d (2026-08-18). Master gained since then:
ba946f6"SerializeRollupStepsomake_distributed_plansupportsWITH ROLLUP" (PR 114950), which droppedRollupStepandCubeStepfromplanHasUnsupportedDistributedStep, plusa768aab"Keep only theWITH TOTALScase in the gate test,ROLLUPandCUBEare supported now", which renamed04308_distributed_totals_rollup_cube_not_distributed.sqlto04308_distributed_totals_not_distributed.sql.6bfccba"SupportWITH CUBEandGROUPING SETSinmake_distributed_plan". On master the onlyGROUPING SETSrejection left intryMakeDistributedAggregationis the in-order one (makeDistributed.cpp:596-601); otherwise it selectsPartialAggregation.5f7a67b(PR 115426) for the Cascades two-phaseGROUPING SETSsplit.
This branch keeps typeid_cast<const RollupStep *> and typeid_cast<const CubeStep *> in planHasUnsupportedDistributedStep, rejects isGroupingSets unconditionally in hasAggregationUnsupportedStepForDistributed, and edits the pre-rename 04308 file, which no longer exists. Merging master conflicts in exactly those places, and taking this branch's side reverts the three commits and breaks 04897_distributed_plan_rollup, 04899_distributed_plan_cube and 04900_distributed_plan_grouping_sets. All three use the legacy path with make_distributed_plan = 1 and pin an EXPLAIN arm in their reference, so they fail on a changed plan rather than on an exception.
I would merge master first: makeDistributed.cpp has 27 and optimizeTree.cpp 73 commits on master since this base.
2. distributed_plan_fallback_to_local_execution does not cover rejections decided after optimization
The description says "log the reason and execute the query on the initiator instead of throwing an exception", but the fallback is decided only at the top of QueryPlan::optimize, before the passes. Three SUPPORT_IS_DISABLED throws stay reachable at the default 1:
QueryPlan.cpp:934, when the post-optimizationhasUnsupportedStepRemoteExecution(*root, false)rejects a plan that by then carries logical exchanges.assertFragmentSerializable,QueryPlan.cpp:85, called at:996.checkStepSupportedByCascadesthroughcheckCascadesSupported,optimizeTree.cpp:395, which runs inside the second pass.
That is reachable rather than theoretical, because the only two conditional isSerializable overrides in the tree both read state the optimizer writes:
AggregatingStep::isSerializableissort_description_for_merging.empty() && !explicit_sorting_required_for_aggregation_in_order(AggregatingStep.h:125-128), andsort_description_for_mergingis filled byoptimizeAggregationInOrder(optimizeTree.cpp:454), after the pre-pass has already accepted the plan.SortingStep::isSerializableis(type == Type::Full || type == Type::FinishSorting) && scatter_partitions == 0(SortingStep.h:166-169), andtypeandscatter_partitionsare set byapplyOrder(optimizeTree.cpp:773).
None of this is a regression, the same queries throw today. But the cases decidable before optimization are largely the ones a user can already see in the query text (WITH TOTALS, PASTE JOIN, GLOBAL IN, STREAM), while these are not, so the feature currently misses the part that is hard to predict. Either honour the fallback at the post-optimization site as well, which needs a copy of the pre-optimization plan to re-optimize with make_distributed_plan = false, or narrow the setting description to say it covers only rejections decided before optimization.
3. Moving the check before optimization is sound, for the record
I checked whether any other step class can make the pre-pass stricter than the post-pass. Of the non-serializable steps the planner builds before QueryPlan::optimize, only CommonSubplanStep and CommonSubplanReferenceStep are removed during optimization, by materializeQueryPlanReferences and optimizeUnusedCommonSubplans (optimizeTree.cpp:268-277), which is exactly what allow_subplan_placeholders whitelists. DelayedCreatingSetsStep is serializable (CreatingSetsStep.h:97); DelayedMaterializingCTEsStep, ReadFromRemote and ReadFromParallelRemoteReplicasStep all survive optimization on this path, so both checks see them either way. Localhost-shard inlining happens in SelectStreamFactory::createForShardImpl at plan build time, not in a pass. Worth stating that invariant next to allow_subplan_placeholders, because the whitelist has to be revisited the first time a pass starts removing some other non-serializable step.
4. Nothing exercises the new default
All seven touched test files add distributed_plan_fallback_to_local_execution = 0, so every arm keeps the old behaviour and the default-on path has no coverage at all. Two arms would fix that: one that takes the fallback and compares its result against the same query with make_distributed_plan = 0, and one asserting a supported query is still distributed (EXPLAIN distributed = 1, as 04671_make_distributed_plan_join_to_in_disabled does). The second matters more than it looks. With the fallback on, an over-rejection stops being an error and becomes a silent single-node run, so a plan-shape assertion is the only thing left that can catch one.
Cleanup
SettingsChangesHistory.cpp: the entry is in the26.8block. Master is 26.9 and already has a26.9block at line 44, so it needs moving when you merge.QueryPlan.cpp:22and:24addTotalsHavingStep.handOptimizations/Utils.h; neither is used in the file.QueryPlan.cpp:822-824declareplanHasUnsupportedDistributedStep,planHasInOrderAggregationandverifyDistributedAggregation, none of which is used there.planHasInOrderAggregationhas its definition deleted by this PR and a second stale declaration inoptimizeTree.cpp;verifyDistributedAggregationdoes not exist anywhere in the tree.hasAggregationUnsupportedStepForDistributedcan take aconst QueryPlan::Node &, and theaggregating_step &&atmakeDistributed.cpp:256is already guaranteed by the early return above it.- Typos and spacing: "beforhand", "a aggregating step", the double space in the
traversePlanForUnsupportedDistributedStepdeclaration, and the added blank lines inQueryPlan.handQueryPlanOptimizationSettings.h. - The new names read backwards at the call sites:
if (auto res = isReadFromMergeTreeSupportedForDistributed(step); res.has_value())means the read is not supported.findUnsupported...would match what the returned value means.
ad39ed5 to
0799b70
Compare
|
Workflow [PR], commit [b1cb504] Summary: ✅
AI ReviewSummaryThis PR centralizes the Missing context / blind spots
Findings
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit b1cb504.
Changed lines: Changed C/C++ lines covered: 374/431 (86.77%) · Uncovered code |
|
@groeneai please check the code again.
In general, the idea for this PR is to have static checks in one place to verify if plan can be rewritten. If there are later some optimization steps which introduce some issues which we cannot detect on unoptimized plan, we can go with approach to try make distributed plan, if the exception happens we then fall back on the normal plan. This would require having copy of the plan nodes before rewrite. I think this is in general good approach, but seems unnecessary for now as we gate in the optimization code steps which would produce unsupported distributed plan. Direct answers For
|
groeneai
left a comment
There was a problem hiding this comment.
Re-checked all of it at 6c521eb. Approving. One thing will fail Style check, the rest is cosmetic.
Verified fixed:
- The merge base is now
573230b(2026-08-26), which containsba946f6,6bfccba,a768aaband5f7a67b, soWITH ROLLUP/WITH CUBE/GROUPING SETSsupport is no longer reverted.RollupStepandCubeStepare gone from the unsupported-step check,isGroupingSetsis aLOG_TRACErather than a rejection, and the diff edits the post-rename04308_distributed_totals_not_distributed.sql. That was the blocker. - Post-optimization rejections (item 2). The two
SUPPORT_IS_DISABLEDthrows left inconvertToDistributednow carry the "the plan is already shaped for distribution, so fail closed" rationale, and the passes that could flip serializability after the decision do not run undermake_distributed_plan(aggregation_in_order, lazy materialization,optimizeJoinByShards). Good enough for me on the reachable paths. - Coverage at the new default (item 4).
05045runs three arms at the default and assertsDistributedPlanLocalExecution = 0on a fallen-back query, and04652asserts> 0on one that must still distribute. That is both directions. makeDistributed.cpp:97: the helper returns step pointers now, so theserializable: Sortingcomposition is gone. Themax_rows_to_group_byrejection names the setting again, thechildren.size() != 1return is out,ERROR OLD:is gone, theSettingsChangesHistoryentry sits in the26.9block, the commented-outvalidateSetsForDistributedPlanis a real call atQueryPlan.cpp:907, and theQueryPlanOptimizationSettings.hinclude is out ofQueryPlan.cpp.
Still open:
makeDistributed.cpp:266is a line of four spaces, left behind by removing the guard.check_cpp.shcheck 06b isgrep -Hn ' $'oversrc/, and master's copy of the file is clean, so this failsStyle checkas it stands.QueryPlan.h:21still includesQueryPlanOptimizationSettings.hnext to the forward declaration at:45. All three uses are by const reference, and 161 files undersrc/includeQueryPlan.h.QueryPlan.cpp:824-825declaresplanHasUnsupportedDistributedStepandverifyDistributedAggregation. Neither is called there, andverifyDistributedAggregationhas no definition anywhere in the tree.- "Is this a aggregating step?" appears at both
makeDistributed.cpp:240and:631. isReadFromMergeTreeSupportedForDistributedreturns a message when the read is not supported, soif (auto maybe_unsupported = ...; maybe_unsupported.has_value())at:353reads inverted.- The setting is declared with the default tier while its own text says it applies only under the experimental
make_distributed_plan; the neighbouringdistributed_plan_*settings areEXPERIMENTAL.
One thing worth a thought before the default flip lands, not necessarily in this PR. On this branch 115 stateless tests set make_distributed_plan; 3 of them assert plan shape with EXPLAIN distributed and 3 assert the execution mode through DistributedPlanLocalExecution (04746, 04652, 05045). The rest assert results only, so with the fallback on by default an over-rejection in the new pre-pass stops being a red and becomes a silent single-node green across most of that corpus. Pinning distributed_plan_fallback_to_local_execution = 0 in the stateless test profile would keep the corpus loud while the product default stays 1; 05045 would then pin = 1 on its three fallback arms. Your call.
|
Your two notes on the lazy-materialization gate and on removing the One thing that is easy to misread in the check list: that run is void, not one red check among many green ones. |
|
@groeneai answer on the last comment:
Currently, setting So I'd rather add |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units256 translation units recompiled, 2138 s compile time in total, 256 of them have a recent master baseline. |
0c881f0 to
3944529
Compare
14f96c9 to
6e2ae2e
Compare
0d8ff04 to
20d8a51
Compare
| return std::move(planner).extractQueryPlan(); | ||
| } | ||
|
|
||
| void InterpreterSelectQueryAnalyzer::applyDistributedPlanFallbackIfNeeded() |
There was a problem hiding this comment.
This only fixes the analyzer paths that go through InterpreterSelectQueryAnalyzer::buildQueryPipeline. There are still callers that take the raw analyzer plan and drive it themselves, for example executeSubqueryNode in src/Storages/buildQueryTreeForShard.cpp:598-631 and StorageDistributed::getFilterFromQuery in src/Storages/StorageDistributed.cpp:1366-1377.
Those paths never call applyDistributedPlanFallbackIfNeeded(), and QueryPlan::buildQueryPipeline / plan.optimize only flip the QueryPlanOptimizationSettings snapshot, not the query-tree contexts the already-built steps captured. So if one of those plans falls back locally (for example a GLOBAL IN subquery whose inner SELECT is not distributable and also contains a nested IN), second-pass index analysis still sees make_distributed_plan = 1 in the captured contexts and goes through the distributed PreparedSets path on what is supposed to be a local fallback. That is the same context leak the PR description says this change fixes.
I would either move the context flip into a truly shared path, or audit these out-of-band analyzer callers so they call this helper before extracting/building the plan and then build QueryPlanOptimizationSettings from interpreter.getContext() rather than the outer context.
There was a problem hiding this comment.
This is true that now we for subquery with IN or GLOBAL IN we can have a inner query which executes in distributed way, but outer query falls back to local execution. The cause is query context which is is to be propagated. Since the main goal of this PR is fallback to local execution instead of error, this will be addressed in the other PR (issue relevant here: #119466) .
| optimization_settings.make_distributed_plan = false; | ||
| /// Include the fallback decision here before call to optimize | ||
| if (child_plan.isInitialized()) | ||
| child_plan.applyDistributedPlanFallbackToLocal(optimization_settings); |
There was a problem hiding this comment.
This only records the child's fallback on the QueryPlanOptimizationSettings snapshot. For analyzer-built child plans the captured QueryNode / UnionNode contexts still keep make_distributed_plan = 1, because nothing here updates modified_context or the query tree the child plan already captured.
That recreates the same leak this PR fixes in InterpreterSelectQueryAnalyzer: if a Merge child falls back locally (for example through a nested View child) and a pushed-down filter contains IN (SELECT ...), child.plan.optimize() can still drive FutureSetFromSubquery::buildOrderedSetInplace through the distributed path on what is supposed to be a local plan. I think the fallback needs to be applied before extractQueryPlan() on the analyzer child interpreter, or this branch needs to flip the child context tree when applyDistributedPlanFallbackToLocal() returns true.
|
📊 Cloud Performance Report ✅ AI verdict: This PR reworks the make_distributed_plan pathway so that a plan which cannot be distributed falls back to local execution instead of throwing, gated by the new default-off distributed_plan_fallback_to_local_execution setting. That entire code path is only reachable when make_distributed_plan (a private preview, disabled by default) is enabled, which standard ClickBench runs do not set, so the ordinary query-execution and optimization hot paths are unchanged. The four flagged queries (Q9, Q28, Q33, Q34) all show small positive deltas (+5% to +11%) that the deterministic gates already kept within the baseline variance band as not_sure; since the diff cannot plausibly touch what these queries execute, they are downgraded as run-to-run variance. No cross-query pattern and no real regression is attributable to this change. clickbenchFlagged queries (4 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
@antoniofilipovic @groeneai @davenger — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Issue
When enabling make_distributed_plan=1, some plans which could not be distributed would throw exception SUPPORT_IS_DISABLED. Some which did not throw the exception would silently be rewritten to the local node execution. The checks producing that exception were scattered across the optimizer, some of them firing mid-transform, after exchanges were already in the plan, when there was no way back.
What this PR does:
For queries planned by the analyzer, the decision is made up front by
InterpreterSelectQueryAnalyzer::applyDistributedPlanFallbackIfNeeded, which propagates an applied fallback into the interpreter context and into every query tree node context. This becomes needed as second-pass index analysis builds IN-subquery sets readingmake_distributed_planlive from the contexts, and if not cleared from the context on fallback, we have a plan which should be executed on single node, but has IN-subquery sets built as for distributed step.On rejection the reason is logged and the query executes on the initiator instead of throwing. The new
distributed_plan_fallback_to_local_execution=0restores the exception; since make_distributed_plan means "distribute this query", setting it to 0 doubles as a per-query assertion that the query really was distributed.Also, there is no anymore silent fallback in
convertToDistributed. If we decide for distributed plan, and optimization pass introduces a node which is not serializable, exception is thrown. Reason is that optimization pass could know what can be done with the plan to keep it distributable. Checks in the optimize pass already exist, so it is easy to guard against wrong plan for distributed mode.Example of silent fallback
There were tests which expected lazy materialization to be distributed, but it can't be and it was not so it needed a fix as part of this for make_distributed_plan=1. Lazy materialization runs after static decision point and after inserting exchanges. Lazy materialization code expected format where exchanges would be inserted so lazy materialization is not applied, as it checks for specific query shape which does not support
Exchangenode. However, theFINAL PREWHERE ... LIMITshape gets no exchange at all and for distributed query non-serializableJoinLazyColumnsStepis inserted into a plan.masterbranch hid this by silently running such plans on one node and making a silent fallback. Lazy materialization and lazy FINAL are now skipped while building a distributed plan, however every fragment is again re-optimized by the executor with make_distributed_plan = 0, so the worker applies the lazy materialization optimization to its own fragment.Tests that pinned the old throws keep their coverage via distributed_plan_fallback_to_local_execution = 0 per query.
Closes: #113687
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
When
make_distributed_planis enabled in the case there is no viable option for distributed plan, the fallback to local execution happens.Workflow [PR]
Sync PR [sync-upstream/pr/116487]
Version info
26.9.1.1280(included in26.9and later)