This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new c6fad05a0a [spark] Clean batch read protection tags per SQL execution
(#10943)
c6fad05a0a is described below
commit c6fad05a0a98eabb4f7a1bceac2f2c7baceff13c
Author: YangJie <[email protected]>
AuthorDate: Mon Nov 2 09:40:56 2026 -0500
[spark] Clean batch read protection tags per SQL execution (#10943)
---
.../org/apache/paimon/spark/PaimonBaseScan.scala | 8 +-
.../spark/read/BatchReadTagCleanupListener.scala | 114 ++++++++++++-----
.../spark/read/BatchReadTagProtectionTest.scala | 140 +++++++++++++++++++++
3 files changed, 226 insertions(+), 36 deletions(-)
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala
index ed3452d2c3..ad277d5b09 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala
@@ -36,6 +36,7 @@ import
org.apache.spark.sql.connector.expressions.NamedReference
import org.apache.spark.sql.connector.metric.{CustomMetric, CustomTaskMetric}
import org.apache.spark.sql.connector.read.{Batch, Statistics}
import org.apache.spark.sql.connector.read.streaming.MicroBatchStream
+import org.apache.spark.sql.execution.SQLExecution
import scala.collection.JavaConverters._
@@ -63,9 +64,10 @@ abstract class PaimonBaseScan(table: InnerTable)
final private[spark] def registerReadProtectionTagCleanup(tagName: String):
Unit = {
Option(tagName).foreach {
name =>
- BatchReadTagCleanupListener
- .getOrCreate(SparkSession.active)
- .registerCleanup(name, table)
+ val spark = SparkSession.active
+ val executionId =
+
Option(spark.sparkContext.getLocalProperty(SQLExecution.EXECUTION_ID_KEY)).map(_.toLong)
+
BatchReadTagCleanupListener.getOrCreate(spark).registerCleanup(executionId,
name, table)
}
}
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/read/BatchReadTagCleanupListener.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/read/BatchReadTagCleanupListener.scala
index 988748c109..31cf60b055 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/read/BatchReadTagCleanupListener.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/read/BatchReadTagCleanupListener.scala
@@ -21,56 +21,99 @@ package org.apache.paimon.spark.read
import org.apache.paimon.table.{DataTable, Table}
import org.apache.paimon.tag.BatchReadTagCreator
+import org.apache.spark.SparkContext
import org.apache.spark.internal.Logging
+import org.apache.spark.scheduler.{SparkListener, SparkListenerEvent}
import org.apache.spark.sql.SparkSession
-import org.apache.spark.sql.execution.QueryExecution
-import org.apache.spark.sql.util.QueryExecutionListener
+import org.apache.spark.sql.execution.SQLExecution
+import org.apache.spark.sql.execution.ui.SparkListenerSQLExecutionEnd
import java.util.concurrent.ConcurrentHashMap
+import scala.collection.JavaConverters._
+
/**
- * A Spark [[QueryExecutionListener]] that cleans up batch-read protection
tags when a query
- * completes (success or failure). TTL expiration serves as a safety net if
this cleanup fails.
+ * Cleans up batch-read protection tags when the SQL execution that planned
the scan ends (success
+ * or failure), or, for scans planned outside a running execution, when the
next execution ends. TTL
+ * expiration serves as a safety net if this cleanup fails.
*/
-class BatchReadTagCleanupListener extends QueryExecutionListener with Logging {
+class BatchReadTagCleanupListener extends SparkListener with Logging {
+
+ private val pendingCleanups =
+ new ConcurrentHashMap[java.lang.Long, ConcurrentHashMap[String,
DataTable]]()
- private val pendingCleanups = new ConcurrentHashMap[String, DataTable]()
+ // scans planned outside a running SQL execution, e.g. through Dataset.rdd
on Spark 3 or
+ // Dataset.cache, with the time they were planned
+ private val unownedCleanups = new ConcurrentHashMap[String, (DataTable,
Long)]()
- def registerCleanup(tagName: String, table: Table): Unit = {
+ def registerCleanup(executionId: Option[Long], tagName: String, table:
Table): Unit = {
table match {
- case dt: DataTable => pendingCleanups.put(tagName, dt)
+ case dt: DataTable =>
+ executionId.filter(SQLExecution.getQueryExecution(_) != null) match {
+ case Some(id) =>
+ // adds the tag inside compute, so it never lands in a map that
onOtherEvent removed
+ pendingCleanups.compute(
+ Long.box(id),
+ (_: java.lang.Long, tags: ConcurrentHashMap[String, DataTable])
=> {
+ val result = if (tags == null) new ConcurrentHashMap[String,
DataTable]() else tags
+ result.put(tagName, dt)
+ result
+ }
+ )
+ case None => unownedCleanups.put(tagName, (dt,
System.currentTimeMillis()))
+ }
case _ =>
}
}
- override def onSuccess(funcName: String, qe: QueryExecution, durationNs:
Long): Unit = {
- cleanupAll()
- }
-
- override def onFailure(funcName: String, qe: QueryExecution, exception:
Exception): Unit = {
- cleanupAll()
+ override def onOtherEvent(event: SparkListenerEvent): Unit = {
+ event match {
+ case end: SparkListenerSQLExecutionEnd =>
+ Option(pendingCleanups.remove(end.executionId)).foreach(cleanup)
+ // executions that have ended without their end event reaching this
listener
+ pendingCleanups.keySet().asScala.foreach {
+ id =>
+ if (SQLExecution.getQueryExecution(id) == null) {
+ Option(pendingCleanups.remove(id)).foreach(cleanup)
+ }
+ }
+ // the end event of an execution that ended before a scan was planned
can still arrive
+ // after it, and must not clean that scan's tag
+ val iter = unownedCleanups.entrySet().iterator()
+ while (iter.hasNext) {
+ val entry = iter.next()
+ val (dataTable, plannedAt) = entry.getValue
+ if (plannedAt < end.time) {
+ iter.remove()
+ deleteTag(entry.getKey, dataTable)
+ }
+ }
+ case _ =>
+ }
}
- private def cleanupAll(): Unit = {
- val iter = pendingCleanups.entrySet().iterator()
+ private def cleanup(tags: ConcurrentHashMap[String, DataTable]): Unit = {
+ val iter = tags.entrySet().iterator()
while (iter.hasNext) {
val entry = iter.next()
- val tagName = entry.getKey
- val dataTable = entry.getValue
iter.remove()
- try {
- val creator = new BatchReadTagCreator(
- dataTable.tagManager(),
- dataTable.snapshotManager(),
- dataTable.coreOptions().scanPlanAutoTagTimeRetained())
- creator.deleteReadTag(tagName)
- } catch {
- case e: Exception =>
- logWarning(
- s"Failed to delete batch read protection tag '$tagName'. " +
- "It will be cleaned up by TTL expiration.",
- e)
- }
+ deleteTag(entry.getKey, entry.getValue)
+ }
+ }
+
+ private def deleteTag(tagName: String, dataTable: DataTable): Unit = {
+ try {
+ val creator = new BatchReadTagCreator(
+ dataTable.tagManager(),
+ dataTable.snapshotManager(),
+ dataTable.coreOptions().scanPlanAutoTagTimeRetained())
+ creator.deleteReadTag(tagName)
+ } catch {
+ case e: Exception =>
+ logWarning(
+ s"Failed to delete batch read protection tag '$tagName'. " +
+ "It will be cleaned up by TTL expiration.",
+ e)
}
}
}
@@ -78,13 +121,18 @@ class BatchReadTagCleanupListener extends
QueryExecutionListener with Logging {
object BatchReadTagCleanupListener {
@volatile private var instance: BatchReadTagCleanupListener = _
+ @volatile private var registeredContext: SparkContext = _
def getOrCreate(spark: SparkSession): BatchReadTagCleanupListener = {
- if (instance == null) {
+ val sc = spark.sparkContext
+ if (instance == null || (registeredContext ne sc)) {
synchronized {
if (instance == null) {
instance = new BatchReadTagCleanupListener()
- spark.listenerManager.register(instance)
+ }
+ if (registeredContext ne sc) {
+ sc.addSparkListener(instance)
+ registeredContext = sc
}
}
}
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/read/BatchReadTagProtectionTest.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/read/BatchReadTagProtectionTest.scala
index afced7afed..8f9903e5f7 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/read/BatchReadTagProtectionTest.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/read/BatchReadTagProtectionTest.scala
@@ -21,7 +21,13 @@ package org.apache.paimon.spark.read
import org.apache.paimon.spark.PaimonSparkTestBase
import org.apache.paimon.tag.BatchReadTagCreator
+import org.apache.spark.scheduler.{SparkListener, SparkListenerEvent}
import org.apache.spark.sql.Row
+import org.apache.spark.sql.execution.SQLExecution
+import org.apache.spark.sql.execution.ui.SparkListenerSQLExecutionStart
+import org.apache.spark.sql.paimon.Utils
+
+import java.util.concurrent.{CountDownLatch, TimeUnit}
class BatchReadTagProtectionTest extends PaimonSparkTestBase {
@@ -56,6 +62,140 @@ class BatchReadTagProtectionTest extends
PaimonSparkTestBase {
s"Protection tags should be cleaned up, but found:
${batchReadTags.mkString(", ")}")
}
+ test("Paimon: a query ending does not clean the protection tag of a running
query") {
+ spark.sql(s"""
+ |CREATE TABLE T (a INT, b STRING)
+ |TBLPROPERTIES (
+ | 'primary-key' = 'a',
+ | 'bucket' = '1',
+ | 'scan.plan-auto-tag-for-read.time-retained' = '1 h'
+ |)
+ |""".stripMargin)
+ spark.sql("INSERT INTO T VALUES (1, 'v1'), (2, 'v2')")
+ val tagManager = loadTable("T").tagManager()
+ def batchReadTags(): Seq[String] =
+
tagManager.allTagNames().toArray.map(_.toString).filter(BatchReadTagCreator.isBatchReadTag)
+
+ val running = spark.sql("SELECT * FROM T")
+ SQLExecution.withNewExecutionId(running.queryExecution, Some("running
query")) {
+ // plans the scan of the running query, which creates its protection tag
+ running.queryExecution.executedPlan.executeCollect()
+ assert(batchReadTags().size == 1)
+
+ // another query ends while the first one is still running
+ spark.sql("SELECT 1").collect()
+ Utils.waitUntilEventEmpty(spark)
+ assert(batchReadTags().size == 1, "the protection tag of the running
query was deleted")
+ }
+ Utils.waitUntilEventEmpty(spark)
+ assert(batchReadTags().isEmpty)
+ }
+
+ test("Paimon: a scan planned with the id of an ended execution is cleaned by
the next query") {
+ spark.sql(s"""
+ |CREATE TABLE T (a INT, b STRING)
+ |TBLPROPERTIES (
+ | 'primary-key' = 'a',
+ | 'bucket' = '1',
+ | 'scan.plan-auto-tag-for-read.time-retained' = '1 h'
+ |)
+ |""".stripMargin)
+ spark.sql("INSERT INTO T VALUES (1, 'v1'), (2, 'v2')")
+ val tagManager = loadTable("T").tagManager()
+ def batchReadTags(): Seq[String] =
+
tagManager.allTagNames().toArray.map(_.toString).filter(BatchReadTagCreator.isBatchReadTag)
+
+ Utils.waitUntilEventEmpty(spark)
+ // like a thread that inherited the execution id of a query that has
already ended
+ val sc = spark.sparkContext
+ sc.setLocalProperty(SQLExecution.EXECUTION_ID_KEY, Long.MaxValue.toString)
+ try {
+ assert(spark.sql("SELECT * FROM
T").queryExecution.executedPlan.executeCollect().length == 2)
+ } finally {
+ sc.setLocalProperty(SQLExecution.EXECUTION_ID_KEY, null)
+ }
+ assert(batchReadTags().size == 1)
+
+ spark.sql("SELECT 1").collect()
+ Utils.waitUntilEventEmpty(spark)
+ assert(batchReadTags().isEmpty)
+ }
+
+ test("Paimon: a late end event of an earlier execution does not clean the
tag of a later scan") {
+ spark.sql(s"""
+ |CREATE TABLE T (a INT, b STRING)
+ |TBLPROPERTIES (
+ | 'primary-key' = 'a',
+ | 'bucket' = '1',
+ | 'scan.plan-auto-tag-for-read.time-retained' = '1 h'
+ |)
+ |""".stripMargin)
+ spark.sql("INSERT INTO T VALUES (1, 'v1'), (2, 'v2')")
+ val tagManager = loadTable("T").tagManager()
+ def batchReadTags(): Seq[String] =
+
tagManager.allTagNames().toArray.map(_.toString).filter(BatchReadTagCreator.isBatchReadTag)
+ Utils.waitUntilEventEmpty(spark)
+
+ // holds the listener bus at the start of an execution, so its end event
reaches the cleanup
+ // listener only after the next scan is planned outside an execution
+ BatchReadTagCleanupListener.getOrCreate(spark)
+ val blocked = new CountDownLatch(1)
+ val release = new CountDownLatch(1)
+ @volatile var released = false
+ val holder = new SparkListener {
+ override def onOtherEvent(event: SparkListenerEvent): Unit = event match
{
+ case _: SparkListenerSQLExecutionStart if blocked.getCount > 0 =>
+ blocked.countDown()
+ released = release.await(1, TimeUnit.MINUTES)
+ case _ =>
+ }
+ }
+ spark.sparkContext.addSparkListener(holder)
+ try {
+ spark.sql("SELECT 1").collect()
+ assert(blocked.await(10, TimeUnit.SECONDS), "the listener bus was not
held")
+ assert(spark.sql("SELECT * FROM
T").queryExecution.executedPlan.executeCollect().length == 2)
+ } finally {
+ release.countDown()
+ spark.sparkContext.removeSparkListener(holder)
+ }
+ Utils.waitUntilEventEmpty(spark)
+ assert(released, "the listener bus was released by the timeout")
+ assert(batchReadTags().size == 1, "an earlier execution deleted the
protection tag")
+
+ spark.sql("SELECT 1").collect()
+ Utils.waitUntilEventEmpty(spark)
+ assert(batchReadTags().isEmpty)
+ }
+
+ test("Paimon: the protection tag of a cached scan is cleaned after the cache
is built") {
+ spark.sql(s"""
+ |CREATE TABLE T (a INT, b STRING)
+ |TBLPROPERTIES (
+ | 'primary-key' = 'a',
+ | 'bucket' = '1',
+ | 'scan.plan-auto-tag-for-read.time-retained' = '1 h'
+ |)
+ |""".stripMargin)
+ spark.sql("INSERT INTO T VALUES (1, 'v1'), (2, 'v2')")
+ val tagManager = loadTable("T").tagManager()
+ def batchReadTags(): Seq[String] =
+
tagManager.allTagNames().toArray.map(_.toString).filter(BatchReadTagCreator.isBatchReadTag)
+
+ Utils.waitUntilEventEmpty(spark)
+ // Dataset.cache plans the scan in a session cloned by the cache manager,
outside an execution
+ val df = spark.table("T")
+ df.cache()
+ try {
+ assert(batchReadTags().size == 1)
+ assert(df.count() == 2)
+ Utils.waitUntilEventEmpty(spark)
+ assert(batchReadTags().isEmpty, "the protection tag of the cached scan
was not cleaned")
+ } finally {
+ df.unpersist()
+ }
+ }
+
test("Paimon: batch read does NOT create tag when disabled") {
spark.sql(s"""
|CREATE TABLE T (a INT, b STRING)