You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by we...@apache.org on 2024/10/22 01:32:26 UTC

(spark) branch master updated: [SPARK-50058][SQL] Factor out plan normalization functions to later use those in single-pass Analyzer testing

This is an automated email from the ASF dual-hosted git repository.

wenchen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new d5419ab0960e [SPARK-50058][SQL] Factor out plan normalization functions to later use those in single-pass Analyzer testing
d5419ab0960e is described below

commit d5419ab0960e1a32e5505c1045b1563a829f6eeb
Author: Vladimir Golubev <vl...@databricks.com>
AuthorDate: Tue Oct 22 09:31:49 2024 +0800

    [SPARK-50058][SQL] Factor out plan normalization functions to later use those in single-pass Analyzer testing
    
    ### What changes were proposed in this pull request?
    
    Factor out plan normalization functions to later use those in single-pass Analyzer testing.
    
    ### Why are the changes needed?
    
    In the single-pass Analyzer [proposal](https://docs.google.com/document/d/1dWxvrJV-0joGdLtWbvJ0uNyTocDMJ90rPRNWa4T56Og/edit?tab=t.0#bookmark=id.yjvozwxpjc5q) we discussed one of the ways to test the single-pass Analyzer - to run tests in dual mode (both single-pass and fixed-point Analyzers) and compare the logical plans. To do that we need to perform plan normalization.
    
    Context: https://issues.apache.org/jira/browse/SPARK-49834
    
    ### Does this PR introduce _any_ user-facing change?
    
    No.
    
    ### How was this patch tested?
    
    Existing tests.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    No.
    
    Closes #48584 from vladimirg-db/vladimirg-db/factor-out-normalize-plan.
    
    Authored-by: Vladimir Golubev <vl...@databricks.com>
    Signed-off-by: Wenchen Fan <we...@databricks.com>
---
 .../spark/sql/catalyst/plans/NormalizePlan.scala}  | 112 +++++----------------
 .../apache/spark/sql/catalyst/plans/PlanTest.scala |  95 +----------------
 2 files changed, 28 insertions(+), 179 deletions(-)

diff --git a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/plans/PlanTest.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/NormalizePlan.scala
similarity index 54%
copy from sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/plans/PlanTest.scala
copy to sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/NormalizePlan.scala
index e90a956ab4fd..3b691f4f8777 100644
--- a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/plans/PlanTest.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/NormalizePlan.scala
@@ -17,59 +17,20 @@
 
 package org.apache.spark.sql.catalyst.plans
 
-import org.scalactic.source
-import org.scalatest.Suite
-import org.scalatest.Tag
-
-import org.apache.spark.SparkFunSuite
-import org.apache.spark.sql.catalyst.SQLConfHelper
-import org.apache.spark.sql.catalyst.analysis.{GetViewColumnByNameAndOrdinal, SimpleAnalyzer}
+import org.apache.spark.sql.catalyst.analysis.GetViewColumnByNameAndOrdinal
 import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.catalyst.expressions.CodegenObjectFactoryMode
 import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
 import org.apache.spark.sql.catalyst.plans.logical._
-import org.apache.spark.sql.catalyst.util._
-import org.apache.spark.sql.internal.SQLConf
-
-/**
- * Provides helper methods for comparing plans.
- */
-trait PlanTest extends SparkFunSuite with PlanTestBase
 
-trait CodegenInterpretedPlanTest extends PlanTest {
-
-  override protected def test(
-      testName: String,
-      testTags: Tag*)(testFun: => Any)(implicit pos: source.Position): Unit = {
-    val codegenMode = CodegenObjectFactoryMode.CODEGEN_ONLY.toString
-    val interpretedMode = CodegenObjectFactoryMode.NO_CODEGEN.toString
-
-    super.test(testName + " (codegen path)", testTags: _*)(
-      withSQLConf(SQLConf.CODEGEN_FACTORY_MODE.key -> codegenMode) { testFun })(pos)
-    super.test(testName + " (interpreted path)", testTags: _*)(
-      withSQLConf(SQLConf.CODEGEN_FACTORY_MODE.key -> interpretedMode) { testFun })(pos)
-  }
-
-  protected def testFallback(
-      testName: String,
-      testTags: Tag*)(testFun: => Any)(implicit pos: source.Position): Unit = {
-    val codegenMode = CodegenObjectFactoryMode.FALLBACK.toString
-    super.test(testName + " (codegen fallback mode)", testTags: _*)(
-      withSQLConf(SQLConf.CODEGEN_FACTORY_MODE.key -> codegenMode) { testFun })(pos)
-  }
-}
-
-/**
- * Provides helper methods for comparing plans, but without the overhead of
- * mandating a FunSuite.
- */
-trait PlanTestBase extends PredicateHelper with SQLHelper with SQLConfHelper { self: Suite =>
+object NormalizePlan extends PredicateHelper {
+  def apply(plan: LogicalPlan): LogicalPlan =
+    normalizePlan(normalizeExprIds(plan))
 
   /**
    * Since attribute references are given globally unique ids during analysis,
    * we must normalize them to check if two different queries are identical.
    */
-  protected def normalizeExprIds(plan: LogicalPlan): LogicalPlan = {
+  def normalizeExprIds(plan: LogicalPlan): LogicalPlan = {
     plan transformAllExpressions {
       case s: ScalarSubquery =>
         s.copy(plan = normalizeExprIds(s.plan), exprId = ExprId(0))
@@ -100,13 +61,6 @@ trait PlanTestBase extends PredicateHelper with SQLHelper with SQLConfHelper { s
     }
   }
 
-  protected def rewriteNameFromAttrNullability(plan: LogicalPlan): LogicalPlan = {
-    plan.transformAllExpressions {
-      case a @ AttributeReference(name, _, false, _) =>
-        a.copy(name = s"*$name")(exprId = a.exprId, qualifier = a.qualifier)
-    }
-  }
-
   /**
    * Normalizes plans:
    * - Filter the filter conditions that appear in a plan. For instance,
@@ -115,11 +69,16 @@ trait PlanTestBase extends PredicateHelper with SQLHelper with SQLConfHelper { s
    * - Sample the seed will replaced by 0L.
    * - Join conditions will be resorted by hashCode.
    */
-  protected def normalizePlan(plan: LogicalPlan): LogicalPlan = {
+  def normalizePlan(plan: LogicalPlan): LogicalPlan = {
     plan transform {
       case Filter(condition: Expression, child: LogicalPlan) =>
-        Filter(splitConjunctivePredicates(condition).map(rewriteBinaryComparison)
-          .sortBy(_.hashCode()).reduce(And), child)
+        Filter(
+          splitConjunctivePredicates(condition)
+            .map(rewriteBinaryComparison)
+            .sortBy(_.hashCode())
+            .reduce(And),
+          child
+        )
       case sample: Sample =>
         sample.copy(seed = 0L)
       case Join(left, right, joinType, condition, hint) if condition.isDefined =>
@@ -131,15 +90,19 @@ trait PlanTestBase extends PredicateHelper with SQLHelper with SQLConfHelper { s
         }
 
         val newCondition =
-          splitConjunctivePredicates(condition.get).map(rewriteBinaryComparison)
-            .sortBy(_.hashCode()).reduce(And)
+          splitConjunctivePredicates(condition.get)
+            .map(rewriteBinaryComparison)
+            .sortBy(_.hashCode())
+            .reduce(And)
         Join(left, right, newJoinType, Some(newCondition), hint)
       case Project(projectList, child) =>
-        val projList = projectList.map { e =>
-          e.transformUp {
-            case g: GetViewColumnByNameAndOrdinal => g.copy(viewDDL = None)
+        val projList = projectList
+          .map { e =>
+            e.transformUp {
+              case g: GetViewColumnByNameAndOrdinal => g.copy(viewDDL = None)
+            }
           }
-        }.asInstanceOf[Seq[NamedExpression]]
+          .asInstanceOf[Seq[NamedExpression]]
         Project(projList, child)
       case c: KeepAnalyzedQuery => c.storeAnalyzedQuery()
     }
@@ -161,33 +124,4 @@ trait PlanTestBase extends PredicateHelper with SQLHelper with SQLConfHelper { s
     case LessThanOrEqual(l, r) if l.hashCode() > r.hashCode() => GreaterThanOrEqual(r, l)
     case _ => condition // Don't reorder.
   }
-
-  /** Fails the test if the two plans do not match */
-  protected def comparePlans(
-      plan1: LogicalPlan,
-      plan2: LogicalPlan,
-      checkAnalysis: Boolean = true): Unit = {
-    if (checkAnalysis) {
-      // Make sure both plan pass checkAnalysis.
-      SimpleAnalyzer.checkAnalysis(plan1)
-      SimpleAnalyzer.checkAnalysis(plan2)
-    }
-
-    val normalized1 = normalizePlan(normalizeExprIds(plan1))
-    val normalized2 = normalizePlan(normalizeExprIds(plan2))
-    if (normalized1 != normalized2) {
-      fail(
-        s"""
-          |== FAIL: Plans do not match ===
-          |${sideBySide(
-            rewriteNameFromAttrNullability(normalized1).treeString,
-            rewriteNameFromAttrNullability(normalized2).treeString).mkString("\n")}
-         """.stripMargin)
-    }
-  }
-
-  /** Fails the test if the two expressions do not match */
-  protected def compareExpressions(e1: Expression, e2: Expression): Unit = {
-    comparePlans(Filter(e1, OneRowRelation()), Filter(e2, OneRowRelation()), checkAnalysis = false)
-  }
 }
diff --git a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/plans/PlanTest.scala b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/plans/PlanTest.scala
index e90a956ab4fd..37baa66049de 100644
--- a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/plans/PlanTest.scala
+++ b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/plans/PlanTest.scala
@@ -23,10 +23,9 @@ import org.scalatest.Tag
 
 import org.apache.spark.SparkFunSuite
 import org.apache.spark.sql.catalyst.SQLConfHelper
-import org.apache.spark.sql.catalyst.analysis.{GetViewColumnByNameAndOrdinal, SimpleAnalyzer}
+import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer
 import org.apache.spark.sql.catalyst.expressions._
 import org.apache.spark.sql.catalyst.expressions.CodegenObjectFactoryMode
-import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
 import org.apache.spark.sql.catalyst.plans.logical._
 import org.apache.spark.sql.catalyst.util._
 import org.apache.spark.sql.internal.SQLConf
@@ -65,40 +64,8 @@ trait CodegenInterpretedPlanTest extends PlanTest {
  */
 trait PlanTestBase extends PredicateHelper with SQLHelper with SQLConfHelper { self: Suite =>
 
-  /**
-   * Since attribute references are given globally unique ids during analysis,
-   * we must normalize them to check if two different queries are identical.
-   */
-  protected def normalizeExprIds(plan: LogicalPlan): LogicalPlan = {
-    plan transformAllExpressions {
-      case s: ScalarSubquery =>
-        s.copy(plan = normalizeExprIds(s.plan), exprId = ExprId(0))
-      case s: LateralSubquery =>
-        s.copy(plan = normalizeExprIds(s.plan), exprId = ExprId(0))
-      case e: Exists =>
-        e.copy(plan = normalizeExprIds(e.plan), exprId = ExprId(0))
-      case l: ListQuery =>
-        l.copy(plan = normalizeExprIds(l.plan), exprId = ExprId(0))
-      case a: AttributeReference =>
-        AttributeReference(a.name, a.dataType, a.nullable)(exprId = ExprId(0))
-      case OuterReference(a: AttributeReference) =>
-        OuterReference(AttributeReference(a.name, a.dataType, a.nullable)(exprId = ExprId(0)))
-      case a: Alias =>
-        Alias(a.child, a.name)(exprId = ExprId(0))
-      case OuterReference(a: Alias) =>
-        OuterReference(Alias(a.child, a.name)(exprId = ExprId(0)))
-      case ae: AggregateExpression =>
-        ae.copy(resultId = ExprId(0))
-      case lv: NamedLambdaVariable =>
-        lv.copy(exprId = ExprId(0), value = null)
-      case udf: PythonUDF =>
-        udf.copy(resultId = ExprId(0))
-      case udaf: PythonUDAF =>
-        udaf.copy(resultId = ExprId(0))
-      case a: FunctionTableSubqueryArgumentExpression =>
-        a.copy(plan = normalizeExprIds(a.plan), exprId = ExprId(0))
-    }
-  }
+  protected def normalizeExprIds(plan: LogicalPlan): LogicalPlan =
+    NormalizePlan.normalizeExprIds(plan)
 
   protected def rewriteNameFromAttrNullability(plan: LogicalPlan): LogicalPlan = {
     plan.transformAllExpressions {
@@ -107,60 +74,8 @@ trait PlanTestBase extends PredicateHelper with SQLHelper with SQLConfHelper { s
     }
   }
 
-  /**
-   * Normalizes plans:
-   * - Filter the filter conditions that appear in a plan. For instance,
-   *   ((expr 1 && expr 2) && expr 3), (expr 1 && expr 2 && expr 3), (expr 3 && (expr 1 && expr 2)
-   *   etc., will all now be equivalent.
-   * - Sample the seed will replaced by 0L.
-   * - Join conditions will be resorted by hashCode.
-   */
-  protected def normalizePlan(plan: LogicalPlan): LogicalPlan = {
-    plan transform {
-      case Filter(condition: Expression, child: LogicalPlan) =>
-        Filter(splitConjunctivePredicates(condition).map(rewriteBinaryComparison)
-          .sortBy(_.hashCode()).reduce(And), child)
-      case sample: Sample =>
-        sample.copy(seed = 0L)
-      case Join(left, right, joinType, condition, hint) if condition.isDefined =>
-        val newJoinType = joinType match {
-          case ExistenceJoin(a: Attribute) =>
-            val newAttr = AttributeReference(a.name, a.dataType, a.nullable)(exprId = ExprId(0))
-            ExistenceJoin(newAttr)
-          case other => other
-        }
-
-        val newCondition =
-          splitConjunctivePredicates(condition.get).map(rewriteBinaryComparison)
-            .sortBy(_.hashCode()).reduce(And)
-        Join(left, right, newJoinType, Some(newCondition), hint)
-      case Project(projectList, child) =>
-        val projList = projectList.map { e =>
-          e.transformUp {
-            case g: GetViewColumnByNameAndOrdinal => g.copy(viewDDL = None)
-          }
-        }.asInstanceOf[Seq[NamedExpression]]
-        Project(projList, child)
-      case c: KeepAnalyzedQuery => c.storeAnalyzedQuery()
-    }
-  }
-
-  /**
-   * Rewrite [[BinaryComparison]] operator to keep order. The following cases will be
-   * equivalent:
-   * 1. (a = b), (b = a);
-   * 2. (a <=> b), (b <=> a).
-   * 3. (a > b), (b < a)
-   */
-  private def rewriteBinaryComparison(condition: Expression): Expression = condition match {
-    case EqualTo(l, r) => Seq(l, r).sortBy(_.hashCode()).reduce(EqualTo)
-    case EqualNullSafe(l, r) => Seq(l, r).sortBy(_.hashCode()).reduce(EqualNullSafe)
-    case GreaterThan(l, r) if l.hashCode() > r.hashCode() => LessThan(r, l)
-    case LessThan(l, r) if l.hashCode() > r.hashCode() => GreaterThan(r, l)
-    case GreaterThanOrEqual(l, r) if l.hashCode() > r.hashCode() => LessThanOrEqual(r, l)
-    case LessThanOrEqual(l, r) if l.hashCode() > r.hashCode() => GreaterThanOrEqual(r, l)
-    case _ => condition // Don't reorder.
-  }
+  protected def normalizePlan(plan: LogicalPlan): LogicalPlan =
+    NormalizePlan.normalizePlan(plan)
 
   /** Fails the test if the two plans do not match */
   protected def comparePlans(


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org