Repository navigation
Improve join planning - #71926
Improve join planning#71926
Conversation
|
This is an automated comment for commit af51dda with description of existing statuses. It's updated for the latest CI running ❌ Click here to open a full report in a separate page
Successful checks
|
e4fa492 to
982fb6a
Compare
| SELECT 't22', * FROM t1 JOIN t22 ON (t22.key == t22.key2 OR t1.id == t22.id) and t1.id == t22.idd; -- { serverError 403 } | ||
| SELECT 't22', * FROM t1 JOIN t22 ON (t1.id == t22.id OR t22.key == t22.key2) and t1.id == t22.idd; -- { serverError 403 } | ||
| SELECT 't22', * FROM t1 JOIN t22 ON (t1.id == t22.id OR t22.key == t22.key2) and (t1.id == t22.idd AND (t1.key2 = 'a1' OR t1.key2 = 'a2' OR t1.key2 = 'a3' OR t1.key2 = 'a4' OR t1.key2 = 'a5' OR t1.key2 = 'a6' OR t1.key2 = 'a7' OR t1.key2 = 'a8' OR t1.key2 = 'a9' OR t1.key2 = 'a10' OR t1.key2 = 'a11' OR t1.key2 = 'a12' OR t1.key2 = 'a13' OR t1.key2 = 'a14' OR t1.key2 = 'a15' OR t1.key2 = 'a16' OR t1.key2 = 'a17' OR t1.key2 = 'a18' OR t1.key2 = 'a19' OR t1.key2 = '111')); -- { serverError 403 } | ||
| SELECT 't22', * FROM t1 JOIN t22 ON t1.id == t22.idd and (t22.key == t22.key2 OR t1.id == t22.id); |
There was a problem hiding this comment.
Check the correctness of this again and introduce a setting to use the old join planning algorithm, but use the new one by default.
…racting-common-exprs' into improve-join-planning
…ons only from one table
| SELECT * FROM t1 JOIN t2 ON t2.key == t2.key2 OR t1.id == t2.id; -- { serverError INVALID_JOIN_ON_EXPRESSION } | ||
| SELECT * FROM t1 JOIN t2 ON (t2.key == t2.key2 AND (t1.key == t1.key2 AND t1.key != 'XXX' OR t1.id == t2.id)) AND t1.id == t2.id; -- { serverError INVALID_JOIN_ON_EXPRESSION } | ||
| SELECT * FROM t1 JOIN t2 ON t2.key == t2.key2 AND t1.key == t1.key2 AND t1.key != 'XXX' AND t1.id == t2.id OR t2.key == t2.key2 AND t1.id == t2.id AND t1.id == t2.id; -- { serverError NOT_IMPLEMENTED } | ||
| SELECT * FROM t1 JOIN t2 ON (t2.key == t2.key2 AND (t1.key == t1.key2 AND t1.key != 'XXX' OR t1.id == t2.id)) AND t1.id == t2.id; -- { serverError NOT_IMPLEMENTED } |
There was a problem hiding this comment.
The following join clauses is generated:
Clause1:
left_key_nodes:
__table1.id Int32
right_key_nodes:
__table2.id Int32
left_condition_nodes:
and(
equals(
__table1.key,
__table1.key2
),
notEquals(
__table1.key,
'XXX'_String
)
) UInt8
right_condition_nodes:
equals(
__table2.key,
__table2.key2
) UInt8,
Clause2:
left_key_nodes:
__table1.id Int32,
__table1.id Int32
right_key_nodes:
__table2.id Int32,
__table2.id Int32
right_condition_nodes:
equals(
__table2.key,
__table2.key2
) UInt8,
I think these are valid, but it is not implemented by partial_merge: Code: 48. DB::Exception: Only hash join supports multiple ORs for keys in JOIN ON section. (NOT_IMPLEMENTED)
| SELECT * FROM t1 JOIN t2 ON (t2.key == t2.key2 AND (t1.key == t1.key2 AND t1.key != 'XXX' OR t1.id == t2.id)) AND t1.id == t2.id; -- { serverError INVALID_JOIN_ON_EXPRESSION } | ||
| SELECT * FROM t1 JOIN t2 ON t2.key == t2.key2 AND t1.key == t1.key2 AND t1.key != 'XXX' AND t1.id == t2.id OR t2.key == t2.key2 AND t1.id == t2.id AND t1.id == t2.id; -- { serverError NOT_IMPLEMENTED } | ||
| SELECT * FROM t1 JOIN t2 ON (t2.key == t2.key2 AND (t1.key == t1.key2 AND t1.key != 'XXX' OR t1.id == t2.id)) AND t1.id == t2.id; -- { serverError NOT_IMPLEMENTED } | ||
| SELECT * FROM t1 JOIN t2 ON t2.key == t2.key2 AND t1.key == t1.key2 AND t1.key != 'XXX' AND t1.id == t2.id OR t2.key == t2.key2 AND t1.key == t2.key2 AND t1.key == t2.key; -- { serverError NOT_IMPLEMENTED } |
There was a problem hiding this comment.
This is optimized to ALL INNER JOIN default.t2 AS __table2 ON (__table2.key = __table2.key2) AND (__table1.id = __table2.id) due to the second part of the original query. The optimized join expression is an easy one, even partial_merge can execute it. Thus I had to change the query.
…racting-common-exprs' into improve-join-planning
…racting-common-exprs' into improve-join-planning
|
I tried to summarize the PR in a private conversation and I thought this message might have a good place in the PR to also have it publicly: As far as I understood the old join algorithm (that we can still use as is by With the new algorithm I tried to generalize it. The new algorithm walks the whole expression tree and tries to handle each
[1]We avoid building multiple join clauses if any of the following is true: [2]The cross product means that in the cross product of two sets of join clauses the resulting set will contain the concatenation of each possible pair, where the concatenation is done by And just a note about the motivation: with the new optimization about extracting common expressions we might convert expressions that is completely fine to use for joins into expressions that the old join planning cannot handle. On example for that is |
| result.asof_conditions = lhs.asof_conditions; | ||
| // And offset the indices from rhs according to lhs size | ||
| std::transform( | ||
| rhs.asof_conditions.begin(), |
There was a problem hiding this comment.
Even though I see handling of several asof conditions in JoinClause::dump, I'm not quite sure if we atually can have them. Don't you know in which case there would be several ones?
Received exception from server (version 24.12.1):
Code: 403. DB::Exception: Received from localhost:9000. DB::Exception: JOIN ASOF LEFT JOIN ... ON (t1.id = t2.id) AND (t1.t <= t2.te) AND (t1.t >= t2.te) ASOF JOIN expects exactly one inequality in ON section. (INVALID_JOIN_ON_EXPRESSION)
(query: SELECT * FROM t1
LEFT ASOF JOIN t2
ON t1.id = t2.id
AND t1.t <= t2.te
AND t1.t >= t2.te
;)
Received exception from server (version 24.12.1):
Code: 48. DB::Exception: Received from localhost:9000. DB::Exception: ASOF join doesn't support JOIN ON expression ASOF LEFT JOIN ... ON ((t1.id = t2.id) AND (t1.t <= t2.te)) OR ((t1.id2 = t2.id2) AND (t1.t <= t2.te)). (NOT_IMPLEMENTED)
(query: SELECT * FROM t1
LEFT ASOF JOIN t2
ON t1.id = t2.id
AND t1.t <= t2.te
OR t1.id2 = t2.id2
AND t1.t <= t2.te
;)
There was a problem hiding this comment.
Don't you know in which case there would be several ones?
It is also not clear to me. I rechecked it, and found two places (one, two) where it suggest that we shouldn't have a vector of ASOF conditions, but a single one. However as I am new to joins in ClickHouse, my main idea behind this was that JoinClause contains a vector of ASOF conditions, thus this should be able to combine them. I was trying to do the logically correct thing, so if our join algorithms would support multiple ASOF conditions, then JoinClause::concatClauses should produce the correct JoinClauses.
| = planner_context->getQueryContext()->getSettingsRef()[Setting::allow_experimental_join_condition]; | ||
| auto join_use_nulls = planner_context->getQueryContext()->getSettingsRef()[Setting::join_use_nulls]; | ||
| /// If join_use_nulls = true, the columns' nullability will be changed later which make this expression not right. | ||
| if (support_mixed_join_condition && !join_use_nulls) | ||
| { | ||
| /// expression involves both tables. | ||
| /// `expr1(left.col1, right.col2) == expr2(left.col3, right.col4)` | ||
| const auto * node = appendExpression(joined_dag, join_expression, planner_context, join_node); | ||
| join_clause.addResidualCondition(node); | ||
| } | ||
| else | ||
| { | ||
| throw Exception( | ||
| ErrorCodes::INVALID_JOIN_ON_EXPRESSION, | ||
| "JOIN {} join expression contains column from left and right table, you may try experimental support of this feature " | ||
| "by `SET allow_experimental_join_condition = 1`", | ||
| join_node.formatASTForErrorMessage()); |
There was a problem hiding this comment.
After #69910 allow_experimental_join_condition is by default, so need to throw exception only in unsupported case with join_use_nulls with proper message
ClickHouse/src/Planner/PlannerJoins.cpp
Lines 379 to 382 in ebe76f9
| const FunctionNode & function_node) | ||
| { | ||
| const auto & join_algorithms = planner_context->getQueryContext()->getSettingsRef()[Setting::join_algorithm]; | ||
| const auto is_hash_join_enabled = TableJoin::isEnabledAlgorithm(join_algorithms, JoinAlgorithm::HASH) |
There was a problem hiding this comment.
How it works in case of auto? Auto starts with hash join, but falls back on partial_merge in case of memory overflow, so if partial_merge doesn't support specific conditions we will get error (while switching?).
There was a problem hiding this comment.
How it works in case of auto?
I haven't checked how does this work exactly with auto for the reason that you mentioned: partial merge doesn't support everything, I just opted to disable this for auto in order to ensure we don't run into weird cases because of this. However I expect that it is handled properly in case of auto though, I think there is nothing to prevent the users to write a query with auto algorithm that works with hash, but not with partial_merge.
| if (function_name == "or") | ||
| { | ||
| for (const auto & child : function_node.getArguments()) | ||
| { | ||
| join_clauses.emplace_back(); | ||
|
|
||
| buildJoinClause( |
There was a problem hiding this comment.
Am I right that recursive call is redundant and in the future we can just perform a looping, as soon as functions are flattened in query tree pass?
There was a problem hiding this comment.
I think we don't do recursive call here and buildJoinClause only calls itself in case of AND functions. If you meant that, then I think we cannot easily replace that, as flattening the conditions only happens in LogicalExpressionOptimizerPass if and only when we can extract some subexpressions. But e.g.: A & (B & C) won't be flattened, because there is no common expression.
| DECLARE(Bool, allow_experimental_json_type, false, R"( | ||
| Allows creation of [JSON](../../sql-reference/data-types/newjson.md) data type. | ||
| )", BETA) ALIAS(enable_json_type) \ | ||
| DECLARE(Bool, allow_general_join_planning, true, R"( |
There was a problem hiding this comment.
Is it intended to be compatible with the current behavior, with allow_general_join_planning = false only being set in cases where there are unknown cases in the new implementation?”
There was a problem hiding this comment.
Is it intended to be compatible with the current behavior
Yes, I was trying to achieve that. I will trigger a force check for all performance tests to make sure I didn't introduce any performance degradation in any performance test.
with
allow_general_join_planning = falseonly being set in cases where there are unknown cases in the new implementation?”
Technically speaking allow_general_join_planning only affects how join clauses are built when the hash algorithm is enabled, because that can handle much more flexible join clauses and as far as I remember the problematic query (t1.id = t2.id AND t1.v < t2.v) OR (t1.id = t2.id AND t1.v2 < t2.v2) (which is rewritten to t1.id = t2.id AND (t1.v < t2.v OR t1.v2 < t2.v2) with optimize_extract_common_expressions = true) could only be executed with the hash algorithm.
| return buffer.str(); | ||
| } | ||
|
|
||
| JoinClause JoinClause::concatClauses(const JoinClause & lhs, const JoinClause & rhs) |
There was a problem hiding this comment.
Is it correct example?
| JoinClause JoinClause::concatClauses(const JoinClause & lhs, const JoinClause & rhs) | |
| /// concatClauses combines two join clauses into a single join clause with `AND` logic. | |
| /// Example: | |
| /// Expression `t1.a = t2.a AND t1.b = t2.b AND t1.x > 1` corresponds to caluse: Keys: (a, b) = (a, b), filter conditions: [greater(t1.x, 1)] | |
| /// Expression `t1.a = t2.a AND t1.c = t2.c AND t1.y < 2 AND t1.z + t2.z == 2` corresponds to caluse: Keys: (a, c) = (a, c), filter conditions: [less(t1.y, 2)], residual condtitions [equals(plus(t1.z, t2.z), 2)] | |
| /// Concatenated: Keys: (a, b, a, c) = (a, b, a, c), filter conditions: [greater(t1.x, 1), less(t1.y, 2)], residual condtitions [equals(plus(t1.z, t2.z), 2)] | |
| JoinClause JoinClause::concatClauses(const JoinClause & lhs, const JoinClause & rhs) |
There was a problem hiding this comment.
I think yes. However it is important to note that I don't build the AND function with all the parameters, just concant the key/condition nodes, which has the same semantic as and AND function.
Edit: I thought that only the first line of the comment is your addition, as I noticed my mistake fixed my answer too.
|
|
||
| if (left_expression_side != right_expression_side) | ||
| { | ||
| if (function_name == "or" || function_name == "and") |
There was a problem hiding this comment.
We have checked functon_name on line 272, so this assertion looks excessive
There was a problem hiding this comment.
Yes, but it is possible that we enter this branch because of is_asof_join_inequality, thus function name can be or or and in my opinion.
| for (auto & argument : arguments) | ||
| { | ||
| auto & child_res = built_clauses.at(argument.get()); | ||
| result.insert(result.end(), std::make_move_iterator(child_res.begin()), std::make_move_iterator(child_res.end())); |
There was a problem hiding this comment.
Shouldn't we clear child_res to avoid leaving empty structures after the move? It seems fine, though, since we won't access that map entry later, as we won't reach these child nodes anymore, right?
There was a problem hiding this comment.
Yes, we shouldn't reach the same node. The key of the map is IQueryTreeNode *, so as far as I understood we shouldn't reach the same node again. However I will add that clear() call. It doesn't take much but makes the code more robust. Debugging random crashes because of memory violation is not fun.
| std::stack<QueryTreeNodePtr> nodes_to_process; | ||
| nodes_to_process.push(join_expression); | ||
|
|
||
| while (!nodes_to_process.empty()) |
There was a problem hiding this comment.
Can we say that the algorithm below essentially builds a DNF by combining expressions into terms, as long as there is no == function inside? Could you confirm or point out how it differs?
There was a problem hiding this comment.
I see the similarity between DNF(/CNF) and what I implemented here, but I wouldn't say the result is a DNF (or CNF). The few differences:
- This algorithm tries to support arbitrary logical expressions, e.g.: XOR
- It won't convert expressions that are not following DNF(/CNF) for. E.g.:
NOT(A AND B)won't be converted intoNOT(A) OR NOT(B), but will try to create a single join clause from the former one. expression_sides.size() == 2is there to make sure we don't overcomplicate the join clauses. An arbitrary long logical expression that only contains expressions from a single side of the join can easily turned into a single join clause.
However the similarity is kind of similar to a DNF on the level of join clauses:
- A single join clause means a singe cojunction (as all of the filter conditions has to be evaluated true)
- A set of join clauses means a disjunction of those clauses
I will try to explain the algorithm in details.
| DROP TABLE IF EXISTS t2_lc; | ||
| DROP TABLE IF EXISTS t22; | ||
|
|
||
| SET enable_analyzer = 0; |
There was a problem hiding this comment.
@antaljanosbenjamin could you explain why the analyzer has been disabled here?
There was a problem hiding this comment.
Probably by mistake. I will check this once I am back from holidays. Hopefully we I didn't break anything.
Builds on top of #71537.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Allow more general join planning algorithm when hash join algorithm is enabled.
Documentation entry for user-facing changes
CI Settings (Only check the boxes if you know what you are doing):