Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-50749][SQL] Fix ordering bug in CommutativeExpression.gatherCommutative method #49392

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1354,19 +1354,24 @@ trait UserDefinedExpression {
}

trait CommutativeExpression extends Expression {
/** Collects adjacent commutative operations. */
private def gatherCommutative(
/**
* Collects adjacent commutative operations.
*
* Exposed for testing
*/
private[spark] def gatherCommutative(
e: Expression,
f: PartialFunction[CommutativeExpression, Seq[Expression]]): Seq[Expression] = {
val resultBuffer = scala.collection.mutable.Buffer[Expression]()
val stack = scala.collection.mutable.Stack[Expression](e)
val queue = scala.collection.mutable.Queue[Expression](e)

// [SPARK-49977]: Use iterative approach to avoid creating many temporary List objects
// for deep expression trees through recursion.
while (stack.nonEmpty) {
stack.pop() match {
while (queue.nonEmpty) {
val current = queue.dequeue()
current match {
case c: CommutativeExpression if f.isDefinedAt(c) =>
stack.pushAll(f(c))
queue ++= f(c)
case other =>
resultBuffer += other.canonicalized
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -479,4 +479,17 @@ class CanonicalizeSuite extends SparkFunSuite {
}
}
}

test("unit test for gatherCommutative()") {
val addExpression = Add(
Literal(1),
Add(
Literal(2),
Literal(3)
)
)
val commutativeExpressions = addExpression.gatherCommutative(addExpression,
{ case Add(l, r, _) => Seq(l, r)})
assert(commutativeExpressions == Seq(Literal(1), Literal(2), Literal(3)))
}
}
Loading