-
Notifications
You must be signed in to change notification settings - Fork 29k
[SPARK-27692][SQL] Add new optimizer rule to evaluate the deterministic scala udf only once if all inputs are literals #24593
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
Closed
Closed
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
efb2242
Add optimizer rule to evaluate deterministic literal udf once
skambha 3e83db9
Add a test
skambha 0cfa744
Add nested testcase
skambha 6d87778
fix the avro test
skambha 7651214
Fix ALSSuite tests to capture the error message that is in the Exception
skambha 98154a2
Add comments
skambha b344b6c
Added the optimization under a conf property that defaults to false
skambha b348cd5
small changes to config name and remove diffs to other tests
skambha 7d54787
Move rule and test to new file respectively - review comment
skambha ee5fa4e
rename
skambha 7b98cad
renames.. and add more tests
skambha 93241b3
add join testcase
skambha File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
39 changes: 39 additions & 0 deletions
39
...c/main/scala/org/apache/spark/sql/catalyst/optimizer/DeterministicLiteralUDFFolding.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.apache.spark.sql.catalyst.optimizer | ||
|
|
||
| import org.apache.spark.sql.catalyst.expressions.{Literal, ScalaUDF} | ||
| import org.apache.spark.sql.catalyst.plans.logical._ | ||
| import org.apache.spark.sql.catalyst.rules._ | ||
| import org.apache.spark.sql.internal.SQLConf | ||
|
|
||
| /** | ||
| * If the UDF is deterministic and if the children are all literal, we can replace the udf | ||
| * with the output of the udf serialized | ||
| */ | ||
| object DeterministicLiteralUDFFolding extends Rule[LogicalPlan] { | ||
| def apply(plan: LogicalPlan): LogicalPlan = | ||
| if (!SQLConf.get.deterministicLiteralUdfFoldingEnabled) { | ||
| plan | ||
| } else plan transformAllExpressions { | ||
| case udf @ ScalaUDF(_, dataType, children, _, _, _, _, _) | ||
| if udf.deterministic && children.forall(_.isInstanceOf[Literal]) => | ||
| val res = udf.eval(null) | ||
| Literal(res, dataType) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
92 changes: 92 additions & 0 deletions
92
sql/core/src/test/scala/org/apache/spark/sql/DeterministicLiteralUDFFoldingSuite.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.apache.spark.sql | ||
|
|
||
| import org.apache.spark.sql.catalyst.expressions.ScalaUDF | ||
| import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan | ||
| import org.apache.spark.sql.functions.udf | ||
| import org.apache.spark.sql.internal.SQLConf | ||
| import org.apache.spark.sql.test.SharedSQLContext | ||
|
|
||
| class DeterministicLiteralUDFFoldingSuite extends QueryTest with SharedSQLContext { | ||
| import testImplicits._ | ||
|
|
||
| test("Deterministic and literal UDF optimization") { | ||
| def udfNodesCount(plan: LogicalPlan): Int = { | ||
| plan.expressions.head.children.collect({ | ||
| case f: ScalaUDF => f | ||
| }).length | ||
| } | ||
|
|
||
| val foo = udf(() => Math.random()).asNondeterministic() | ||
| spark.udf.register("random0", foo) | ||
| assert(!foo.deterministic) | ||
| val foo2 = udf((x: String, i: Int) => x.length + i) | ||
| spark.udf.register("mystrlen", foo2) | ||
| assert(foo2.deterministic) | ||
|
|
||
| Seq(("true", (1, 0, 0, 1)), ("false", (1, 1, 1, 1))).foreach { case (flag, expectedCounts) => | ||
| withSQLConf(SQLConf.DETERMINISTIC_LITERAL_UDF_FOLDING_ENABLED.key -> flag) { | ||
| // Non deterministic | ||
| val plan = sql("SELECT random0()").queryExecution.optimizedPlan | ||
| assert(udfNodesCount(plan) == expectedCounts._1) | ||
|
|
||
| // udf is deterministic and args are literal | ||
| assert(sql("SELECT mystrlen('abc', 1)").head().getInt(0) == 4) | ||
| val plan2 = sql("SELECT mystrlen('abc', 1)").queryExecution.optimizedPlan | ||
| assert(udfNodesCount(plan2) == expectedCounts._2) | ||
| val plan3 = sql("SELECT mystrlen('abc', mystrlen('c', 1))").queryExecution.optimizedPlan | ||
| assert(udfNodesCount(plan3) == expectedCounts._3) | ||
|
|
||
| // udf is deterministic and args are not literal | ||
| withTempView("temp1") { | ||
| val df = sparkContext.parallelize( | ||
| (1 to 10).map(i => i.toString)).toDF("i1") | ||
| df.createOrReplaceTempView("temp1") | ||
| val plan = sql("SELECT mystrlen(i1, 1) FROM temp1").queryExecution.optimizedPlan | ||
| assert(udfNodesCount(plan) == expectedCounts._4) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| test("udf folding rule in join") { | ||
| withTempView("temp1") { | ||
| val df = sparkContext.parallelize((1 to 5).map(i => i.toString)).toDF("i1") | ||
| df.createOrReplaceTempView("temp1") | ||
| val foo = udf((x: String, i: Int) => x.length + i) | ||
| spark.udf.register("mystrlen1", foo) | ||
| assert(foo.deterministic) | ||
|
|
||
| val query = "SELECT mystrlen1(i1, 1) FROM temp1, " + | ||
| "(SELECT mystrlen1('abc', mystrlen1('c', 1)) AS ref) WHERE mystrlen1(i1, ref) > 1" | ||
| assert(sql(query).count() == 5) | ||
|
|
||
| withSQLConf(SQLConf.DETERMINISTIC_LITERAL_UDF_FOLDING_ENABLED.key -> "true") { | ||
| val exception = intercept[AnalysisException] { | ||
| sql(query).count() | ||
| } | ||
| assert(exception.message.startsWith("Detected implicit cartesian product")) | ||
|
|
||
| withSQLConf(SQLConf.CROSS_JOINS_ENABLED.key -> "true") { | ||
| assert(sql(query).count() == 5) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This udf optimization rule is as part of the operator optimization batch. One other option we could consider is to move it after the 'Check Cartesian Products' batch.