Copilot commented on code in PR #12751: URL: https://github.com/apache/gluten/pull/12751#discussion_r3759756893
########## backends-velox/src/main/scala/org/apache/gluten/extension/RemoveBloomFilterToRecoverExchangeReuse.scala: ########## @@ -0,0 +1,502 @@ +/* + * 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 + +import org.apache.gluten.execution.{BatchScanExecTransformer, FileSourceScanExecTransformer, FilterExecTransformer} +import org.apache.gluten.expression.VeloxBloomFilterMightContain + +import org.apache.spark.internal.Logging +import org.apache.spark.sql.SparkSession +import org.apache.spark.sql.catalyst.expressions.{And, Attribute, BloomFilterMightContain, Expression, PredicateHelper, XxHash64} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.execution.{BinaryExecNode, FileSourceScanExec, FilterExec, SparkPlan} +import org.apache.spark.sql.execution.adaptive.{BroadcastQueryStageExec, ShuffleQueryStageExec} +import org.apache.spark.sql.execution.datasources.v2.BatchScanExec +import org.apache.spark.sql.execution.exchange.ReusedExchangeExec +import org.apache.spark.sql.types.DataType + +import java.util.IdentityHashMap +import java.util.concurrent.ConcurrentHashMap + +import scala.collection.JavaConverters._ +import scala.collection.mutable.ArrayBuffer + +/** + * Fixes a performance regression in TPC-DS Q24a/Q24b (and similar) queries on the Gluten Velox + * backend where asymmetric runtime BloomFilters injected by Spark cause the same large table (e.g. + * store_sales) to have different BF counts on the two join-input sides. This asymmetry makes + * canonicalized sameResult=false => ReusedExchange is disabled => the large table is scanned twice. + * + * The fix: on the join-input side that has MORE BloomFilters, precisely strip the extra BF + * conjuncts so that the canonicalized plans of the main query and the HAVING correlated + * scalar-subquery side become identical. Spark's native ReuseExchange rule then kicks in naturally, + * eliminating the duplicate scan. + * + * The apply() method runs in 5 phases: + * + * STEP1 Collect: traverse ALL physical joins (including those inside subqueries) in the current + * plan and build one JoinInputEntry per join child (leaf-tables-set, output-column signature, + * unique BF-keys set). STEP2 Publish: for every entry that carries BFs, publish its bfKeys into a + * cross-apply global pool. For each group (leafTables, outputSig) the pool retains the HISTORICALLY + * SMALLEST bfKeys set. STEP3 Group: cluster join inputs by (leafTables-set, output-signature) so + * that we only compare BF count asymmetry between join inputs that are actually eligible for + * exchange reuse. STEP4 Find asymmetry: within the same local group first look for a baseline whose + * bfKeys is a proper subset of entry.bfKeys and strictly smaller. If not found, fall back to the + * cross-apply global pool. If baseline exists and extraBf = entry.bfKeys -- baseline.bfKeys is + * non-empty, mark the entry for stripping. STEP5 Strip precisely: for each marked entry, walk + * top-down through all physical Filters under its subtree and drop ONLY those BF conjuncts whose + * exprKey is NOT in baseline.bfExprKeys. Leave isnotnull / other predicates intact. Finally graft + * the rewritten subtrees back into the original BinaryJoin's left/right children. + */ +case class RemoveBloomFilterToRecoverExchangeReuse(spark: SparkSession) + extends Rule[SparkPlan] + with PredicateHelper + with Logging { + + /** + * Cross-apply shared pool of the "historically smallest bfKeys set" per exchange-reuse group. + * + * Rationale: in Q24a the main query (bfCount=2) and the HAVING scalar subquery (bfCount=1) arrive + * in two completely separate apply() invocations because AQE splits them across different query + * stages. A purely local STEP4 would never see the smaller side as baseline -- the pool bridges + * that gap. + * + * Key = (leafTableNames, outputSignature): dimensions that uniquely define an exchange-reuse + * group. + * - leafTableNames: all leaf table names under this join input (e.g. {store_sales} or + * {store_sales,store_returns,store,item,customer} after multi-way joins) + * - outputSignature: sequence of (column-name, data-type) for the join input's output. Only + * join inputs sharing the exact same pair qualify for exchange reuse against each other. + * + * Value = Set[String] (bfExprKeys): the smallest bfExprKeys set historically published for this + * group. Encoding: see exprKey() -- "probe=<attr>:<type>|seed=<long|NONE>" On publish we only + * update if the new size is strictly smaller. On lookup only a strict proper-subset ("globalMin + * subsetOf entryBfKeys and globalMin != entryBfKeys") is returned as a valid baseline. + */ + private val globalMinBfKeys = + new ConcurrentHashMap[(Set[String], Seq[(String, DataType)]), Set[String]]() Review Comment: `globalMinBfKeys` is mutable state that appears to persist for the lifetime of the rule instance/session, which can (1) leak memory over time as new (leafTables, outputSig) keys accumulate, and (2) cause cross-query interference (a baseline from an earlier query can trigger stripping in an unrelated later query that happens to share the same key). Consider scoping this cache to a single SQL execution (e.g., key by Spark SQL execution id / query execution id) and adding a cleanup strategy (remove on completion, or bounded/TTL cache) to prevent unbounded growth and unintended stripping across queries. -- 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]
