This is an automated email from the ASF dual-hosted git repository.
rui-mo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gluten.git
The following commit(s) were added to refs/heads/main by this push:
new ac541428b6 [CORE] Extend non-foldable IN support to V2 scans and
projections (#13614)
ac541428b6 is described below
commit ac541428b684c64e5cfdce31f1bd1d3cb7fe4485
Author: kevinwilfong <[email protected]>
AuthorDate: Thu Nov 19 12:23:52 2026 -0800
[CORE] Extend non-foldable IN support to V2 scans and projections (#13614)
---
.../gluten/backendsapi/bolt/BoltRuleApi.scala | 1 -
.../gluten/backendsapi/clickhouse/CHRuleApi.scala | 1 -
.../gluten/backendsapi/velox/VeloxRuleApi.scala | 1 -
.../gluten/expression/ExpressionConverter.scala | 35 +++-
.../extension/columnar/rewrite/RewriteIn.scala | 79 ---------
.../expressions/GlutenExpressionMappingSuite.scala | 179 ++++++++++++++++++++-
6 files changed, 205 insertions(+), 91 deletions(-)
diff --git
a/backends-bolt/src/main/scala/org/apache/gluten/backendsapi/bolt/BoltRuleApi.scala
b/backends-bolt/src/main/scala/org/apache/gluten/backendsapi/bolt/BoltRuleApi.scala
index 4cf2747b6a..f42882ae55 100644
---
a/backends-bolt/src/main/scala/org/apache/gluten/backendsapi/bolt/BoltRuleApi.scala
+++
b/backends-bolt/src/main/scala/org/apache/gluten/backendsapi/bolt/BoltRuleApi.scala
@@ -88,7 +88,6 @@ object BoltRuleApi {
Validators.newValidator(conf, offloads)
val rewrites =
Seq(
- RewriteIn,
RewriteMultiChildrenCount,
RewriteJoin,
PullOutPreProject,
diff --git
a/backends-clickhouse/src/main/scala/org/apache/gluten/backendsapi/clickhouse/CHRuleApi.scala
b/backends-clickhouse/src/main/scala/org/apache/gluten/backendsapi/clickhouse/CHRuleApi.scala
index 0a694ce696..d4ef183133 100644
---
a/backends-clickhouse/src/main/scala/org/apache/gluten/backendsapi/clickhouse/CHRuleApi.scala
+++
b/backends-clickhouse/src/main/scala/org/apache/gluten/backendsapi/clickhouse/CHRuleApi.scala
@@ -102,7 +102,6 @@ object CHRuleApi {
Validators.newValidator(conf, offloads)
val rewrites =
Seq(
- RewriteIn,
RewriteMultiChildrenCount,
RewriteJoin,
PullOutPreProject,
diff --git
a/backends-velox/src/main/scala/org/apache/gluten/backendsapi/velox/VeloxRuleApi.scala
b/backends-velox/src/main/scala/org/apache/gluten/backendsapi/velox/VeloxRuleApi.scala
index 07de0ab0f0..4fa6cbd40d 100644
---
a/backends-velox/src/main/scala/org/apache/gluten/backendsapi/velox/VeloxRuleApi.scala
+++
b/backends-velox/src/main/scala/org/apache/gluten/backendsapi/velox/VeloxRuleApi.scala
@@ -107,7 +107,6 @@ object VeloxRuleApi {
Validators.newValidator(conf, offloads)
val rewrites =
Seq(
- RewriteIn,
RewriteMultiChildrenCount,
RewriteJoin,
PullOutPreProject,
diff --git
a/gluten-substrait/src/main/scala/org/apache/gluten/expression/ExpressionConverter.scala
b/gluten-substrait/src/main/scala/org/apache/gluten/expression/ExpressionConverter.scala
index d915dc805f..dd006603d6 100644
---
a/gluten-substrait/src/main/scala/org/apache/gluten/expression/ExpressionConverter.scala
+++
b/gluten-substrait/src/main/scala/org/apache/gluten/expression/ExpressionConverter.scala
@@ -39,7 +39,29 @@ trait Transformable {
def getTransformer(childrenTransformers: Seq[ExpressionTransformer]):
ExpressionTransformer
}
-object ExpressionConverter extends SQLConfHelper with Logging {
+object ExpressionConverter extends SQLConfHelper with Logging with
PredicateHelper {
+
+ /**
+ * Rewrites non-foldable IN list entries as equalities for native
conversion, preserving the
+ * original Catalyst expression for Spark fallback.
+ */
+ private[gluten] def rewriteIn(condition: Expression): Expression = {
+ condition.transform {
+ // Expansion can evaluate the value more than once and regroup list
expressions.
+ // Struct equality is unsupported by the native converter.
+ case in: In
+ if in.deterministic && !in.value.dataType.isInstanceOf[StructType] &&
+ in.list.exists(!_.foldable) =>
+ val (foldableExprs, nonFoldableExprs) = in.list.partition(_.foldable)
+ val newIn = if (foldableExprs.isEmpty) {
+ None
+ } else {
+ Some(in.copy(list = foldableExprs))
+ }
+ // Keep conversion depth logarithmic for large lists, as for scan
conjuncts.
+ buildBalancedPredicate(newIn.toSeq ++
nonFoldableExprs.map(EqualTo(in.value, _)), Or)
+ }
+ }
/**
* Rebinds extraction paths handled by Spark's ProjectionOverSchema,
including maps and arrays.
@@ -515,11 +537,16 @@ object ExpressionConverter extends SQLConfHelper with
Logging {
},
cw
)
- case i: In =>
- if (i.list.exists(!_.foldable)) {
+ case i: In if i.list.exists(!_.foldable) =>
+ val rewritten = rewriteIn(i)
+ if (rewritten == i) {
throw new GlutenNotSupportException(
- s"In list option does not support non-foldable expression,
${i.list.map(_.sql)}")
+ s"Cannot rewrite IN with non-foldable list entries when the
expression is " +
+ s"nondeterministic or the value is struct-typed: ${i.sql}")
}
+ // Use the same conversion for validation and translation, preserving
the Spark expression.
+ replaceWithExpressionTransformer0(rewritten, attributeSeq,
expressionsMap)
+ case i: In =>
InTransformer(
substraitExprName,
replaceWithExpressionTransformer0(i.value, attributeSeq,
expressionsMap),
diff --git
a/gluten-substrait/src/main/scala/org/apache/gluten/extension/columnar/rewrite/RewriteIn.scala
b/gluten-substrait/src/main/scala/org/apache/gluten/extension/columnar/rewrite/RewriteIn.scala
deleted file mode 100644
index deec91dfb9..0000000000
---
a/gluten-substrait/src/main/scala/org/apache/gluten/extension/columnar/rewrite/RewriteIn.scala
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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.gluten.extension.columnar.rewrite
-
-import org.apache.spark.sql.catalyst.expressions.{EqualTo, Expression, In, Or}
-import org.apache.spark.sql.execution.{FileSourceScanExec, FilterExec,
SparkPlan}
-import org.apache.spark.sql.types.StructType
-
-/**
- * This rule rewrites the [[In]] if the list option contains non-foldable
value. A rewrite example:
- *
- * {{{
- * SELECT * FROM t WHERE c in (1, 2, c2)
- * =>
- * SELECT * FROM t WHERE c in (1, 2) or c = c2
- * }}}
- *
- * TODO: Remove this rule once Velox support the list option in `In` is not
literal.
- */
-object RewriteIn extends RewriteSingleNode {
- override def isRewritable(plan: SparkPlan): Boolean = {
- plan match {
- case _: FileSourceScanExec => true
- case _: FilterExec => true
- case _ => false
- }
- }
-
- private def shouldRewrite(e: Expression): Boolean = {
- e match {
- case in: In if !in.value.dataType.isInstanceOf[StructType] &&
in.list.exists(!_.foldable) =>
- // `EqualTo` does not allow struct type
- true
- case _ => false
- }
- }
-
- private def rewriteIn(condition: Expression): Expression = {
- condition.transform {
- case in: In if shouldRewrite(in) =>
- val (foldableExprs, nonFoldableExprs) = in.list.partition(_.foldable)
- assert(nonFoldableExprs.nonEmpty)
- val rewrittenExpr = nonFoldableExprs.map(expr => EqualTo(in.value,
expr)).reduce(Or)
- val newIn = if (foldableExprs.isEmpty) {
- None
- } else {
- Some(in.copy(list = foldableExprs))
- }
- (newIn ++ Seq(rewrittenExpr)).reduce(Or)
- }
- }
-
- override def rewrite(plan: SparkPlan): SparkPlan = {
- plan match {
- // TODO: Support datasource v2
- case scan: FileSourceScanExec if
scan.dataFilters.exists(_.find(shouldRewrite).isDefined) =>
- val newDataFilters = scan.dataFilters.map(rewriteIn)
- scan.copy(dataFilters = newDataFilters)
- case f: FilterExec if f.condition.find(shouldRewrite).isDefined =>
- val newCondition = rewriteIn(f.condition)
- f.copy(condition = newCondition)
- case _ => plan
- }
- }
-}
diff --git
a/gluten-ut/test/src/test/scala/org/apache/gluten/expressions/GlutenExpressionMappingSuite.scala
b/gluten-ut/test/src/test/scala/org/apache/gluten/expressions/GlutenExpressionMappingSuite.scala
index cc8bb5309e..942d012972 100644
---
a/gluten-ut/test/src/test/scala/org/apache/gluten/expressions/GlutenExpressionMappingSuite.scala
+++
b/gluten-ut/test/src/test/scala/org/apache/gluten/expressions/GlutenExpressionMappingSuite.scala
@@ -16,19 +16,25 @@
*/
package org.apache.gluten.expressions
+import org.apache.gluten.backendsapi.BackendsApiManager
import org.apache.gluten.config.GlutenConfig
-import org.apache.gluten.execution.ProjectExecTransformer
-import org.apache.gluten.expression.ExpressionMappings
+import org.apache.gluten.execution.{BasicScanExecTransformer,
BatchScanExecTransformerBase, FileSourceScanExecTransformer,
FilterExecTransformerBase, GlutenQueryComparisonTest, ProjectExecTransformer}
+import org.apache.gluten.expression.{ExpressionConverter, ExpressionMappings}
import org.apache.gluten.utils.BackendTestUtils
import org.apache.spark.SparkConf
-import org.apache.spark.sql.{GlutenQueryTest, Row}
-import org.apache.spark.sql.execution.ProjectExec
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.execution.{FileSourceScanExec, ProjectExec}
import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
+import org.apache.spark.sql.execution.datasources.v2.BatchScanExec
+import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DoubleType, IntegerType, StructType}
class GlutenExpressionMappingSuite
- extends GlutenQueryTest
+ extends GlutenQueryComparisonTest
with SharedSparkSession
with AdaptiveSparkPlanHelper {
@@ -107,4 +113,167 @@ class GlutenExpressionMappingSuite
assert(fallbackSummary.fallbackNodeToReason.flatMap(_.values).exists(_.contains(msg)))
}
}
+
+ private def hasNonFoldableIn(expression: Expression): Boolean = {
+ expression.exists {
+ case in: In => in.list.exists(!_.foldable)
+ case _ => false
+ }
+ }
+
+ test("rewrite preserves IN and NOT IN results with nulls") {
+ val value = BoundReference(0, IntegerType, nullable = true)
+ val option = BoundReference(1, IntegerType, nullable = true)
+ val lists = Seq(
+ Seq(Literal(1), Literal(2), option),
+ Seq(option),
+ Seq(Literal.create(null, IntegerType), option),
+ Seq(Literal(1), Add(option, Literal(1))))
+ for (list <- lists; negate <- Seq(false, true)) {
+ val in = In(value, list)
+ val expression = if (negate) Not(in) else in
+ val rewritten = ExpressionConverter.rewriteIn(expression)
+ assert(!hasNonFoldableIn(rewritten))
+ for (v <- Seq(null, 1, 2, 3); o <- Seq(null, 1, 2, 3)) {
+ val row = InternalRow(v, o)
+ assert(rewritten.eval(row) == expression.eval(row))
+ }
+ assert(ExpressionConverter.rewriteIn(rewritten) == rewritten)
+ }
+ }
+
+ test("literal-only and struct IN expressions are unchanged") {
+ val value = BoundReference(0, IntegerType, nullable = true)
+ val literalIn = In(value, Seq(Literal(1), Literal(2)))
+ assert(ExpressionConverter.rewriteIn(literalIn) == literalIn)
+ val structType = new StructType().add("a", IntegerType)
+ val structIn = In(
+ BoundReference(0, structType, nullable = true),
+ Seq(BoundReference(1, structType, nullable = true)))
+ assert(ExpressionConverter.rewriteIn(structIn) == structIn)
+ }
+
+ test("large non-foldable IN lists convert through a balanced OR tree") {
+ val value = AttributeReference("a", IntegerType, nullable = true)()
+ val option = AttributeReference("b", IntegerType, nullable = true)()
+ val entries = (1 to 4096).map(i => Add(option, Literal(i)))
+ def depth(expression: Expression): Int = {
+ 1 + expression.children.map(depth).foldLeft(0)(math.max)
+ }
+ for (foldable <- Seq(Seq.empty[Expression], Seq(Literal(0)))) {
+ val in = In(value, foldable ++ entries)
+ val rewritten = ExpressionConverter.rewriteIn(in)
+ assert(depth(rewritten) <= 16)
+ assert(rewritten.collect { case _: EqualTo => 1 }.size == entries.size)
+ assert(!hasNonFoldableIn(rewritten))
+ assert(ExpressionConverter.canReplaceWithExpressionTransformer(in,
Seq(value, option)))
+ }
+ }
+
+ test("conversion accepts dynamic IN and preserves unsupported cases") {
+ val value = AttributeReference("a", IntegerType, nullable = true)()
+ val option = AttributeReference("b", IntegerType, nullable = true)()
+ val in = In(value, Seq(Literal(1), option))
+ assert(ExpressionConverter.canReplaceWithExpressionTransformer(in,
Seq(value, option)))
+ assert(ExpressionConverter.canReplaceWithExpressionTransformer(Not(in),
Seq(value, option)))
+ withSQLConf(GlutenConfig.EXPRESSION_BLACK_LIST.key -> "equal") {
+ assert(!ExpressionConverter.canReplaceWithExpressionTransformer(in,
Seq(value, option)))
+ }
+
+ val structType = new StructType().add("a", IntegerType)
+ val structValue = AttributeReference("s1", structType, nullable = true)()
+ val structOption = AttributeReference("s2", structType, nullable = true)()
+ assert(!ExpressionConverter.canReplaceWithExpressionTransformer(
+ In(structValue, Seq(structOption)),
+ Seq(structValue, structOption)))
+
+ // Expansion duplicates the value expression; nondeterministic inputs must
fall back.
+ val doubleOption = AttributeReference("d", DoubleType, nullable = true)()
+ val randomIn = In(Rand(Literal(0L)), Seq(Literal(1.0), doubleOption))
+ assert(ExpressionConverter.rewriteIn(randomIn) == randomIn)
+ assert(!ExpressionConverter.canReplaceWithExpressionTransformer(randomIn,
Seq(doubleOption)))
+ }
+
+ for (format <- Seq("parquet", "orc"); useV1 <- Seq(true, false)) {
+ val version = if (useV1) "V1" else "V2"
+ test(s"convert non-foldable IN in $version $format filters and
projections") {
+ withTempPath {
+ path =>
+ withTempView("rewrite_in") {
+ withSQLConf(
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.USE_V1_SOURCE_LIST.key -> (if (useV1) format else "")) {
+ withSQLConf(GlutenConfig.GLUTEN_ENABLED.key -> "false") {
+ sql("""SELECT * FROM VALUES
+ |(1, 9), (2, NULL), (3, 3), (4, 3), (5, 8), (NULL, 3)
+ |AS t(a, b)""".stripMargin)
+ .write.format(format).save(path.getCanonicalPath)
+ }
+ spark.read.format(format).load(path.getCanonicalPath)
+ .createOrReplaceTempView("rewrite_in")
+ val predicates = Seq(
+ "a IN (1, 2, b)",
+ "a NOT IN (1, 2, b)",
+ "a IN (b, b + 1)",
+ "a NOT IN (b, b + 1)",
+ "a IN (1, b + 1)",
+ "a NOT IN (1, CASE WHEN b > 2 THEN b + 1 ELSE b END)",
+ "a IN (1, NULL, b)"
+ )
+ predicates.foreach {
+ predicate =>
+ runQueryAndCompare(s"SELECT * FROM rewrite_in WHERE
$predicate") {
+ df =>
+ val scans = collect(df.queryExecution.executedPlan) {
+ case scan: BasicScanExecTransformer => scan
+ }
+ assert(scans.size == 1)
+ val scan = scans.head
+ assert(if (useV1)
scan.isInstanceOf[FileSourceScanExecTransformer]
+ else scan.isInstanceOf[BatchScanExecTransformerBase])
+ val originalFilters = scan.scanFilters
+ assert(originalFilters.exists(hasNonFoldableIn))
+ if (
+ BackendsApiManager.getSparkPlanExecApiInstance
+ .supportPushDownFilterToScan(scan)
+ ) {
+ assert(scan.filterExprs().exists(hasNonFoldableIn))
+ assert(scan.filterExprs().forall(
+
ExpressionConverter.canReplaceWithExpressionTransformer(_, scan.output)))
+ } else {
+ // ClickHouse V1 Parquet scans only accept Spark's
translatable filters.
+ // The dynamic IN must instead be converted by the
native outer filter.
+ assert(!scan.filterExprs().exists(hasNonFoldableIn))
+ val filters = collect(df.queryExecution.executedPlan) {
+ case filter: FilterExecTransformerBase => filter
+ }
+ assert(filters.exists(filter =>
hasNonFoldableIn(filter.cond)))
+ }
+ }
+ runQueryAndCompare(s"SELECT a, b, $predicate AS matches FROM
rewrite_in") {
+ df =>
+ val projects = collect(df.queryExecution.executedPlan) {
+ case project: ProjectExecTransformer => project
+ }
+
assert(projects.exists(_.projectList.exists(hasNonFoldableIn)))
+ }
+ }
+ val scanConfig = if (useV1)
GlutenConfig.COLUMNAR_FILESCAN_ENABLED
+ else GlutenConfig.COLUMNAR_BATCHSCAN_ENABLED
+ withSQLConf(scanConfig.key -> "false") {
+ runQueryAndCompare(
+ "SELECT * FROM rewrite_in WHERE a NOT IN (1, 2, b)",
+ noFallBack = false) {
+ df =>
+ assert(collect(df.queryExecution.executedPlan) {
+ case scan: BatchScanExec if !useV1 => scan
+ case scan: FileSourceScanExec if useV1 => scan
+ }.nonEmpty)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]