Skip to content

Fix No set is registered for key when reading a Distributed table through merge - #117817

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-sharding-key-probe-unregistered-set
Sep 20, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-sharding-key-probe-unregistered-set

Conversation

@groeneai

@groeneai groeneai commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117252

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix the logical error No set is registered for key for 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.

Description

ReadFromMerge derives a fresh PlannerContext per child table, and prepared_sets is a
by-value member that the derived constructor does not copy, so that context starts with an empty
set registry. When the child is a Distributed table,
StorageDistributed::isShardingKeySuitsQueryTreeNodeExpression runs a PlannerActionsVisitor
over the query's GROUP BY, DISTINCT or LIMIT BY expression in that context; an IN there
resolves to nothing and the planner throws. In debug and sanitizer builds the server aborts, in a
release build the query is rejected.

PlannerActionsVisitor.h names collected IN sets as a precondition, and
CollectTableExpressionData.h names this error as the consequence of breaking it. This consumer
did 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.cpp twice for these same derived
contexts, and buildFilterInfo in Planner/Utils.cpp for the filter tree it builds. Registration
changes no verdict, but it is not free: CollectSets.cpp materializes a constant right-hand side
before 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 IN node that reaches the actions DAG is not
injective, so the check declined it before and declines it now. The new test asserts that a plain
sharding-key GROUP BY still keeps its aggregation on the shards, and the existing sharding-key
tests pass unchanged.

The test covers all three clauses and the constant-tuple, GLOBAL IN, subquery and union set
kinds. It aborts a debug server on master and passes here, 50 of 50 randomized runs.

Not in this PR: buildWatermarkActionsDAG (Interpreters/Streaming/Utils.cpp) misses the same
registration on a fresh context; IN <bare table identifier> aborts without any Merge table, as
#113757 records; the old-analyzer getOptimizedQueryProcessingStage is untouched.

Closes #119444


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

Version info

  • Merged into: 26.10.1.246-master (included in 26.10 and later)
  • Backported to: 26.9.37.8

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`.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 3, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 0 blockers, 0 majors

Two things worth stating rather than hiding:

⚠️ collectSets is idempotent, but on the plain-Distributed path it is a no-op in effect, not in
cost: getSetElementsForConstantValue runs before the findTuple early-out, so a large constant
IN list is re-materialised on each check (up to three times per query, and only with
optimize_skip_unused_shards=1). Reordering that shared helper for a StorageDistributed defect
looked like the wrong blast radius, so I left it. Magnitude not measured.

💡 Also noticed, not raised and not chased: SELECT DISTINCT toTypeName(v) FROM merge(...) over two
Distributed children returns Code: 10, Not found column __table1._row_exists in block on
unmodified master. Unrelated to this change.

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Sep 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ec648e4]

Summary: ✅


AI Review

Summary

This PR fixes the analyzer path that probes whether a Distributed read can keep GROUP BY/DISTINCT/LIMIT BY on the shards when the query comes through Merge/merge: the probe now registers IN sets before building the actions DAG, which matches the PlannerActionsVisitor precondition and avoids the No set is registered for key exception. After checking the current PR head, the existing discussion, and the new stateless regression, I do not see a remaining correctness issue in the change as written.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit ec648e4.

Metric Baseline Current Δ
Lines 89.10% 89.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Changed C/C++ lines covered: 3/3 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 3, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @novikd, could you review this? ReadFromMerge derives a PlannerContext per child table and the derived constructor does not copy prepared_sets, so the Distributed sharding-key check ran a PlannerActionsVisitor over the query's GROUP BY expression in a context with an empty set registry, and the IN lookup threw a logical error. The fix registers that expression's sets first, which is what the other consumers of that visitor already do.


/// 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);

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ec648e46e with master 6b8954cd0 (stripped binary size, per-symbol sizes and ThinLTO time; 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

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

Job report

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 999d6ea

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

My source diff on this head is +6/-0 in StorageDistributed.cpp, reachable only when a
Distributed child evaluates its sharding-key predicate. None of the four failures enter it.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Not-ready Set is passed as the second argument for function 'globalNotIn' (STID 0250-4e52) pre-existing trunk defect, not reachable from this diff: the fuzzer mutated my new test's LIMIT 1 BY k IN (1, 2) into globalNotIn over a _data_* external table, and the table it reads is a plain MergeTree, not Distributed #102308 (external, open)
AST fuzzer (amd_release, oracle) / server-side TLP WHERE oracle mismatch pre-existing, not reachable from this diff: the fuzzed query is SELECT x FROM (SELECT DISTINCT assumeNotNull(65537) AS x GROUP BY 1 WITH CUBE) WHERE x, with no Distributed table and no merge(). The reference query returns 2 rows and the WHERE / not / isNull partition returns 3, the extra row being the WITH CUBE totals row #117200 (external, open)
Docs examples / Function/timeSeriesPrometheusValueToString#0 trunk-side, and not reachable from this diff: the documented output box for SELECT timeSeriesPrometheusValueToString(toFloat64(1e-7)) is one character wider than the box the server prints, so the check fails on every tree carrying it #117827 (external, merged 2026-09-03T09:33:59Z), rule 3c: measured ABSENT from this failing tree, master merge deferred below
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) resource guard, not a test result: praktika's own verdict on the leaf reads infrastructure/resource failure, not bug reproduction #117564 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

I have not merged master to pick up #117827 on this head. It is merged and absent here, but two
other gating reds on this head are owned by PRs that are still open (#102308, #117200), so the
merge cannot turn this head green and would only cost another full run plus a workflow approval.
The next push will carry it.

Session id: cron:our-pr-ci-monitor:20260903-100000

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov help reviewing this one

@groeneai

Copy link
Copy Markdown
Collaborator Author

The Stress test (arm_asan_ubsan, s3) failure on 80365e1c now has a fixing PR: #119540.

That failure is UndefinedBehaviorSanitizer: null pointer / Segmentation fault (STID 0250-2dff) in getBlockWithSortingKey at applyPatches.cpp:328, a trunk defect in the lightweight-update read path. It is not reachable from this PR's diff: three unrelated carrier PRs show the identical frame across 10 days, and none of them touches patch parts or lightweight updates.

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit a98320d Sep 20, 2026
177 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

26.9 branched on 2026-09-16, before this merged, so it does not have the fix. The same No set is registered for key LOGICAL_ERROR on the merge() over Distributed route (ReadFromMerge::createPlanForTable -> StorageDistributed::isShardingKeySuitsQueryTreeNodeExpression) fired in a 26.9 stress run today: Stress test (arm_tsan). On master and PRs this stack has not failed since the merge (14 failures in the three weeks before it).

Could this get v26.9-must-backport? 26.10 already has it. The hunk (one include, one collectSets call) has the same context on 26.9, and also on 26.8 and 26.3 if those should be covered (v26.8-must-backport would cover 26.8 and 26.9).

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 23, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 23, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 23, 2026
Backport #117817 to 26.9: Fix `No set is registered for key` when reading a `Distributed` table through `merge`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.9-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: No set is registered for key A (STID: 0250-1016)

7 participants