You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kyuubi.apache.org by ul...@apache.org on 2023/03/16 04:58:50 UTC

[kyuubi] branch master updated: [KYUUBI #4330] Non-temporary views do not resolve to a specific real table

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

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


The following commit(s) were added to refs/heads/master by this push:
     new 25e7b2255 [KYUUBI #4330] Non-temporary views do not resolve to a specific real table
25e7b2255 is described below

commit 25e7b225536b9584e466433c9b6a02a2ce558c0c
Author: odone <od...@gmail.com>
AuthorDate: Thu Mar 16 12:58:41 2023 +0800

    [KYUUBI #4330] Non-temporary views do not resolve to a specific real table
    
    close #4330
    
    ### _Why are the changes needed?_
    
    ### _How was this patch tested?_
    - [x] Add some test cases that check the changes thoroughly including negative and positive cases if possible
    
    - [ ] Add screenshots for manual tests if appropriate
    
    - [x] [Run test](https://kyuubi.readthedocs.io/en/master/develop_tools/testing.html#running-tests) locally before make a pull request
    
    Closes #4503 from iodone/kyuubi-4330.
    
    Closes #4330
    
    d2c48e7a [odone] Instead of `optimizedPlan` with `analyzedPlan`
    12614d19 [odone] add skip permenent view support
    
    Authored-by: odone <od...@gmail.com>
    Signed-off-by: ulyssesyou <ul...@apache.org>
---
 docs/extensions/engines/spark/lineage.md           | 32 +++++++--
 ...arkOperationLineageQueryExecutionListener.scala |  2 +-
 .../helper/SparkSQLLineageParseHelper.scala        | 18 ++++-
 ...{SparkContextHelper.scala => LineageConf.scala} | 19 +++---
 .../spark/kyuubi/lineage/SparkContextHelper.scala  |  8 +++
 .../events/OperationLineageEventSuite.scala        | 40 +++++++++++
 .../helper/SparkSQLLineageParserHelperSuite.scala  | 77 ++++++++++++++++------
 7 files changed, 154 insertions(+), 42 deletions(-)

diff --git a/docs/extensions/engines/spark/lineage.md b/docs/extensions/engines/spark/lineage.md
index 8f2f76c9f..0f4b0c458 100644
--- a/docs/extensions/engines/spark/lineage.md
+++ b/docs/extensions/engines/spark/lineage.md
@@ -168,13 +168,31 @@ Add `org.apache.kyuubi.plugin.lineage.SparkOperationLineageQueryExecutionListene
 spark.sql.queryExecutionListeners=org.apache.kyuubi.plugin.lineage.SparkOperationLineageQueryExecutionListener
 ```
 
-### Settings for Lineage Logger and Path
+### Optional configuration
 
-#### Lineage Logger Path
+#### Whether to Skip Permanent View Resolution
 
-The location of all the engine operation lineage events go for the builtin JSON logger.
-We first need set `kyuubi.engine.event.loggers` to `JSON`.
-All operation lineage events will be written in the unified event json logger path, which be setting with
-`kyuubi.engine.event.json.log.path`. We can get the lineage logger from the `operation_lineage` dir in the
-`kyuubi.engine.event.json.log.path`.
+If enabled, lineage resolution will stop at permanent views and treats them as physical tables. We need
+to add one configurations.
+
+```properties
+spark.kyuubi.plugin.lineage.skip.parsing.permanent.view.enabled=true
+```
+
+### Get Lineage Events from SparkListener
+
+All lineage events will be sent to the `SparkListenerBus`. To handle lineage events, a new `SparkListener` needs to be added.
+Example for Adding `SparkListener`:
+
+```scala
+spark.sparkContext.addSparkListener(new SparkListener {
+      override def onOtherEvent(event: SparkListenerEvent): Unit = {
+        event match {
+          case lineageEvent: OperationLineageEvent =>
+            // Your processing logic
+          case _ =>
+        }
+      }
+    })
+```
 
diff --git a/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/kyuubi/plugin/lineage/SparkOperationLineageQueryExecutionListener.scala b/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/kyuubi/plugin/lineage/SparkOperationLineageQueryExecutionListener.scala
index c27d2eb8b..01deb0a44 100644
--- a/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/kyuubi/plugin/lineage/SparkOperationLineageQueryExecutionListener.scala
+++ b/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/kyuubi/plugin/lineage/SparkOperationLineageQueryExecutionListener.scala
@@ -28,7 +28,7 @@ class SparkOperationLineageQueryExecutionListener extends QueryExecutionListener
 
   override def onSuccess(funcName: String, qe: QueryExecution, durationNs: Long): Unit = {
     val lineage =
-      SparkSQLLineageParseHelper(qe.sparkSession).transformToLineage(qe.id, qe.optimizedPlan)
+      SparkSQLLineageParseHelper(qe.sparkSession).transformToLineage(qe.id, qe.analyzed)
     val event = OperationLineageEvent(qe.id, System.currentTimeMillis(), lineage, None)
     SparkContextHelper.postEventToSparkListenerBus(event)
   }
diff --git a/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/kyuubi/plugin/lineage/helper/SparkSQLLineageParseHelper.scala b/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/kyuubi/plugin/lineage/helper/SparkSQLLineageParseHelper.scala
index 1224da023..7106dfb8c 100644
--- a/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/kyuubi/plugin/lineage/helper/SparkSQLLineageParseHelper.scala
+++ b/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/kyuubi/plugin/lineage/helper/SparkSQLLineageParseHelper.scala
@@ -21,6 +21,7 @@ import scala.collection.immutable.ListMap
 import scala.util.{Failure, Success, Try}
 
 import org.apache.spark.internal.Logging
+import org.apache.spark.kyuubi.lineage.{LineageConf, SparkContextHelper}
 import org.apache.spark.sql.SparkSession
 import org.apache.spark.sql.catalyst.TableIdentifier
 import org.apache.spark.sql.catalyst.analysis.{NamedRelation, PersistedView, ViewType}
@@ -324,6 +325,10 @@ trait LineageParser {
         }
         ListMap(targetColumnsWithTargetTable.zip(sourceColumnsLineage.values).toSeq: _*)
 
+      case p if p.nodeName == "WithCTE" =>
+        val optimized = sparkSession.sessionState.optimizer.execute(p)
+        extractColumnsLineage(optimized, parentColumnsLineage)
+
       // For query
       case p: Project =>
         val nextColumnsLineage =
@@ -360,6 +365,7 @@ trait LineageParser {
           }
         }
         p.children.map(extractColumnsLineage(_, nextColumnsLineage)).reduce(mergeColumnsLineage)
+
       case p: Join =>
         p.joinType match {
           case LeftSemi | LeftAnti =>
@@ -415,9 +421,15 @@ trait LineageParser {
         }
 
       case p: View =>
-        val viewColumnsLineage =
-          extractColumnsLineage(p.child, ListMap[Attribute, AttributeSet]())
-        mergeRelationColumnLineage(parentColumnsLineage, p.output, viewColumnsLineage)
+        if (!p.isTempView && SparkContextHelper.getConf(
+            LineageConf.SKIP_PARSING_PERMANENT_VIEW_ENABLED)) {
+          val viewName = p.desc.qualifiedName
+          joinRelationColumnLineage(parentColumnsLineage, p.output, Seq(viewName))
+        } else {
+          val viewColumnsLineage =
+            extractColumnsLineage(p.child, ListMap[Attribute, AttributeSet]())
+          mergeRelationColumnLineage(parentColumnsLineage, p.output, viewColumnsLineage)
+        }
 
       case p: InMemoryRelation =>
         // get logical plan from cachedPlan
diff --git a/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/spark/kyuubi/lineage/SparkContextHelper.scala b/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/spark/kyuubi/lineage/LineageConf.scala
similarity index 68%
copy from extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/spark/kyuubi/lineage/SparkContextHelper.scala
copy to extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/spark/kyuubi/lineage/LineageConf.scala
index e6272364f..777e70121 100644
--- a/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/spark/kyuubi/lineage/SparkContextHelper.scala
+++ b/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/spark/kyuubi/lineage/LineageConf.scala
@@ -17,18 +17,15 @@
 
 package org.apache.spark.kyuubi.lineage
 
-import org.apache.spark.SparkContext
-import org.apache.spark.scheduler.SparkListenerEvent
-import org.apache.spark.sql.SparkSession
+import org.apache.spark.internal.config.ConfigBuilder
 
-object SparkContextHelper {
+object LineageConf {
 
-  def globalSparkContext: SparkContext = SparkSession.active.sparkContext
-
-  def postEventToSparkListenerBus(
-      event: SparkListenerEvent,
-      sc: SparkContext = globalSparkContext) {
-    sc.listenerBus.post(event)
-  }
+  val SKIP_PARSING_PERMANENT_VIEW_ENABLED =
+    ConfigBuilder("spark.kyuubi.plugin.lineage.skip.parsing.permanent.view.enabled")
+      .doc("Whether to skip the lineage parsing of permanent views")
+      .version("1.8.0")
+      .booleanConf
+      .createWithDefault(false)
 
 }
diff --git a/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/spark/kyuubi/lineage/SparkContextHelper.scala b/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/spark/kyuubi/lineage/SparkContextHelper.scala
index e6272364f..6e0f0e5c8 100644
--- a/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/spark/kyuubi/lineage/SparkContextHelper.scala
+++ b/extensions/spark/kyuubi-spark-lineage/src/main/scala/org/apache/spark/kyuubi/lineage/SparkContextHelper.scala
@@ -18,6 +18,7 @@
 package org.apache.spark.kyuubi.lineage
 
 import org.apache.spark.SparkContext
+import org.apache.spark.internal.config.ConfigEntry
 import org.apache.spark.scheduler.SparkListenerEvent
 import org.apache.spark.sql.SparkSession
 
@@ -31,4 +32,11 @@ object SparkContextHelper {
     sc.listenerBus.post(event)
   }
 
+  def getConf[T](entry: ConfigEntry[T]): T = {
+    globalSparkContext.getConf.get(entry)
+  }
+
+  def setConf[T](entry: ConfigEntry[T], value: T): Unit = {
+    globalSparkContext.conf.set(entry, value)
+  }
 }
diff --git a/extensions/spark/kyuubi-spark-lineage/src/test/scala/org/apache/kyuubi/plugin/lineage/events/OperationLineageEventSuite.scala b/extensions/spark/kyuubi-spark-lineage/src/test/scala/org/apache/kyuubi/plugin/lineage/events/OperationLineageEventSuite.scala
index 6eeebbd3c..1057bd74e 100644
--- a/extensions/spark/kyuubi-spark-lineage/src/test/scala/org/apache/kyuubi/plugin/lineage/events/OperationLineageEventSuite.scala
+++ b/extensions/spark/kyuubi-spark-lineage/src/test/scala/org/apache/kyuubi/plugin/lineage/events/OperationLineageEventSuite.scala
@@ -19,7 +19,10 @@ package org.apache.kyuubi.plugin.lineage.events
 
 import java.util.concurrent.{CountDownLatch, TimeUnit}
 
+import scala.collection.immutable.List
+
 import org.apache.spark.SparkConf
+import org.apache.spark.kyuubi.lineage.LineageConf.SKIP_PARSING_PERMANENT_VIEW_ENABLED
 import org.apache.spark.scheduler.{SparkListener, SparkListenerEvent}
 import org.apache.spark.sql.SparkListenerExtensionTest
 
@@ -40,6 +43,7 @@ class OperationLineageEventSuite extends KyuubiFunSuite with SparkListenerExtens
       .set(
         "spark.sql.queryExecutionListeners",
         "org.apache.kyuubi.plugin.lineage.SparkOperationLineageQueryExecutionListener")
+      .set(SKIP_PARSING_PERMANENT_VIEW_ENABLED.key, "true")
   }
 
   test("operation lineage event capture: for execute sql") {
@@ -116,4 +120,40 @@ class OperationLineageEventSuite extends KyuubiFunSuite with SparkListenerExtens
     }
   }
 
+  test("test for skip parsing permanent view") {
+    val countDownLatch = new CountDownLatch(1)
+    var actual: Lineage = null
+    spark.sparkContext.addSparkListener(new SparkListener {
+      override def onOtherEvent(event: SparkListenerEvent): Unit = {
+        event match {
+          case lineageEvent: OperationLineageEvent =>
+            lineageEvent.lineage.foreach {
+              case lineage if lineage.inputTables.nonEmpty && lineage.outputTables.isEmpty =>
+                actual = lineage
+                countDownLatch.countDown()
+            }
+          case _ =>
+        }
+      }
+    })
+
+    withTable("t1") { _ =>
+      spark.sql("CREATE TABLE t1 (a string, b string, c string) USING hive")
+      spark.sql("CREATE VIEW t2 as select * from t1")
+      spark.sql(
+        s"select a as k, b" +
+          s" from t2" +
+          s" where a in ('HELLO') and c = 'HELLO'").collect()
+
+      val expected = Lineage(
+        List("default.t2"),
+        List(),
+        List(
+          ("k", Set("default.t2.a")),
+          ("b", Set("default.t2.b"))))
+      countDownLatch.await(20, TimeUnit.SECONDS)
+      assert(actual == expected)
+    }
+  }
+
 }
diff --git a/extensions/spark/kyuubi-spark-lineage/src/test/scala/org/apache/kyuubi/plugin/lineage/helper/SparkSQLLineageParserHelperSuite.scala b/extensions/spark/kyuubi-spark-lineage/src/test/scala/org/apache/kyuubi/plugin/lineage/helper/SparkSQLLineageParserHelperSuite.scala
index 6180980c8..ed61a1b5f 100644
--- a/extensions/spark/kyuubi-spark-lineage/src/test/scala/org/apache/kyuubi/plugin/lineage/helper/SparkSQLLineageParserHelperSuite.scala
+++ b/extensions/spark/kyuubi-spark-lineage/src/test/scala/org/apache/kyuubi/plugin/lineage/helper/SparkSQLLineageParserHelperSuite.scala
@@ -21,6 +21,7 @@ import scala.collection.immutable.List
 import scala.reflect.io.File
 
 import org.apache.spark.SparkConf
+import org.apache.spark.kyuubi.lineage.{LineageConf, SparkContextHelper}
 import org.apache.spark.sql.{DataFrame, SparkListenerExtensionTest, SparkSession, SQLContext}
 import org.apache.spark.sql.catalyst.TableIdentifier
 import org.apache.spark.sql.catalyst.catalog.{CatalogStorageFormat, CatalogTable, CatalogTableType}
@@ -932,8 +933,8 @@ class SparkSQLLineageParserHelperSuite extends KyuubiFunSuite
       df0.cache()
       val df1 = spark.sql("select a, b from table1")
       val df = df0.join(df1).select(df0("a0").alias("aa"), df1("b").alias("bb"))
-      val optimized = df.queryExecution.optimizedPlan
-      val ret1 = SparkSQLLineageParseHelper(spark).transformToLineage(0, optimized).get
+      val analyzed = df.queryExecution.analyzed
+      val ret1 = SparkSQLLineageParseHelper(spark).transformToLineage(0, analyzed).get
       assert(ret1 == Lineage(
         List("default.table0", "default.table1"),
         List(),
@@ -1091,6 +1092,19 @@ class SparkSQLLineageParserHelperSuite extends KyuubiFunSuite
         List(
           ("aa", Set("default.table1.a", "default.table0.a")),
           ("bb", Set("default.table1.b")))))
+
+      val sql11 =
+        """
+          |select tmp.a, b from (select * from table1) tmp;
+          |""".stripMargin
+
+      val ret11 = exectractLineage(sql11)
+      assert(ret11 == Lineage(
+        List("default.table1"),
+        List(),
+        List(
+          ("a", Set("default.table1.a")),
+          ("b", Set("default.table1.b")))))
     }
   }
 
@@ -1162,7 +1176,7 @@ class SparkSQLLineageParserHelperSuite extends KyuubiFunSuite
     }
   }
 
-  test("test catch table with window function") {
+  test("test cache table with window function") {
     withTable("t1", "t2") { _ =>
       spark.sql("CREATE TABLE t1 (a string, b string) USING hive")
       spark.sql("CREATE TABLE t2 (a string, b string) USING hive")
@@ -1233,19 +1247,43 @@ class SparkSQLLineageParserHelperSuite extends KyuubiFunSuite
   test("test create view from view") {
     withTable("t1") { _ =>
       spark.sql("CREATE TABLE t1 (a string, b string, c string) USING hive")
-      spark.sql("CREATE VIEW t2 as select * from t1")
-      val ret0 =
-        exectractLineage(
-          s"create or replace view view_tst comment 'view'" +
-            s" as select a as k,b" +
-            s" from t2" +
-            s" where a in ('HELLO') and c = 'HELLO'")
-      assert(ret0 == Lineage(
-        List("default.t1"),
-        List("default.view_tst"),
-        List(
-          ("default.view_tst.k", Set("default.t1.a")),
-          ("default.view_tst.b", Set("default.t1.b")))))
+      withView("t2") { _ =>
+        spark.sql("CREATE VIEW t2 as select * from t1")
+        val ret0 =
+          exectractLineage(
+            s"create or replace view view_tst comment 'view'" +
+              s" as select a as k,b" +
+              s" from t2" +
+              s" where a in ('HELLO') and c = 'HELLO'")
+        assert(ret0 == Lineage(
+          List("default.t1"),
+          List("default.view_tst"),
+          List(
+            ("default.view_tst.k", Set("default.t1.a")),
+            ("default.view_tst.b", Set("default.t1.b")))))
+      }
+    }
+  }
+
+  test("test for skip parsing permanent view") {
+    withTable("t1") { _ =>
+      SparkContextHelper.setConf(LineageConf.SKIP_PARSING_PERMANENT_VIEW_ENABLED, true)
+      spark.sql("CREATE TABLE t1 (a string, b string, c string) USING hive")
+      withView("t2") { _ =>
+        spark.sql("CREATE VIEW t2 as select * from t1")
+        val ret0 =
+          exectractLineage(
+            s"select a as k, b" +
+              s" from t2" +
+              s" where a in ('HELLO') and c = 'HELLO'")
+
+        assert(ret0 == Lineage(
+          List("default.t2"),
+          List(),
+          List(
+            ("k", Set("default.t2.a")),
+            ("b", Set("default.t2.b")))))
+      }
     }
   }
 
@@ -1253,15 +1291,14 @@ class SparkSQLLineageParserHelperSuite extends KyuubiFunSuite
     val parsed = spark.sessionState.sqlParser.parsePlan(sql)
     val analyzed = spark.sessionState.analyzer.execute(parsed)
     spark.sessionState.analyzer.checkAnalysis(analyzed)
-    val optimized = spark.sessionState.optimizer.execute(analyzed)
-    SparkSQLLineageParseHelper(spark).transformToLineage(0, optimized).get
+    SparkSQLLineageParseHelper(spark).transformToLineage(0, analyzed).get
   }
 
   private def exectractLineage(sql: String): Lineage = {
     val parsed = spark.sessionState.sqlParser.parsePlan(sql)
     val qe = spark.sessionState.executePlan(parsed)
-    val optimized = qe.optimizedPlan
-    SparkSQLLineageParseHelper(spark).transformToLineage(0, optimized).get
+    val analyzed = qe.analyzed
+    SparkSQLLineageParseHelper(spark).transformToLineage(0, analyzed).get
   }
 
 }