brijrajk commented on code in PR #12151: URL: https://github.com/apache/gluten/pull/12151#discussion_r3452539073
########## gluten-ut/test/src/test/scala/org/apache/gluten/sql/GlutenBloomFilterFallbackSuite.scala: ########## @@ -0,0 +1,151 @@ +/* + * 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.sql + +import org.apache.gluten.backendsapi.BackendsApiManager +import org.apache.gluten.config.GlutenConfig +import org.apache.gluten.execution.WholeStageTransformerSuite + +import org.apache.spark.sql.catalyst.FunctionIdentifier +import org.apache.spark.sql.catalyst.expressions.BloomFilterMightContain +import org.apache.spark.sql.catalyst.expressions.ExpressionInfo +import org.apache.spark.sql.catalyst.expressions.aggregate.BloomFilterAggregate +import org.apache.spark.sql.internal.SQLConf + +/** + * Regression tests for https://github.com/apache/gluten/issues/12013. + * + * Verifies that `BloomFilterMightContainJointRewriteRule`, registered as a `Rule[LogicalPlan]` via + * `injectOptimizerRule`, correctly handles whole-stage AQE fallback scenarios where one or both + * bloom-filter stages revert to vanilla Spark execution. + */ +class GlutenBloomFilterFallbackSuite extends WholeStageTransformerSuite { + protected val resourcePath: String = null + protected val fileFormat: String = null + + import testImplicits._ + + private val funcIdBloomFilterAgg = FunctionIdentifier("bloom_filter_agg") + private val funcIdMightContain = FunctionIdentifier("might_contain") + + override def beforeAll(): Unit = { + super.beforeAll() + spark.sessionState.functionRegistry.registerFunction( + funcIdBloomFilterAgg, + new ExpressionInfo(classOf[BloomFilterAggregate].getName, "bloom_filter_agg"), + args => + args.size match { + case 1 => new BloomFilterAggregate(args(0)) + case 2 => new BloomFilterAggregate(args(0), args(1)) + case 3 => new BloomFilterAggregate(args(0), args(1), args(2)) + case _ => throw new IllegalArgumentException("bloom_filter_agg requires 1-3 arguments") + } + ) + spark.sessionState.functionRegistry.registerFunction( + funcIdMightContain, + new ExpressionInfo(classOf[BloomFilterMightContain].getName, "might_contain"), + args => BloomFilterMightContain(args(0), args(1))) + } + + override def afterAll(): Unit = { + spark.sessionState.functionRegistry.dropFunction(funcIdBloomFilterAgg) + spark.sessionState.functionRegistry.dropFunction(funcIdMightContain) + super.afterAll() + } + + private val veloxBloomFilterMaxNumBits = 4194304L + + // GLUTEN-12013: only filter stage falls back (threshold=2). + // bloom_filter_agg subquery runs natively and produces Velox-format bytes; + // the filter stage falls back via ExpandFallbackPolicy. The optimizer-level + // substitution ensures the fallback plan still uses VeloxBloomFilterMightContain + // so the JVM filter can read Velox-format bytes without a version mismatch. + testWithMinSparkVersion( + "GLUTEN-12013: bloom_filter_agg whole-stage fallback does not corrupt bloom filter bytes", + "3.3") { + if (BackendsApiManager.getSettings.requireBloomFilterAggMightContainJointFallback()) { + val table = "bloom_filter_test" + val numEstimatedItems = 5000000L + val sqlString = + s""" + |SELECT col positive_membership_test + |FROM $table + |WHERE might_contain( + | (SELECT bloom_filter_agg(col, + | cast($numEstimatedItems as long), + | cast($veloxBloomFilterMaxNumBits as long)) + | FROM $table), col) + |""".stripMargin + withTempView(table) { + (Seq(Long.MinValue, 0, Long.MaxValue) ++ (1L to 200000L)) + .toDF("col") + .createOrReplaceTempView(table) + // Threshold=2: FilterExec fallback cost=2 triggers whole-stage fallback; agg cost=1 + // does not, so Stage 0 runs natively. ANSI off keeps agg cost at 1 on Spark 4.0+. + withSQLConf( + GlutenConfig.COLUMNAR_FILTER_ENABLED.key -> "false", + GlutenConfig.COLUMNAR_WHOLESTAGE_FALLBACK_THRESHOLD.key -> "2", + SQLConf.ANSI_ENABLED.key -> "false" + ) { + val df = spark.sql(sqlString) + // Must not throw: java.io.IOException: Unexpected Bloom filter version number. + assert(df.collect().length == 200003) + } + } + } + } + + // GLUTEN-12013: both stages fall back (threshold=1). + // Stage 0's inherent transition cost of 1 meets the threshold so ExpandFallbackPolicy + // promotes it to a whole-stage fallback too. Stage 0 produces Spark-format bytes; + // Stage 1 must use vanilla BloomFilterMightContain (not VeloxBloomFilterMightContain) + // to read them. The optimizer rule rewrites both sides together so when Stage 0 falls + // back the whole query uses the vanilla variants end-to-end. + testWithMinSparkVersion( + "GLUTEN-12013: bloom_filter_agg whole-stage fallback when both stages fall back", + "3.3") { + if (BackendsApiManager.getSettings.requireBloomFilterAggMightContainJointFallback()) { + val table = "bloom_filter_test" + val numEstimatedItems = 5000000L + val sqlString = + s""" + |SELECT col positive_membership_test + |FROM $table + |WHERE might_contain( + | (SELECT bloom_filter_agg(col, + | cast($numEstimatedItems as long), + | cast($veloxBloomFilterMaxNumBits as long)) + | FROM $table), col) + |""".stripMargin + withTempView(table) { + (Seq(Long.MinValue, 0, Long.MaxValue) ++ (1L to 200000L)) + .toDF("col") + .createOrReplaceTempView(table) + // Threshold=1: both stages fall back. Stage 0 produces Spark-format bytes. + withSQLConf( + GlutenConfig.COLUMNAR_FILTER_ENABLED.key -> "false", + GlutenConfig.COLUMNAR_WHOLESTAGE_FALLBACK_THRESHOLD.key -> "1", + SQLConf.ANSI_ENABLED.key -> "false" + ) { + val df = spark.sql(sqlString) + // Must not throw: java.io.IOException: Unexpected Bloom filter version number. + assert(df.collect().length == 200003) Review Comment: Good catch, thanks @rdtr! You are right -- VeloxBloomFilterMightContain and VeloxBloomFilterAggregate call Velox JNI even in JVM row-mode fallback, so both sides always produce/consume Velox-format bytes regardless of whether the stage is wrapped in a FallbackNode. Fixed in the latest push: each test now also asserts that `velox_might_contain` appears in the optimized plan, which proves the optimizer rule ran (the query not throwing alone does not distinguish the case where both sides accidentally remain as vanilla Spark and produce consistent Spark-format bytes). ########## backends-velox/src/main/scala/org/apache/gluten/extension/BloomFilterMightContainJointRewriteRule.scala: ########## @@ -21,63 +21,38 @@ import org.apache.gluten.expression.VeloxBloomFilterMightContain import org.apache.gluten.expression.aggregate.VeloxBloomFilterAggregate import org.apache.spark.sql.SparkSession -import org.apache.spark.sql.catalyst.expressions.{BinaryExpression, BloomFilterMightContain, Expression} -import org.apache.spark.sql.catalyst.expressions.aggregate.{BloomFilterAggregate, TypedImperativeAggregate} +import org.apache.spark.sql.catalyst.expressions.BloomFilterMightContain +import org.apache.spark.sql.catalyst.expressions.aggregate.{AggregateExpression, BloomFilterAggregate} +import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan import org.apache.spark.sql.catalyst.rules.Rule -import org.apache.spark.sql.execution.SparkPlan -case class BloomFilterMightContainJointRewriteRule( - spark: SparkSession, - isBloomFilterStatFunction: Boolean) - extends Rule[SparkPlan] { - override def apply(plan: SparkPlan): SparkPlan = { - if (isBloomFilterStatFunction || !GlutenConfig.get.enableNativeBloomFilter) { +/** + * Optimizer rule that rewrites `BloomFilterAggregate` -> `VeloxBloomFilterAggregate` and + * `BloomFilterMightContain` -> `VeloxBloomFilterMightContain` at the logical plan level. + * + * Running as an optimizer rule ensures the substitution is captured in the `originalPlan` snapshot + * that [[org.apache.gluten.extension.columnar.heuristic.ExpandFallbackPolicy]] uses when promoting + * an individual stage fallback to a whole-stage AQE fallback. This guarantees that both sides of + * the bloom-filter pair always produce and consume the same byte format, regardless of whether + * stages fall back to JVM execution after AQE re-planning. + */ +case class BloomFilterMightContainJointRewriteRule(spark: SparkSession) + extends Rule[LogicalPlan] { + + override def apply(plan: LogicalPlan): LogicalPlan = { + if (!GlutenConfig.get.enableNativeBloomFilter) { Review Comment: Done -- added a third test `"GLUTEN-12013: native bloom filter disabled skips rewrite and produces correct results"` that sets `spark.gluten.sql.native.bloomFilter=false` and asserts: 1. The query produces the correct result count (200003). 2. The optimized plan does NOT contain `velox_might_contain`, confirming the rule early-exited and left vanilla `BloomFilterMightContain` in place. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
