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 d1becfc1b0 [spark] Expose micro-batch source offset ranges in
foreachBatch (#11021)
d1becfc1b0 is described below
commit d1becfc1b0813bfd8034b06862b300a4baaa7f34
Author: XiaoHongbo <[email protected]>
AuthorDate: Sun Nov 8 19:43:28 2026 +0800
[spark] Expose micro-batch source offset ranges in foreachBatch (#11021)
---
docs/docs/spark/structured-streaming.md | 15 +++
.../spark/PaimonSparkMicroBatchMetadata.scala | 124 ++++++++++++++++++---
.../org/apache/paimon/spark/PaimonSourceTest.scala | 97 +++++++++++++++-
3 files changed, 221 insertions(+), 15 deletions(-)
diff --git a/docs/docs/spark/structured-streaming.md
b/docs/docs/spark/structured-streaming.md
index cc28c1d652..47b4ffe108 100644
--- a/docs/docs/spark/structured-streaming.md
+++ b/docs/docs/spark/structured-streaming.md
@@ -188,6 +188,21 @@ A present `Optional` contains the complete, immutable list
of written field IDs
An empty `Optional` means that metadata is unavailable, for example because a
file or schema cannot be resolved, the micro-batch is empty, the `Dataset` is
not the raw batch from a query with exactly one distinct Paimon streaming
source, or its lineage is incomplete or ambiguous. An empty `Optional` does not
mean that no columns were written; callers must fall back to processing all
columns.
+## Micro-Batch Offset Range
+
+Use the raw `foreachBatch` dataset and its `batchId` to get Paimon source
offset JSON:
+
+```scala
+.foreachBatch { (batch: Dataset[Row], batchId: Long) =>
+ val range = PaimonSparkMicroBatchMetadata.offsetRange(batch, batchId)
+ require(range.isPresent, "Paimon source offsets unavailable")
+ val startOffset = range.get().startOffset
+ val endOffset = range.get().endOffset
+}
+```
+
+The result is empty if the range cannot be verified or the query has multiple
distinct sources. Empty full snapshots require `consumer-id` so the end offset
includes a completion marker. This read-only API does not advance the Consumer
or checkpoint.
+
## Read Changelogs
Expose a row-kind column to distinguish inserts, updates, and deletes. Use
either the system
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkMicroBatchMetadata.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkMicroBatchMetadata.scala
index cc5b94fe6b..0cdcd2850e 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkMicroBatchMetadata.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkMicroBatchMetadata.scala
@@ -19,12 +19,13 @@
package org.apache.paimon.spark
import org.apache.paimon.annotation.Experimental
-import org.apache.paimon.spark.sources.PaimonMicroBatchStream
+import org.apache.paimon.spark.sources.{PaimonMicroBatchStream,
PaimonSourceOffset}
import org.apache.spark.Partition
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.Dataset
import org.apache.spark.sql.connector.read.InputPartition
+import org.apache.spark.sql.connector.read.streaming.Offset
import org.apache.spark.sql.execution.datasources.v2.DataSourceRDD
import java.util.{IdentityHashMap, List => JList, Map => JMap, Optional, UUID}
@@ -35,6 +36,12 @@ import scala.util.control.NonFatal
@Experimental
final class PaimonSparkMicroBatchMetadata private ()
+/** The Paimon source offsets bounding one Spark streaming micro-batch. */
+@Experimental
+final class PaimonSparkMicroBatchOffsetRange private[spark] (
+ val startOffset: String,
+ val endOffset: String)
+
object PaimonSparkMicroBatchMetadata {
private val StreamingQueryIdKey = "sql.streaming.queryId"
@@ -47,18 +54,107 @@ object PaimonSparkMicroBatchMetadata {
*/
def writtenColumnIds(batch: Dataset[_]): Optional[JList[Integer]] = {
try {
- extractWrittenColumnIds(batch)
+ extractMetadata(batch).flatten
+ .map(_.writtenColumnIds)
+ .getOrElse(Optional.empty())
} catch {
case NonFatal(_) => Optional.empty()
case _: LinkageError => Optional.empty()
}
}
- private def extractWrittenColumnIds(batch: Dataset[_]):
Optional[JList[Integer]] = {
- if (!hasExactlyOnePaimonSource(batch)) {
+ /**
+ * Returns the exact source offset range of a raw foreachBatch Dataset. The
batchId must be the
+ * value passed to the same callback. Empty full snapshots are supported
when the source offset
+ * includes snapshot completion metadata (consumer-id is set). An empty
result means the source,
+ * batch, or its offsets cannot be identified unambiguously.
+ */
+ def offsetRange(batch: Dataset[_], batchId: Long):
Optional[PaimonSparkMicroBatchOffsetRange] = {
+ try {
+ extractOffsetRange(batch, batchId)
+ } catch {
+ case NonFatal(_) => Optional.empty()
+ case _: LinkageError => Optional.empty()
+ }
+ }
+
+ private def extractOffsetRange(
+ batch: Dataset[_],
+ batchId: Long): Optional[PaimonSparkMicroBatchOffsetRange] = {
+ val source = activePaimonSource(batch)
+ if (source.isEmpty || activeBatchId(source.get._1) != batchId) {
return Optional.empty()
}
+ extractMetadata(batch) match {
+ case Some(Some(metadata)) =>
+ Optional.of(new PaimonSparkMicroBatchOffsetRange(metadata.startOffset,
metadata.endOffset))
+ case Some(None) =>
+ val (execution, stream) = source.get
+ val end = executionOffset(execution, "availableOffsets", stream)
+ .map(offset => PaimonSourceOffset(offset.json()))
+ if (!end.exists(_.emptySnapshotCompleted)) {
+ return Optional.empty()
+ }
+ val start = executionOffset(execution, startOffsetsMethod(execution),
stream)
+ .map(offset => PaimonSourceOffset(offset.json()))
+ .orElse {
+ if (batchId == 0 && end.get.snapshotId > 0) {
+ Some(PaimonSourceOffset(end.get.snapshotId - 1, -1, scanSnapshot
= true))
+ } else {
+ None
+ }
+ }
+ start
+ .filter(offset => offset.compareTo(end.get) < 0)
+ .map(
+ offset =>
+ Optional.of(new PaimonSparkMicroBatchOffsetRange(offset.json(),
end.get.json())))
+ .getOrElse(Optional.empty())
+ case None => Optional.empty()
+ }
+ }
+
+ private def activeBatchId(execution: AnyRef): Long = {
+ val value =
+ try {
+ execution.getClass.getMethod("currentBatchId").invoke(execution)
+ } catch {
+ case _: NoSuchMethodException =>
+ // Spark 4 moved the batch ID into StreamExecutionContext.
+ val context =
execution.getClass.getMethod("getLatestExecutionContext").invoke(execution)
+ context.getClass.getMethod("batchId").invoke(context)
+ }
+ value.asInstanceOf[java.lang.Number].longValue()
+ }
+
+ private def startOffsetsMethod(execution: AnyRef): String = {
+ try {
+ // Spark 4 keeps each batch's start offsets in its execution context.
+ execution.getClass.getMethod("getStartOffsetsOfLatestBatch")
+ "getStartOffsetsOfLatestBatch"
+ } catch {
+ case _: NoSuchMethodException => "committedOffsets"
+ }
+ }
+
+ private def executionOffset(
+ execution: AnyRef,
+ method: String,
+ source: PaimonMicroBatchStream): Option[Offset] = {
+ execution.getClass
+ .getMethod(method)
+ .invoke(execution)
+ .asInstanceOf[scala.collection.Map[AnyRef, Offset]]
+ .get(source)
+ }
+
+ // Outer None means invalid or ambiguous lineage; Some(None) means no input
partitions.
+ private def extractMetadata(batch: Dataset[_]):
Option[Option[PaimonMicroBatchMetadata]] = {
+ if (!hasExactlyOnePaimonSource(batch)) {
+ return None
+ }
+
val visited = new IdentityHashMap[RDD[_], java.lang.Boolean]()
var only: PaimonMicroBatchMetadata = null
@@ -127,11 +223,7 @@ object PaimonSparkMicroBatchMetadata {
}
}
- if (!visit(batch.queryExecution.toRdd) || (only eq null)) {
- Optional.empty()
- } else {
- only.writtenColumnIds
- }
+ if (!visit(batch.queryExecution.toRdd)) None else Some(Option(only))
}
private def dataSourceInputPartitions(partition: Partition):
Seq[InputPartition] = {
@@ -172,10 +264,13 @@ object PaimonSparkMicroBatchMetadata {
s"Unexpected input partition type ${other.getClass.getName}.")
}
- private def hasExactlyOnePaimonSource(batch: Dataset[_]): Boolean = {
+ private def hasExactlyOnePaimonSource(batch: Dataset[_]): Boolean =
+ activePaimonSource(batch).isDefined
+
+ private def activePaimonSource(batch: Dataset[_]): Option[(AnyRef,
PaimonMicroBatchStream)] = {
val queryId =
batch.sparkSession.sparkContext.getLocalProperty(StreamingQueryIdKey)
if (queryId == null) {
- return false
+ return None
}
val sharedState =
@@ -187,7 +282,7 @@ object PaimonSparkMicroBatchMetadata {
.asInstanceOf[JMap[UUID, AnyRef]]
val execution = activeQueries.get(UUID.fromString(queryId))
if (execution == null) {
- return false
+ return None
}
// Spark replaces sources without new offsets with LocalRelation before
foreachBatch. Their
@@ -196,7 +291,8 @@ object PaimonSparkMicroBatchMetadata {
// access isolated here and fail closed if a Spark version changes it.
val sources =
execution.getClass.getMethod("sources").invoke(execution).asInstanceOf[Seq[AnyRef]]
- sources.headOption.exists(
- first => first.isInstanceOf[PaimonMicroBatchStream] && sources.forall(_
eq first))
+ sources.headOption.collect {
+ case first: PaimonMicroBatchStream if sources.forall(_ eq first) =>
(execution, first)
+ }
}
}
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/PaimonSourceTest.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/PaimonSourceTest.scala
index 2a5b84dc69..98b4d7b629 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/PaimonSourceTest.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/PaimonSourceTest.scala
@@ -18,6 +18,7 @@
package org.apache.paimon.spark
+import org.apache.paimon.CoreOptions
import org.apache.paimon.schema.{SchemaManager, TableSchema}
import org.apache.paimon.spark.sources.{PaimonMicroBatchStream,
PaimonSourceOffset}
import org.apache.paimon.table.DataTable
@@ -163,6 +164,99 @@ class PaimonSourceTest extends PaimonSparkTestBase with
StreamTest {
}
}
+ test("Paimon Source: expose exact offset ranges for split full snapshots") {
+ withTempDir {
+ checkpointDir =>
+ val TableSnapshotState(_, location, snapshotData, _, _) =
+ prepareTableAndGetLocation(3, hasPk = true)
+ @volatile var ranges = Vector.empty[(Long, String, String)]
+ @volatile var rowCount = 0L
+
+ withStartedQuery(
+ spark.readStream
+ .format("paimon")
+ .option(CoreOptions.CONSUMER_ID.key(), "offset-range-test")
+ .option("scan.mode", "latest-full")
+ .option("read.stream.maxFilesPerTrigger", "1")
+ .load(location)
+ .writeStream
+ .option("checkpointLocation", checkpointDir.getCanonicalPath)
+ .foreachBatch {
+ (batch: Dataset[Row], batchId: Long) =>
+ val range = PaimonSparkMicroBatchMetadata.offsetRange(batch,
batchId)
+ assert(range.isPresent)
+ assert(!PaimonSparkMicroBatchMetadata.offsetRange(batch,
batchId + 1).isPresent)
+ ranges :+= ((batchId, range.get().startOffset,
range.get().endOffset))
+ rowCount += batch.count()
+ ()
+ }
+ .start()) {
+ query =>
+ query.processAllAvailable()
+ assert(ranges.size >= 2)
+ assert(rowCount == snapshotData.size)
+ assert(ranges.map(_._1) == ranges.indices.map(_.toLong))
+ assert(ranges.sliding(2).forall(pair => pair.size < 2 ||
pair.head._3 == pair(1)._2))
+ val firstEnd = PaimonSourceOffset(ranges.head._3)
+ val lastEnd = PaimonSourceOffset(ranges.last._3)
+ assert(firstEnd.scanSnapshot)
+ assert(firstEnd.totalSplits.exists(_ > 1L))
+ assert(firstEnd.index < firstEnd.totalSplits.get - 1L)
+ assert(lastEnd.snapshotCompleted)
+ }
+ }
+ }
+
+ test("Paimon Source: expose the offset range of an empty full snapshot") {
+ withTempDir {
+ checkpointDir =>
+ spark.sql(
+ "CREATE TABLE T (a INT, b STRING) TBLPROPERTIES ('primary-key'='a',
'bucket'='2')")
+ val location = loadTable("T").location().toString
+ spark.sql("INSERT INTO T VALUES (1, 'before')")
+ spark.sql("INSERT OVERWRITE T SELECT * FROM T WHERE false")
+ val emptySnapshotId =
loadTable("T").snapshotManager().latestSnapshotId()
+ @volatile var ranges = Vector.empty[(String, String)]
+
+ withStartedQuery(
+ spark.readStream
+ .format("paimon")
+ .option(CoreOptions.CONSUMER_ID.key(), "empty-offset-range-test")
+ .load(location)
+ .writeStream
+ .option("checkpointLocation", checkpointDir.getCanonicalPath)
+ .foreachBatch {
+ (batch: Dataset[Row], batchId: Long) =>
+ val range = PaimonSparkMicroBatchMetadata.offsetRange(batch,
batchId)
+ assert(range.isPresent)
+ if (batchId == 0) {
+
assert(!PaimonSparkMicroBatchMetadata.writtenColumnIds(batch).isPresent)
+ assert(batch.count() == 0L)
+ }
+ assert(!PaimonSparkMicroBatchMetadata.offsetRange(batch,
batchId + 1).isPresent)
+ ranges :+= ((range.get().startOffset, range.get().endOffset))
+ ()
+ }
+ .start()) {
+ query =>
+ query.processAllAvailable()
+ assert(ranges.size == 1)
+ val start = PaimonSourceOffset(ranges.head._1)
+ val end = PaimonSourceOffset(ranges.head._2)
+ assert(start.snapshotId == emptySnapshotId)
+ assert(start.scanSnapshot)
+ assert(end.snapshotId == emptySnapshotId + 1L)
+ assert(end.emptySnapshotCompleted)
+
+ spark.sql("INSERT INTO T VALUES (2, 'after')")
+ query.processAllAvailable()
+ assert(ranges.size == 2)
+ assert(ranges(1)._1 == ranges.head._2)
+ assert(PaimonSourceOffset(ranges(1)._2).snapshotId ==
emptySnapshotId + 1L)
+ }
+ }
+ }
+
test("Paimon Source: expose written columns for a self-union") {
withTempDir {
checkpointDir =>
@@ -218,9 +312,10 @@ class PaimonSourceTest extends PaimonSparkTestBase with
StreamTest {
.writeStream
.option("checkpointLocation", checkpointDir.getCanonicalPath)
.foreachBatch {
- (batch: Dataset[Row], _: Long) =>
+ (batch: Dataset[Row], batchId: Long) =>
val metadataPresent =
PaimonSparkMicroBatchMetadata.writtenColumnIds(batch).isPresent
+ assert(!PaimonSparkMicroBatchMetadata.offsetRange(batch,
batchId).isPresent)
if (batch.count() > 0) {
nonEmptyBatchMetadataPresent =
nonEmptyBatchMetadataPresent :+ metadataPresent
}