Repository navigation
Introduce ITableExpressionNode in the query tree - #108645
Conversation
Add an `ITableExpressionNode` base class for query tree nodes that can act as a column source, and remove the generic `weak_pointers` vector (and the `QueryTreeNodeWeakPtr` / `QueryTreeWeakNodes` / `QueryTreeNodesDeque` typedefs) from `IQueryTreeNode`. `ColumnNode` now holds a single typed `std::weak_ptr<ITableExpressionNode>` source instead of a slot in the generic weak-pointer array, and `getColumnSource` / `getColumnSourceOrNull` return a `TableExpressionNodePtr`. The node classes usable as a column source -- `TableNode`, `TableFunctionNode`, `QueryNode`, `UnionNode`, `JoinNode`, `ArrayJoinNode`, `InterpolateNode` and the new `LambdaArgumentsNode` -- derive from `ITableExpressionNode`. Lambda arguments are now represented by a dedicated `LambdaArgumentsNode` that holds the argument names and their resolved types and serves as the column source for the lambda parameters, replacing the previous list of argument identifier / column nodes. `resolveLambda` binds parameters by name, and the planner reconstructs the (name, type) pairs from the node. `cloneAndReplace` is narrowed to operate on table expressions only: its `ReplacementMap` is keyed by `const ITableExpressionNode *` and the clone consults it only for nodes whose `asTableExpression` is non-null. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [0d72335] Summary: ✅
AI ReviewSummaryThis PR refactors query-tree table-expression typing by introducing Findings❌ Blockers
Final Verdict❌ Needs changes before merge. |
…pression-node Resolved a conflict in `QueryAnalyzer.cpp`: upstream added the `is_qualified_matcher` branch in `updateMatchedColumnsFromJoinUsing`, kept alongside our rename of the join-tree accessor to `getJoinTreeNode`. Also fixed semantic conflicts from auto-merged code that used APIs changed by this branch (`getJoinTree` now returns a `const ITableExpressionNode &`, and `SelectQueryInfo::table_expression` is a `TableExpressionNodePtr`) in the `gtest_planner_empty_projection` and `gtest_transform_query_for_external_database` tests. Verified with a clean build of the `clickhouse` target. Co-Authored-By: Claude Fable 5 <[email protected]>
…ce checks
All 407 stateless tests failed in Fast test with two shared root causes:
1. `CrossJoinNode` did not derive from `ITableExpressionNode`, while the
join tree of a query with comma/cross joins is a `CrossJoinNode` and the
asserting accessors (`QueryNode::getJoinTree`, `JoinNode` table expression
getters) call `assertTableExpression` on it, throwing the logical error
`CROSS_JOIN is not a table expression`.
2. Column-source type checks still compared against `QueryTreeNodeType::LAMBDA`,
but lambda argument columns are now sourced from `LambdaArgumentsNode`
(`LAMBDA_ARGS`), so the checks never matched:
- `CollectTableExpressionData.cpp`: lambda columns fell through to the
table-expression whitelist and threw `Expected table, table function,
array join, query or union column source`.
- `ValidationUtils.cpp`: false `Column is not under aggregate function and
not in GROUP BY keys` errors for lambdas inside aggregates.
- `PlannerActionsVisitor.cpp`: the lambda-capture check compared the source
against the scope node; the source is now the arguments node owned by the
lambda scope, causing `Cannot find the original scope of the column`.
- `Analyzer/Utils.cpp`: correlation check exemption for lambda arguments.
- `StorageMerge.cpp`: guard against re-qualifying lambda argument columns.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108645&sha=88b22b8fb66c1154eb55f412fec88d92f292a144&name_0=PR&name_1=Fast+test
PR: #108645
Co-Authored-By: Claude Fable 5 <[email protected]>
`LambdaNode::dumpTreeImpl` no longer prints a separate `ARGUMENTS` header row; the arguments node dumps itself as `ARGUMENTS id: N` with one `ARGUMENT id: i, name: ..., type: ...` row per argument. Update test references: - `02366_explain_query_tree`, `02576_rewrite_array_exists_to_has`: new lambda arguments dump format, node id renumbering, and lambda argument columns now reporting the lambda arguments node as `source_id`. - `01625_constraints_index_append`: `and` argument order changed because CNF atoms are ordered by tree hash (`CNFAtomicFormula::operator<`) and this branch changed tree hash computation (the generic weak pointer contribution was removed from `IQueryTreeNode::getTreeHash`). The new order is deterministic; the test pins the database name for exactly this reason. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108645&sha=e7713e360eadbe36cce6dba37bd0547f9ad9e11c&name_0=PR PR: #108645 Co-Authored-By: Claude Fable 5 <[email protected]>
The tidy build is the only one that compiles `unit_tests_dbms`, and it failed on code passing a plain `QueryTreeNodePtr` as a `ColumnNode` source, which is now a `std::weak_ptr<ITableExpressionNode>`: - `gtest_analyzer_utils.cpp` passed the identifier node being replaced as the column source. Pass an empty source instead: the identifier was immediately replaced by the column in the tree, so its weak pointer always expired and the columns effectively never had a live source. - `gtest_query_tree_node.cpp`: the test-local `SourceNode` mock used as a column source now derives from `ITableExpressionNode`. Verified by building `unit_tests_dbms` and running the affected suites (`QueryTreeNode`, `OptimizeAndCompareChain`, `LikePerfectAffixRewrite`, `PlannerJoinTreeEmptyProjectionGuard`, `TransformQueryForExternalDatabase`). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108645&sha=64a7e35854718fdbaedced0e43e61f76cc20e40b&name_0=PR PR: #108645 Co-Authored-By: Claude Fable 5 <[email protected]>
`JoinNode::dumpTreeImpl` used the asserting table expression accessors, but in an unresolved query tree (`EXPLAIN QUERY TREE run_passes = 0`, or error message formatting during analysis) the join children are still identifier nodes, so `assertTableExpression` threw the logical error `IDENTIFIER is not a table expression`. Dump through the raw node accessors instead. Found by AST fuzzer and BuzzHouse. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108645&sha=4ae1da7a582827d4d1627d713595e91a28c2276c&name_0=PR PR: #108645 Co-Authored-By: Claude Fable 5 <[email protected]>
`ArrayJoinNode::cloneImpl` passed the join expressions list as the table
expression constructor argument, and both `ArrayJoinNode::cloneImpl` and
`JoinNode::cloneImpl` wrapped children in `static_pointer_cast<ITableExpressionNode>`,
which is invalid for unresolved trees where the children are still identifier
nodes (and pointless, since the constructors take `QueryTreeNodePtr`).
This had no observable effect: `cloneAndReplace` overwrites the clone's
children with the original's children right after `cloneImpl` and clones them
recursively, per the `cloneImpl` contract ("do not clone children"). Fixed for
clarity and to keep correctness independent of that non-local invariant.
Found by review.
PR: #108645
Co-Authored-By: Claude Fable 5 <[email protected]>
| /// The column source is left empty: previously the replaced identifier node was | ||
| /// passed here, and its weak pointer expired as soon as the identifier was | ||
| /// replaced by the column in the tree. | ||
| auto column = std::make_shared<ColumnNode>(NameAndTypePair(col_name, type), std::weak_ptr<ITableExpressionNode>{}); |
| @@ -1,3 +1,4 @@ | |||
| #include <Analyzer/IQueryTreeNode.h> | |||
| @@ -1,3 +1,4 @@ | |||
| #include <Analyzer/IQueryTreeNode.h> | |||
| @@ -1,3 +1,4 @@ | |||
| #include <Analyzer/IQueryTreeNode.h> | |||
| @@ -1,3 +1,4 @@ | |||
| #include <Analyzer/IQueryTreeNode.h> | |||
| /// Lambda argument columns are sourced from the lambda's arguments node, | ||
| /// while the scope node on the actions stack is the owning lambda itself. | ||
| const auto & scope_node = actions_stack[i].getScopeNode(); | ||
| if (scope_node && scope_node->getNodeType() == QueryTreeNodeType::LAMBDA && |
There was a problem hiding this comment.
Yes, it's top-level scope. See PlannerActionsVisitorImpl::PlannerActionsVisitorImpl
| @@ -1,3 +1,4 @@ | |||
| #include <Analyzer/IQueryTreeNode.h> | |||
| if (table_node) | ||
| replacement_map.emplace(table_node, std::move(dummy_table_node)); | ||
| else | ||
| replacement_map.emplace(table_function_node, std::move(dummy_table_node)); |
| { | ||
| NameSet column_names; | ||
| NamesAndTypes columns; | ||
| TableExpressionNodePtr source; |
There was a problem hiding this comment.
Yes, line 563
It's just a not-very-nice hack to keep typed ptr.
| @@ -1,5 +1,6 @@ | |||
| #pragma once | |||
|
|
|||
| #include <Analyzer/IQueryTreeNode.h> | |||
# Conflicts: # src/Analyzer/LambdaNode.cpp
…ions Master-side code added since the last merge assumed the old untyped API: - resolveFunction.cpp: use getJoinTreeNode for join tree assignment and cast the IN right-hand subquery/table to ITableExpressionNode for the ColumnNode source (QueryNode/UnionNode/TableNode all are table expressions). - InterpreterExplainQuery.cpp: extractTableExpressions now takes TableExpressionNodePtr; cast the query tree (QueryNode/UnionNode). - resolveStorages.cpp: SelectQueryInfo::table_expression is typed; cast the resolved TableFunctionNode. Co-Authored-By: Claude Fable 5 <[email protected]>
Most files get IQueryTreeNode.h transitively from the concrete node headers they already include; CNF.h needs only the QueryTreeNodePtr alias from HashUtils.h and now includes <functional> directly for std::function. ValidationUtils.h is reduced to a forward declaration. Also add the TableExpressionNodeWeakPtr alias and use it instead of spelling out std::weak_ptr<ITableExpressionNode>, drop the unused <span> include from IQueryTreeNode.h, simplify the replacement map insertion in findParallelReplicasQuery.cpp, and remove commented-out code from LambdaNode.cpp. The include stays in CNFAtomicFormula.cpp (its QueryTreeNodeWithHash comparison instantiates isEqual and needs the complete type) and in OptimizeKeyExpressionsUtils.h (declares functions using QueryTreeNodes). Co-Authored-By: Claude Fable 5 <[email protected]>
…dump format Lambda arguments in the query tree dump are now printed as an ARGUMENTS block with ARGUMENT name/type lines instead of a LIST of COLUMN nodes, and node ids inside the lambda expression shift accordingly. The optimization behavior checked by the test is unchanged. Co-Authored-By: Claude Fable 5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR is a query-tree analyzer refactor: it introduces an ITableExpressionNode base class, moves column-source tracking off the generic weak-pointer array, and reworks clone/hash/equality traversal. All of that runs in the analysis phase, not in the scan or aggregation execution path that ClickBench Q15 and Q33 actually spend their time in. Both flagged queries stay not_sure: Q15 (+10.2%) and Q33 (+8.5%) both land inside master's current variance band (255 ms in 191-287; 1388 ms just under the 1401 ceiling), so these small deltas are within-envelope run-to-run noise rather than a real effect of the change. The deterministic envelope suppression looks correct here and is consistent with the diff. clickbenchFlagged queries (2 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
|
# Conflicts: # src/Interpreters/InterpreterExplainQuery.cpp
|
|
||
| TableExpressionNodePtr getTableExpressionNodeTyped() const | ||
| { | ||
| assertTableExpression(); |
There was a problem hiding this comment.
getTableExpressionNodeTyped is meant to be the checked cast for the inner table expression, but this asserts this ArrayJoinNode instead of the child. If an unresolved ARRAY JOIN subtree reaches a typed caller, this will happily static_pointer_cast an IdentifierNode child to ITableExpressionNode and hand back an invalid typed pointer instead of throwing the logical exception the other typed accessors give. Please assert children[table_expression_child_index] here, like QueryNode::getJoinTreeNodeTyped / JoinNode::*Typed, before doing the cast.
…tree-table-expression-node # Conflicts: # src/Analyzer/Passes/InjectRandomOrderIfNoOrderByPass.cpp
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 1221/1330 (91.80%) · Uncovered code |
…lyzed twice A `TableFunctionNode` analyzed twice lost the record of which arguments are unresolved, so query tree passes walked into a subtree that is deliberately left unresolved and hit a logical error `IDENTIFIER is not a table expression` at `IQueryTreeNode::assertTableExpression`, reached from `RemoveUnusedProjectionColumnsPass` via `QueryNode::getJoinTreeNodeTyped`. With `analyzer_compatibility_join_using_top_level_identifier = 1`, resolving a `USING` key that matches a `SELECT` list alias reuses the left table expression without cloning and resolves it a second time (`QueryAnalyzer.cpp:5400-5410`). On the first pass a `view` argument is force-skipped, because its subquery may reference tables that only exist on the remote server, and its index goes into `unresolved_arguments_indexes`. On the second pass the argument is already a `TableFunctionNode`, so it takes the passthrough at `QueryAnalyzer.cpp:4612` and its index is never re-recorded; `TableFunctionNode::resolve` then overwrites the whole index set with the shorter one. Measured on a single node pointer: the set goes `[]` to `[1]` after the first resolution and `[1]` to `[]` after the second. With the index gone, `traverseQueryTree` descends into the argument and its unresolved `IdentifierNode` join tree reaches a pass. Carry the index forward at that passthrough, and only when the node already had it, so an argument can retain a skip it had but never gain a new one. `TableFunctionNode::resolve` keeps its last-writer-wins contract on purpose: making membership monotonic there would re-create the overly broad skip that `da1b0593205b2910` had to narrow, which previously broke error reporting for `cluster(name, numbers(...GLOBAL IN...))`. The test pins both halves of that condition. The first added query is the reproducer and fails without the fix. The second asserts, via `EXPLAIN QUERY TREE`, that a nested non-`view` table function which was legitimately resolved keeps its alias in the query tree; that arm fails if the index is carried forward unconditionally instead of only when already present. The producer defect predates `88b22b8fb66c115` (ClickHouse#108645); it arrived with the passthroughs in `f1c071de7408ee2` and `eaeaa7929d78795`. ClickHouse#108645 made it visible by removing the `extractTableExpressions` IDENTIFIER tolerance that used to discard the leaked node. Release exposure, measured with the current per-branch rolling binaries from builds.clickhouse.com against all five active release branches. The versions below are server-reported build metadata, not release tags: only 26.6.2.158 also exists as a published tag, and every other number is ahead of the newest tag on its line. The identity of each run is its Build ID, asserted with `SELECT lower(buildId())` before every verdict. 26.7.3.11 tolerance present returns 2, correct 26.6.2.158 tolerance present returns 2, correct 26.5.7.5 tolerance present returns 2, correct 26.3.17.108 no tolerance Code: 49 LOGICAL_ERROR, 5/5 runs 25.8.29.49 no passthrough Code: 49, different message and throw site The 26.3 failure has the same root cause, but it throws from a different place. Master throws at `IQueryTreeNode::assertTableExpression` reached through `QueryNode::getJoinTreeNodeTyped`; neither symbol exists on any release branch, because `88b22b8fb66c115` introduced both. On 26.3 the throw happens inside `extractTableExpressions` itself, with that branch's older message wording. So 26.3 is affected and this fix applies there (the source hunk cherry-picks cleanly onto that branch, though the backport needs the new test file placed by hand because it does not exist on 26.3); a `v26.3-must-backport` label is the route. 25.8 predates the passthrough this change touches and fails earlier inside `resolveExpressionNode` with `TABLE_FUNCTION ... is not allowed in expression context`, which this fix does not address. Found by the AST fuzzer on master, STID 3981-42df, commit `bffd1f1bc64a0d8c11066ca1852b534b043a99a6`, check `AST fuzzer (amd_tsan)`. Related: ClickHouse#83442 Co-Authored-By: Claude Fable 5 <[email protected]>
|
This breaks compatibility with previous versions. |
Add an
ITableExpressionNodebase class for query tree nodes that can act as a column source, and remove the genericweak_pointersvector (and theQueryTreeNodeWeakPtr/QueryTreeWeakNodes/QueryTreeNodesDequetypedefs) fromIQueryTreeNode.ColumnNodenow holds a single typedstd::weak_ptr<ITableExpressionNode>source instead of a slot in the generic weak-pointer array, andgetColumnSource/getColumnSourceOrNullreturn aTableExpressionNodePtr. The node classes usable as a column source --TableNode,TableFunctionNode,QueryNode,UnionNode,JoinNode,ArrayJoinNode,InterpolateNodeand the newLambdaArgumentsNode-- derive fromITableExpressionNode.Lambda arguments are now represented by a dedicated
LambdaArgumentsNodethat holds the argument names and their resolved types and serves as the column source for the lambda parameters, replacing the previous list of argument identifier / column nodes.resolveLambdabinds parameters by name, and the planner reconstructs the (name, type) pairs from the node.cloneAndReplaceis narrowed to operate on table expressions only: itsReplacementMapis keyed byconst ITableExpressionNode *and the clone consults it only for nodes whoseasTableExpressionis non-null.Changelog category (leave one):