Repository navigation
Fix No set is registered for key when reading a Distributed table through merge - #117817
Conversation
A `SELECT` that reads a `Distributed` table through a `Merge` table or the `merge` table function, and whose `GROUP BY`, `DISTINCT` or `LIMIT BY` key contains an `IN`-family function, failed with the logical error `No set is registered for key __set_<h1>_<h2>`. In a release build the query is rejected; in debug and sanitizer builds the server aborts. `ReadFromMerge` derives a `PlannerContext` per child table, and the derived constructor copies only `query_context`, `global_planner_context` and `is_ast_level_optimization_allowed`, so `prepared_sets` starts empty. When the child is a `Distributed` table, `createPlanForTable` asks it for a processing stage with that context, which reaches `StorageDistributed::isShardingKeySuitsQueryTreeNodeExpression`. That function builds an actions DAG over the query's `GROUP BY` expression, and `PlannerActionsVisitor` resolves the `IN` by looking the set up in the context it was handed. `PlannerActionsVisitor.h` states as a precondition that the sets for `IN` functions are already collected in the planner context, and `CollectTableExpressionData.h` names this exact error as the consequence of breaking it. The check did not satisfy it. Registering the expression's sets first is what the three other consumers that introduce a tree into a context already do: two in `StorageMerge` and `buildFilterInfo` in `Planner/Utils.cpp`. `collectSets` is idempotent, so on the main planner path, where the sets are already registered, the call is a no-op. The optimization the check gates is unchanged. `in`, `notIn`, `globalIn` and `globalNotIn` are not injective, so `isInjectiveFunction` already made the check decline such an expression; it now declines it in the same way it would have had the set been registered all along. The new test asserts that a plain sharding-key `GROUP BY` still leaves the aggregation on the shards, and the six existing sharding-key tests pass unchanged. The new test reaches the check through two `Distributed` children whose second column does not convert to the `Merge` header type order-preservingly. That is what makes `ReadFromMerge` request `FetchColumns` from its children; `StorageDistributed::getQueryProcessingStage` returns before the check when the requested stage is `WithMergeableState`.
Internal second-model review: 0 blockers, 0 majorsTwo things worth stating rather than hiding:
💡 Also noticed, not raised and not chased: |
|
Workflow [PR], commit [ec648e4] Summary: ✅
AI ReviewSummaryThis PR fixes the analyzer path that probes whether a Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit ec648e4.
Changed lines: Changed C/C++ lines covered: 3/3 (100.00%) · Uncovered code |
|
cc @devcrafter @novikd, could you review this? |
|
|
||
| /// The set registry of a planner context derived per child table is empty, and | ||
| /// `PlannerActionsVisitor` resolves `IN` through it. | ||
| collectSets(expr, *query_info.planner_context); |
There was a problem hiding this comment.
isShardingKeySuitsQueryTreeNodeExpression is only a suitability probe, but this unconditional collectSets turns it into another full set-registration pass even on the plain Distributed path where the analyzer already did collectSets(query_tree, *planner_context) in src/Planner/Planner.cpp:2577.
For constant-tuple IN, collectSets materializes the tuple before it checks whether the set is already present (src/Planner/CollectSets.cpp:95-120), so a query like GROUP BY k IN (...) now rebuilds that set once per DISTINCT/GROUP BY/LIMIT BY probe and once per Merge child (src/Storages/StorageMerge.cpp:1784). With a large RHS that is a real planning-time CPU/memory regression on a path that should only answer "can we use the sharding-key optimization?".
Can we short-circuit IN here instead of registering the set? This predicate already rejects any non-injective subtree, so returning false before buildActionsDAGFromExpressionNode would fix the No set is registered for key exception without duplicating tuple-set construction.
There was a problem hiding this comment.
Measured both halves.
The cost is real. CollectSets.cpp:95 materializes a constant right-hand side before the findTuple lookup at :120, so an already-registered set is rebuilt. I isolated it by toggling optimize_distributed_group_by_sharding_key, which is read only at StorageDistributed.cpp:677 and :735 and so switches nothing but this probe, on a shape where the probe accepts and its own DAG holds no set work. Debug build, 7 runs per arm, arms interleaved, a unique leading literal per run so nothing is served from a cache. Median query_duration_ms: 1979 against 1759 for a 100000-element list (+12.5%), peak memory_usage +2.6 MiB, 20 against 19 at 1000 elements, 2 against 2 with a subquery right-hand side. Linear in the list, one extra materialization rather than a doubling. The description said the call changes nothing where the set is already registered; that was right about the verdict and wrong about the cost, so the number is in there now.
Short-circuiting IN is not equivalent, though. PlannerActionsVisitor makes an aggregate function an INPUT node and returns at :1306, before the argument loop at :1316, so an IN inside an aggregate argument never enters the DAG and the injectivity check never sees it. With d a Distributed table sharded by k:
SELECT DISTINCT k, sum(v IN (1, 2)) FROM d GROUP BY k
-> ReadFromRemote accepted, shards keep aggregating
SELECT count() FROM d GROUP BY k IN (1, 2)
-> Expression / MergingAggregated / ReadFromRemote declined
sum(v GLOBAL IN (1, 2)) behaves like the first. So the predicate rejects the non-injective subtrees the DAG shows it, not every tree containing IN, and a tree-level short-circuit would drop the first plan's optimization. Neither shape changed here: an IN the DAG never sees never asks for a set, so it never threw.
Looking the key up before materializing would remove the redundant work without that behaviour change, but CollectSets.cpp:110-113 derives the element types from the materialization on purpose, for the LowCardinality dictionary type. Ten other call sites share that path, so I am keeping it out of a six-line fix for a logical error.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 20 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - 999d6eaEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task My source diff on this head is
I have not merged master to pick up #117827 on this head. It is merged and absent here, but two Session id: cron:our-pr-ci-monitor:20260903-100000 |
…ng-key-probe-unregistered-set
|
cc @alexey-milovidov help reviewing this one |
|
The That failure is |
…ng-key-probe-unregistered-set
|
26.9 branched on 2026-09-16, before this merged, so it does not have the fix. The same Could this get |
Backport #117817 to 26.9: Fix `No set is registered for key` when reading a `Distributed` table through `merge`
Related: #117252
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix the logical error
No set is registered for keyfor aSELECTthat reads aDistributedtable through aMergetable or themergetable function and whoseGROUP BY,DISTINCTorLIMIT BYkey contains anIN-family function.Description
ReadFromMergederives a freshPlannerContextper child table, andprepared_setsis aby-value member that the derived constructor does not copy, so that context starts with an empty
set registry. When the child is a
Distributedtable,StorageDistributed::isShardingKeySuitsQueryTreeNodeExpressionruns aPlannerActionsVisitorover the query's
GROUP BY,DISTINCTorLIMIT BYexpression in that context; anINthereresolves to nothing and the planner throws. In debug and sanitizer builds the server aborts, in a
release build the query is rejected.
PlannerActionsVisitor.hnames collectedINsets as a precondition, andCollectTableExpressionData.hnames this error as the consequence of breaking it. This consumerdid not. The fix registers the expression's sets first, as the other consumers that run the
visitor over a tree they introduce already do:
StorageMerge.cpptwice for these same derivedcontexts, and
buildFilterInfoinPlanner/Utils.cppfor the filter tree it builds. Registrationchanges no verdict, but it is not free:
CollectSets.cppmaterializes a constant right-hand sidebefore looking the key up, so an already-registered set is rebuilt, 220 ms of a 1979 ms
debug-build plan for a 100000-element list and nothing for a subquery.
The optimization the check gates is unaffected: an
INnode that reaches the actions DAG is notinjective, so the check declined it before and declines it now. The new test asserts that a plain
sharding-key
GROUP BYstill keeps its aggregation on the shards, and the existing sharding-keytests pass unchanged.
The test covers all three clauses and the constant-tuple,
GLOBAL IN, subquery and union setkinds. It aborts a debug server on
masterand passes here, 50 of 50 randomized runs.Not in this PR:
buildWatermarkActionsDAG(Interpreters/Streaming/Utils.cpp) misses the sameregistration on a fresh context;
IN <bare table identifier>aborts without anyMergetable, as#113757 records; the old-analyzer
getOptimizedQueryProcessingStageis untouched.Closes #119444
Workflow [PR]
Sync PR [sync-upstream/pr/117817]
Version info
26.10.1.246-master(included in26.10and later)26.9.37.8