Repository navigation
Conversation
…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]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-0:20260616-094500 |
|
cc @KochetovNicolai @vdimir — could you review this? It fixes the AST-fuzzer |
|
Workflow [PR], commit [f3e51ac] Summary: ❌
AI ReviewSummaryThis PR fixes analyzer/planner set-key drift for an PR Metadata
Missing context / blind spots
Final VerdictStatus: ✅ Approve |
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]>
Pre-PR validation gate (follow-up commit:
|
| # | 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]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 12/12 (100.00%) | Lost baseline coverage: none · Uncovered code |
|
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:
Finish Workflow is green; Mergeable Check is red only due to the non-PR-caused Stress hung-check above. |
|
Superseded by #112219, which fixes the same sharing one Why the narrower placement here is not enough: the Measured: this PR's committed test Leaving the close-or-keep decision to a maintainer. |
CI finish ledger - f3e51acEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Gates: 161 check-runs, 0 queued or in progress; Neither failure is PR-caused: the first never ran a test, and the second is a DDL-guard convoy in Note this PR is superseded by #112219, which fixes the same table-expression sharing one layer up at Session id: cron:our-pr-ci-monitor:20260803-180000 |
|
Fixing PR for the The hung check's three cancelled DDL queries were a convoy behind one 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. |
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.
Changelog category (leave one):
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 aFROMtable expression and as the right argument of anIN/NOT IN/GLOBAL INfunction, for exampleSELECT 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
FROMtable expression and as the right argument of anIN/NOT IN/GLOBAL INfunction (the right argument being an alias of thatFROMtable expression), the analyzer resolves both references to the same shared query-tree node.collectSets()registers theINset inPreparedSetskeyed by that node's tree hash. When the node is later planned as theFROMsource,Planner::buildPlanForQueryNode()mutates it in place (constant-trueWHEREremoval, or theQUALIFY -> HAVING -> WHERErewrite). That changes its tree hash, so the later set lookup inPlannerActionsVisitor::makeSetForInFunction()recomputes the hash from the mutated node and fails to find the set, aborting withLOGICAL_ERROR"No set is registered for key ...".Fix: when the
INset source is aQUERY/UNIONnode that is shared with another part of the query tree (use_count() > 1), resolve theINargument against an independent copy. The set source is then no longer aliased to theFROMtable expression, so planning theFROMsource 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_tableis added; all four queries it contains abort on master and pass with this fix.Follow-up commit: copy
column_nameinSortNode::cloneImplThe new
clone()of theINset source exposed a latent defect:SortNode::cloneImpldid not copycolumn_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 resolvedORDER BY <identifier>lost the name. This is visible inEXPLAIN QUERY TREE(SORTprintsEXPRESSIONinstead ofEXPRESSION <name>) and is read by the planner:PlannerSortingbuildsSortColumnDescription::aliasfrom it, and that alias is used byFillingTransformforWITH FILL ... INTERPOLATEcolumn matching.InterpolateNode::cloneImplalready copies its analogousexpression_name; this mirrors that. The pre-existing test03165_order_by_duplicate(anEXPLAIN QUERY TREEof anINsubquery withORDER BY) regressed toEXPRESSIONand is restored by this commit.