Skip to content

Fix "No set is registered for key" for a subquery used as both FROM source and IN argument - #107603

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-no-set-registered-shared-in-source
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-no-set-registered-shared-in-source

Conversation

@groeneai

@groeneai groeneai commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator

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 a LOGICAL_ERROR "No set is registered for key" that could abort the server (or fail the query in release builds) for a query where a subquery is used both as a FROM table expression and as the right argument of an IN / NOT IN / GLOBAL IN function, for example SELECT y FROM (SELECT y FROM t QUALIFY 1) AS s QUALIFY globalNotIn((SELECT 1), s).

Description

Found by the AST fuzzer (AST fuzzer (arm_asan_ubsan)). Example report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104939&sha=d224ae20875bb869add720814dd4c5e5fd4604e8&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29 (STID 0250-04e2). The crash is a pre-existing trunk bug, unrelated to the PR it happened to fire on.

When a subquery is referenced both as a FROM table expression and as the right argument of an IN / NOT IN / GLOBAL IN function (the right argument being an alias of that FROM table expression), the analyzer resolves both references to the same shared query-tree node.

collectSets() registers the IN set in PreparedSets keyed by that node's tree hash. When the node is later planned as the FROM source, Planner::buildPlanForQueryNode() mutates it in place (constant-true WHERE removal, or the QUALIFY -> HAVING -> WHERE rewrite). That changes its tree hash, so the later set lookup in PlannerActionsVisitor::makeSetForInFunction() recomputes the hash from the mutated node and fails to find the set, aborting with LOGICAL_ERROR "No set is registered for key ...".

Fix: when the IN set source is a QUERY/UNION node that is shared with another part of the query tree (use_count() > 1), resolve the IN argument against an independent copy. The set source is then no longer aliased to the FROM table expression, so planning the FROM source cannot mutate the node behind the set key.

This is the same root-cause class as #80757 (a set key drifting between registration and lookup), here caused by an in-place planner mutation of a shared node rather than by CTE-name decoration.

No open issue was found for this error. A stateless regression test 04338_in_set_source_aliases_from_table is added; all four queries it contains abort on master and pass with this fix.

Follow-up commit: copy column_name in SortNode::cloneImpl

The new clone() of the IN set source exposed a latent defect: SortNode::cloneImpl did not copy column_name (a member derived from the original AST identifier in the constructor, not a child node, so the base clone machinery cannot reproduce it). A clone of any subtree containing a resolved ORDER BY <identifier> lost the name. This is visible in EXPLAIN QUERY TREE (SORT prints EXPRESSION instead of EXPRESSION <name>) and is read by the planner: PlannerSorting builds SortColumnDescription::alias from it, and that alias is used by FillingTransform for WITH FILL ... INTERPOLATE column matching. InterpolateNode::cloneImpl already copies its analogous expression_name; this mirrors that. The pre-existing test 03165_order_by_duplicate (an EXPLAIN QUERY TREE of an IN subquery with ORDER BY) regressed to EXPRESSION and is restored by this commit.

…source and IN argument

When a subquery is referenced both as a FROM table expression and as the right
argument of an IN / NOT IN / GLOBAL IN function (the right argument being an alias
of the FROM table expression), the analyzer resolves both references to the same
shared query-tree node.

collectSets() registers the IN set in PreparedSets keyed by that node's tree hash.
When the node is later planned as the FROM source, Planner::buildPlanForQueryNode()
mutates it in place (constant-true WHERE removal, or the QUALIFY -> HAVING -> WHERE
rewrite), which changes its tree hash. The subsequent set lookup in
PlannerActionsVisitor::makeSetForInFunction() recomputes the hash from the mutated
node and fails to find the set, aborting with LOGICAL_ERROR
"No set is registered for key ...".

Fix: when the IN set source is a QUERY/UNION node that is shared with another part
of the query tree (use_count() > 1), resolve the IN argument against an independent
copy. The set source is then no longer aliased to the FROM table expression, so
planning the FROM source cannot mutate the node behind the set key.

Found by the AST fuzzer (e.g. QUALIFY + globalNotIn over a derived-table alias).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On master (clang debug), clickhouse local --enable_analyzer=1 on SELECT y FROM (SELECT y FROM t QUALIFY 1) AS s QUALIFY globalNotIn((SELECT 1), s) (table t (y Int32) with a few rows) aborts every run with Logical error: 'No set is registered for key ...'. Each of the four queries in the new test reproduces it on master.
b Root cause explained? Yes. A subquery used as both a FROM table expression and the right IN/NOT IN/GLOBAL IN argument resolves to one shared query-tree node. collectSets() registers the set keyed by that node's tree hash. Planning the node as the FROM source mutates it in place in Planner::buildPlanForQueryNode() (constant-WHERE removal / QUALIFY -> HAVING -> WHERE rewrite), changing its tree hash; makeSetForInFunction() then recomputes the hash from the mutated node, misses the registered set, and throws LOGICAL_ERROR.
c Fix matches root cause? Yes. The fix removes the node sharing at its source: when the IN set source is a QUERY/UNION shared beyond this argument (use_count() > 1), the IN argument is resolved against an independent clone, so FROM-source planning mutations can no longer change the node behind the registered set key. It does not widen any bound or suppress the assertion.
d Test intent preserved / new tests added? New test added: 04338_in_set_source_aliases_from_table (4 queries: IN, NOT IN, GLOBAL IN, and QUALIFY globalNotIn). All 4 abort on master HEAD and pass with the fix. No existing test was weakened.
e Both directions demonstrated? Yes. With the fix reverted (same build dir), all 4 test queries abort (exit 134). With the fix, the test passes, including 30/30 runs with randomized settings, and the curated IN/set/qualify/analyzer suite (02841_not_ready_set_bug, 02500_remove_redundant_distinct[_analyzer], 03095_window_functions_qualify, 04008_count_distinct_optimization_with_qualify, etc.) is green.
f Fix is general, not a narrow patch? Yes. The fix is at the single shared-node origin (analyzer IN resolution), so it covers all set-source mutation variants (constant-WHERE removal and QUALIFY/HAVING rewrites) and all IN/NOT IN/GLOBAL IN forms, not just the one fuzzed query. It is not a defensive if (!ptr) guard at the crash site; it prevents the bad state (a mutated registered node) from arising.

Session id: cron:clickhouse-worker-slot-0:20260616-094500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @vdimir — could you review this? It fixes the AST-fuzzer LOGICAL_ERROR "No set is registered for key": a subquery used both as a FROM source and as an IN/NOT IN/GLOBAL IN right argument is one shared query-tree node, and planning it as the FROM source mutates it in place (constant-WHERE removal / QUALIFY->HAVING->WHERE rewrite), so the recomputed tree hash no longer matches the PreparedSets key. The fix clones the IN set source when it is shared (use_count() > 1). @KochetovNicolai, this is the same key-drift class as your #80757 — does decoupling at the analyzer (clone the shared set source) match your intent, or would you prefer the set lookup be made robust to the mutation instead?

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jun 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f3e51ac]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb
Stateless tests (arm_asan_ubsan, targeted) ERROR

AI Review

Summary

This PR fixes analyzer/planner set-key drift for an IN set source that aliases a FROM table expression by cloning only set-source QUERY/UNION nodes that are also registered table expressions, and it makes SortNode::cloneImpl preserve the planner-visible column_name. The current code addresses the previous use_count review finding; I did not find a blocking correctness issue.

PR Metadata
  • 💡 The Bug Fix category is appropriate and the changelog entry is specific, but the changelog text says the issue could "abort the server". For a stable-release changelog, describe the release behavior as a query exception instead. Suggested entry:

    Fix a LOGICAL_ERROR exception "No set is registered for key" for queries where a subquery is used both as a FROM table expression and as the right argument of an IN, NOT IN, or GLOBAL IN function, for example SELECT y FROM (SELECT y FROM t QUALIFY 1) AS s QUALIFY globalNotIn((SELECT 1), s).

  • 💡 The free-form PR description still says the fix uses the use_count check, which is no longer true after f3e51ac. Please update that paragraph to say the clone is keyed off IdentifierResolveScope::registered_table_expression_nodes in the current or enclosing scope.

Missing context / blind spots
  • ⚠️ No build* directory or clickhouse binary is available in this checkout, so I did not run 04338_in_set_source_aliases_from_table locally. A stateless run with a built server would close this gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 16, 2026
SortNode::cloneImpl did not copy column_name, which is derived from the
original AST identifier in the constructor (it is not a child node, so the
base clone machinery cannot reproduce it). A clone of any query subtree
containing a resolved ORDER BY <identifier> therefore lost the column name.

This is observable in EXPLAIN QUERY TREE (the SORT node prints EXPRESSION
instead of EXPRESSION <name>) and, more importantly, the planner reads it:
PlannerSorting builds SortColumnDescription::alias from it, and that alias is
used by FillingTransform for WITH FILL ... INTERPOLATE column matching. So a
cloned ORDER BY ... WITH FILL ... INTERPOLATE could behave incorrectly.

The preceding commit introduced a clone() of the IN set source subquery, which
makes this latent defect reachable: test 03165_order_by_duplicate (an EXPLAIN
QUERY TREE of an IN subquery with ORDER BY) started showing EXPRESSION instead
of EXPRESSION id. InterpolateNode::cloneImpl already copies its analogous
expression_name member; this mirrors that.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (follow-up commit: SortNode::cloneImpl copies column_name)

This gate covers the second commit. The first commit's gate was posted earlier on this PR.

# Question Answer
a Deterministic repro? Yes. clickhouse local -q "CREATE TABLE test ENGINE=ReplacingMergeTree PRIMARY KEY id AS SELECT number AS id FROM numbers(100); EXPLAIN QUERY TREE SELECT id FROM test FINAL WHERE id IN (SELECT DISTINCT id FROM test FINAL ORDER BY id ASC LIMIT 4) ORDER BY id ASC LIMIT 1 BY id SETTINGS enable_analyzer=1;" — the inner SORT id: 12 prints a bare EXPRESSION on every run with the first commit alone. This is exactly 03165_order_by_duplicate.
b Root cause explained? The first commit added in_second_argument = in_second_argument->clone() for shared QUERY/UNION set sources. clone() -> SortNode::cloneImpl(), which constructed a new SortNode without copying column_name. column_name is set in the SortNode constructor from the original AST identifier (only when the sort key is an identifier), is not a child node, and so the base clone machinery cannot reproduce it. The cloned ORDER BY id therefore had an empty column_name, which dumpTreeImpl renders as bare EXPRESSION instead of EXPRESSION id.
c Fix matches root cause? Yes — root-cause fix at the source. cloneImpl() now copies column_name so the clone is faithful, rather than papering over it by narrowing the clone guard or editing the test reference. This mirrors the existing InterpolateNode::cloneImpl, which already copies its analogous expression_name.
d Test intent preserved / new tests added? Preserved. No test was weakened and no reference was changed. The pre-existing 03165_order_by_duplicate (an EXPLAIN QUERY TREE over an IN subquery with ORDER BY) is itself the regression guard: it fails with the first commit alone and passes with this commit, restoring its committed reference byte-for-byte. A scan of all stateless references confirmed the only other bare-EXPRESSION-under-SORT cases (01323_redundant_functions_in_order_by) are legitimately function sort keys (exp(x)), where column_name is correctly empty and is unchanged by this fix.
e Both directions demonstrated? Yes. Without fix: inner SORT id: 12 -> bare EXPRESSION (diff vs reference). With fix: inner SORT id: 12 -> EXPRESSION id, and diff 03165_order_by_duplicate.reference <got> is an exact match. 04338_in_set_source_aliases_from_table (this PR's own test) also still matches its reference.
f Fix is general, not a narrow patch? Yes. The bug class is "a scalar member derived from the AST identifier during resolution, dropped on clone." All 18 Analyzer/*::cloneImpl were audited: every other node already copies its non-child scalar members (e.g. QueryNode, FunctionNode, TableNode, and notably InterpolateNode::expression_name). SortNode.column_name was the lone outlier; this brings it in line. The member is also read functionally, not just for display: PlannerSorting maps it to SortColumnDescription::alias, which FillingTransform uses for WITH FILL ... INTERPOLATE column matching, so a cloned ORDER BY ... WITH FILL ... INTERPOLATE could otherwise misbehave.

Session id: cron:clickhouse-worker-slot-3:20260616-175600

The previous commit detached the IN/NOT IN/GLOBAL IN set source with
in_second_argument.use_count() > 1 as a proxy for "shared with a FROM table
expression". That proxy is unreliable: every resolved subquery already has a
second strong reference from QueryAnalyzer::node_to_scope_map (created in
createIdentifierResolveScope during resolveExpressionNodeList, which runs before
this check), so an ordinary x IN (SELECT ...) RHS also has use_count() > 1 and
was cloned unnecessarily, dropping the node's analyzer scope-map entry.

Detect the actual condition instead: the set source is cloned only when it is a
node registered as a table expression in the current or an enclosing scope
(IdentifierResolveScope::registered_table_expression_nodes), i.e. the same node
also appears in a join tree. That is exactly the case where planning the table
expression mutates the node in place and would invalidate the set's PreparedSets
key. A standalone IN (SELECT ...) is no longer touched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.40% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 12/12 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI summary for head f3e51ac. Both red checks are pre-existing failures unrelated to this analyzer IN-set / SortNode clone fix. The PR's own tests passed: 04338_in_set_source_aliases_from_table (233 OK, 0 FAIL) and 03165_order_by_duplicate (14 OK, 0 FAIL; the SortNode::cloneImpl regression is fixed in 591a501).

Finish Workflow is green; Mergeable Check is red only due to the non-PR-caused Stress hung-check above.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #112219, which fixes the same sharing one
layer up, at the identifier-resolution site both consuming paths funnel through, rather than inside
the regular IN block.

Why the narrower placement here is not enough: the rewrite_in_to_join path resolves the IN
operands itself and clears is_special_function_in before the regular block runs, so this PR's hunk
is never reached for that mode, which is why it still fails with Code: 10. #112219 also covers the
GLOBAL IN external-table rewrite (Code: 179).

Measured: this PR's committed test 04338_in_set_source_aliases_from_table.sql aborts on the merge
base and matches its .reference byte for byte against master plus #112219 without this PR's
resolveFunction.cpp hunk. All four of its shapes are carried into #112219's test, and its
SortNode::cloneImpl hunk is carried over as well, so nothing is lost if this one is closed.

Leaving the close-or-keep decision to a maintainer.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f3e51ac

Every failure below has an owner: a fixing PR (ours 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.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, targeted) harness abort, not a test result: the job never selected tests. find_tests.py:415 -> cidb.query raised Failed to query CI DB, so get_tests_by_changed_lines propagated out of functional_tests.py:517 and the job reported ERROR with no test rows. Confined to a CI-database outage window: 107 hits on this job over 60 days, all inside 2026-06-16/17, 0 on master, and nothing since #113052 (ours, merged 2026-08-03) - stops the workflow-configuration path from querying the CI database at all
Stress test (amd_tsan) / Hung check failed, possible deadlock found three stuck queries, all is_cancelled=1 and all DDL: DROP TABLE IF EXISTS test at 1512 s, drop table if exists test at 698 s, DETACH DATABASE test_5 at 392 s, each with 0 rows read and 0 bytes written. Stacks put them in DatabaseCatalog::getDDLGuard under unique_lock, i.e. a DDL-guard convoy behind one holder, with database_atomic_wait_for_drop_and_detach_synchronously = 1. Logging is not a factor here (LogTest is 1-2 messages per row) a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)

Gates: 161 check-runs, 0 queued or in progress; Finish Workflow completed successfully.

Neither failure is PR-caused: the first never ran a test, and the second is a DDL-guard convoy in
unrelated tests (02950_parallel_replicas_used_count, 03469_json_read_subcolumns_combined_1_wide_merge_tree)
while this PR changes analyzer IN-set handling only.

Note this PR is superseded by #112219, which fixes the same table-expression sharing one layer up at
the identifier-resolution site. This ledger covers the CI result on this head; it is not an argument
for reviving this PR.

Session id: cron:our-pr-ci-monitor:20260803-180000

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (amd_tsan) hung check on my CI finish ledger (head f3e51ac230cd): #109636.

The hung check's three cancelled DDL queries were a convoy behind one DROP TABLE that was waiting on a background merge of a JSON(max_dynamic_paths = 2, ...) column. That merge consumed 1 -> 16 GiB over 27 minutes without finishing, because the AST fuzzer had rewritten one INSERT's map key into a row-unique expression, giving one source part ~100,000 distinct shared-data paths (its json.object_shared_data.paths.bin is 828,373 bytes against ~3,100 for its siblings). With index_granularity randomized to 37,535 that is ~11.8 GiB for a single flattenAndBucketSharedDataPaths call, which matches the observed growth.

That is #108992, and #109636 (approved) fixes it via per-bucket materialization plus row chunking. Full evidence: #108992 (comment)

Not caused by this PR: it changes analyzer IN-set / SortNode clone handling, and neither hung query reaches an IN-set path.

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@abashkeev abashkeev added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 6, 2026
When the right operand of an `IN`-family function is an identifier, `resolveFunction`
allows it to be resolved as a table expression, and that resolution returns the join
tree's own node pointer: the alias path deliberately does not clone for a
table-expression lookup, and the surrounding block clones only for CTEs and
materialized CTEs. A plain subquery-with-alias, bare table alias or table function
therefore ends up as one shared node in two places in the query tree.

`IdentifierResolveScope.h` already states the invariant this violates and names the
three stages that rewrite each `IN` argument instance independently. All three break:
`createUniqueAliasesIfNecessary` strips the shared node's alias and renumbers its inner
table, so the planner throws `Column identifier ... is already registered`; the
`GLOBAL IN` external-table rewrite collides on the generated `FROM` alias with
`MULTIPLE_EXPRESSIONS_FOR_ALIAS`; and `rewrite_in_to_join` produces
`NOT_FOUND_COLUMN_IN_BLOCK`. The latter two are reachable on release builds for queries
that are answered correctly when the same subquery is spelled out instead of referenced
by alias.

Clone the resolved node when it is a table expression that is registered in the join
tree of the current or an enclosing scope. This is the single retrieval site both
consuming paths reach - the `rewrite_in_to_join` path resolves the operand itself and
clears `is_special_function_in` before the regular `IN` block runs - so one change
covers all three symptoms, and the detector is independent of how the table expression
is spelled.

`SortNode::cloneImpl` is fixed to carry `column_name`, which is derived from the
original AST identifier rather than from a child node and so is not reproduced by the
base clone machinery. It is read by the planner and printed by `EXPLAIN`, and this
change routes more nodes through cloning.

This supersedes the narrower clone in ClickHouse#107603, whose committed test passes against this
change without its own hunk; its shapes are carried into the test added here.
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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants