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

gengliangwang 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 f093bdfa9ad4 [SPARK-61284][SQL] Close the stream writer of a native 
data source after it commits or aborts its micro-batch
f093bdfa9ad4 is described below

commit f093bdfa9ad47ad10d77d90e6515a480dff16446
Author: Gengliang Wang <[email protected]>
AuthorDate: Tue Nov 10 09:28:07 2026 -0800

    [SPARK-61284][SQL] Close the stream writer of a native data source after it 
commits or aborts its micro-batch
    
    ### What changes were proposed in this pull request?
    
    A native data source closes the writer of a batch write right after Spark 
commits it, and after Spark aborts it (`NativeDataSourceWriter`). It did not 
close the writer of a micro-batch of a streaming write: 
`NativeDataSourceStreamWriter.commit` and `abort` left its handle open, and 
`NativeStreamWriters.register` closed it only when the query created the stream 
writer of its next micro-batch, after `create_writer` of that micro-batch, or, 
for the last micro-batch of a query, once the h [...]
    
    This PR closes the handle of a stream writer after a successful commit and 
after an abort, as for a batch write:
    
    - `NativeDataSourceStreamWriter.commit` closes its handle once the commit 
succeeded. When the commit fails, the handle stays open, since Spark then 
aborts the micro-batch; `ColumnarStreamingWrite` does not abort a committed 
micro-batch.
    - `NativeDataSourceStreamWriter.abort` closes its handle in a `finally`.
    - `NativeStreamWriters` still closes the previous stream writer of a query 
when the query creates a new one, and the last one once it becomes unreachable, 
but that now only matters for a stream writer that is neither committed nor 
aborted. `NativeHandle.close` releases a handle at most once 
(`Cleaner.Cleanable.clean`), so closing a handle that a commit or an abort 
already closed has no effect.
    - `spark_datasource.h` and `docs/sql-native-data-sources.md` describe the 
new lifecycle: Spark closes a stream writer once it committed or aborted its 
micro-batch, and a stream writer that Spark neither commits nor aborts is 
closed when the query creates its next one, or once it is no longer referenced. 
The header's example of a handle that is released once it is no longer 
referenced, possibly on a JVM Cleaner thread, is now a batch reader whose 
partitions are never planned, instead o [...]
    
    ### Why are the changes needed?
    
    A library that releases an exclusive resource in `close_writer`, such as a 
lock on its destination, fails or blocks at the second micro-batch of a 
streaming query: the writer of the first micro-batch still holds the resource 
when Spark calls `create_writer` for the second one. The writer of the last 
micro-batch of a query is even closed only once the JVM collects it. The batch 
writer avoids both by closing its handle right after its commit or its abort, 
and the stream writer now does  [...]
    
    This was found in the review of the Rust SDK for native data sources: 
https://github.com/apache/spark/pull/59520#discussion_r4515939460
    
    ### Does this PR introduce _any_ user-facing change?
    
    No, compared to the released versions: native data sources ship first in 
Spark 4.4.0. Within the unreleased branches, a native data source library now 
gets `close_writer` for the writer of a micro-batch right after Spark commits 
or aborts the micro-batch, instead of when the next micro-batch creates its 
writer, or, for the last micro-batch of a query, once the JVM collects the 
writer.
    
    ### How was this patch tested?
    
    Three tests of `NativeDataSourceSuite` now also check when Spark closes the 
writer of a micro-batch, and fail without this change:
    
    - "keep the order of the calls whatever the callers of the adapter do": a 
committed micro-batch closes its writer right away, as a committed batch write 
does.
    - "abort a micro-batch whose write failed": the aborted micro-batch closes 
its writer.
    - "streaming read and write": the writer of every micro-batch, the last one 
included, is closed while the query still runs.
    
    `build/sbt 'sql/testOnly *NativeDataSourceSuite'` passes on Java 25: 83 
tests succeed, and 2 are canceled because they need a Java version before 22, 
or pandas and PyArrow. `sql/scalastyle` and `sql/Test/scalastyle` pass too.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Opus 5.5)
    
    This pull request and its description were written by Isaac.
    
    Closes #60262 from gengliangwang/SPARK-61284-close-stream-writer.
    
    Authored-by: Gengliang Wang <[email protected]>
    Signed-off-by: Gengliang Wang <[email protected]>
    
    
    skip-checks: true
---
 docs/sql-native-data-sources.md                    |   7 +-
 .../apache/spark/sql/datasource/spark_datasource.h |  22 +++--
 .../v2/columnar/ColumnarDataSource.scala           |   7 +-
 .../datasources/v2/ffi/NativeDataSource.scala      | 100 ++++++++++++-------
 .../native-datasource/test_native_datasource.cc    |   4 +-
 .../datasources/v2/ffi/NativeDataSourceSuite.scala | 110 ++++++++++++++-------
 6 files changed, 164 insertions(+), 86 deletions(-)

diff --git a/docs/sql-native-data-sources.md b/docs/sql-native-data-sources.md
index 3f8074c13930..da18eb61821a 100644
--- a/docs/sql-native-data-sources.md
+++ b/docs/sql-native-data-sources.md
@@ -181,9 +181,10 @@ Spark calls the functions of the table as follows:
   together, they identify the output of a micro-batch, so that a library can 
skip an epoch that it
   already committed. A restarted query may also abort such an epoch, so an 
abort only removes what
   the data writers of its own writer wrote. A micro-batch streaming query 
creates a new stream
-  writer for each micro-batch, and Spark closes the previous one when it 
creates the next one.
-  Because Spark is not told when a streaming query stops, the last stream 
writer of a query is
-  closed once it is no longer referenced, or when the query is restarted.
+  writer for each micro-batch, and Spark closes it with `close_writer` once it 
committed or aborted
+  the micro-batch. A stream writer that Spark neither commits nor aborts is 
closed before the
+  query creates its next one, or, because Spark is not told when a streaming 
query stops, once it
+  is no longer referenced.
 
 The library defines the format of the partitions, of the state of its readers 
and writers, and of
 the commit messages, which Spark sends to the executors and back as byte 
arrays. The library
diff --git 
a/sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h
 
b/sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h
index 9c5b7330853d..5cfe42b73e84 100644
--- 
a/sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h
+++ 
b/sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h
@@ -119,10 +119,11 @@
  *   the same when the query restarts from its checkpoint, so the ID of the 
query and the epoch ID
  *   identify the output of a micro-batch, also when other queries write to 
the same destination. A
  *   micro-batch streaming query creates a new stream writer for each 
micro-batch, and Spark closes
- *   the previous stream writer of the query when the query creates a new one. 
Spark is not told
- *   when a streaming query stops, so it closes the last stream writer of the 
query once the writer
- *   is no longer referenced, or when the query is restarted. Streaming writes 
are micro-batch only:
- *   a query with continuous processing fails before create_writer.
+ *   it once it committed or aborted the micro-batch, as for a batch write. A 
stream writer that
+ *   Spark neither commits nor aborts is closed before the query calls 
create_writer for its next
+ *   one, or, since Spark is not told when a streaming query stops, once the 
writer is no longer
+ *   referenced. Streaming writes are micro-batch only: a query with 
continuous processing fails
+ *   before create_writer.
  *
  * Conventions
  * -----------
@@ -137,10 +138,11 @@
  *   NULL handle as an error. Spark releases each handle exactly once, with 
the close function of
  *   its kind: close, close_reader, close_stream_reader, close_writer or 
close_data_writer, and no
  *   other function releases a handle. A handle is not always released right 
after its last use: a
- *   batch reader whose partitions are never planned and the last stream 
writer of a query are
- *   released once they are no longer referenced (see Lifecycle above). A 
reader or writer handle
- *   must not depend on the data source handle it was created from, because 
Spark closes the data
- *   source handle right after creating it.
+ *   batch reader whose partitions are never planned may only be released once 
it is no longer
+ *   referenced, and a stream writer that is neither committed nor aborted 
before the query
+ *   creates its next one or once it is no longer referenced (see Lifecycle 
above). A reader or
+ *   writer handle must not depend on the data source handle it was created 
from, because Spark
+ *   closes the data source handle right after creating it.
  * - Order of the calls. After a function on a handle fails, Spark calls no 
other function on the
  *   handle than its close function, except that it aborts a writer whose 
commit failed and a data
  *   writer whose write or commit failed. It does not abort a writer or a data 
writer whose commit
@@ -201,8 +203,8 @@
  * - Threads. Spark calls the library from multiple threads, and calls on 
different handles may
  *   run concurrently. Calls on the same handle never run concurrently. A 
handle may be released
  *   from a thread other than the threads that used it, such as a JVM Cleaner 
thread when Spark
- *   releases a handle once it is no longer referenced, for example the last 
stream writer of a
- *   streaming query. A SparkDsSink must be called on the thread of the call 
that it was passed
+ *   releases a handle once it is no longer referenced, for example a batch 
reader whose partitions
+ *   are never planned. A SparkDsSink must be called on the thread of the call 
that it was passed
  *   to, during that call. The functions of SparkDsHost and 
SparkDsTaskContext, and the callbacks
  *   of the stream that read initializes, can be called from any thread. The 
callbacks of the
  *   stream never run concurrently.
diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarDataSource.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarDataSource.scala
index 9991f37d7db8..4e1ed1e7ebee 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarDataSource.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarDataSource.scala
@@ -201,9 +201,10 @@ trait ColumnarWriter extends Serializable {
 }
 
 /**
- * Writes data to a [[ColumnarDataSource]] for a streaming write, one 
micro-batch at a time. Spark
- * does not abort a micro-batch once the writer committed it, but a restarted 
query may abort a
- * micro-batch that a writer of an earlier run of the query committed.
+ * Writes data to a [[ColumnarDataSource]] for a streaming write, for a single 
micro-batch: Spark
+ * creates a new writer for each micro-batch, and does not call a writer after 
it committed or
+ * aborted its micro-batch. Spark does not abort a micro-batch once the writer 
committed it, but a
+ * restarted query may abort a micro-batch that a writer of an earlier run of 
the query committed.
  */
 trait ColumnarStreamWriter extends Serializable {
   def createWriter(partitionId: Int, taskId: Long, epochId: Long): 
DataWriter[ColumnarBatch]
diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSource.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSource.scala
index 5ced8e65a6e2..79850003f143 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSource.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSource.scala
@@ -167,12 +167,14 @@ class NativeDataSource(
       queryId: String): ColumnarStreamWriter = {
     val executorLocation = NativeDataSourceRegistry.distribute(location)
     val library = NativeLibraries.get(location)
+    // The previous stream writer of the query is closed before create_writer, 
which may wait for
+    // it to release its destination.
+    NativeStreamWriters.closePrevious(queryId)
     val created = createWriter(library, schema, overwrite, queryId)
     val handle = new NativeHandle(created.handle, library.closeWriter)
-    val writer = new NativeDataSourceStreamWriter(
-      executorLocation, name, schema, timeZoneId, handle, 
bytesOrEmpty(Option(created.state)))
     NativeStreamWriters.register(queryId, handle)
-    writer
+    new NativeDataSourceStreamWriter(
+      executorLocation, name, schema, timeZoneId, handle, 
bytesOrEmpty(Option(created.state)))
   }
 
   /** Runs `f` with a new native data source, which is closed afterwards. */
@@ -551,27 +553,19 @@ class NativeDataSourceWriter(
   }
 
   override def commit(messages: Array[WriterCommitMessage]): Unit = {
-    call(name, "commit a write to") {
-      library.commit(handle.get, -1L, 
NativeWriterCommitMessage.toBytes(messages))
-    }
-    // Not closed if the commit fails: Spark then aborts the write, which 
closes it. Spark does
-    // not abort a committed write, see ColumnarBatchWrite.
-    handle.close()
+    commitWrite(library, name, handle, -1L, messages)
   }
 
   override def abort(messages: Array[WriterCommitMessage]): Unit = {
-    Utils.tryWithSafeFinally {
-      call(name, "abort a write to") {
-        library.abort(handle.get, -1L, 
NativeWriterCommitMessage.toBytes(messages))
-      }
-    }(handle.close())
+    abortWrite(library, name, handle, -1L, messages)
   }
 }
 
 /**
- * Writes to a native data source for a streaming write. Its handle is closed 
when the streaming
- * query creates its next stream writer, or, for the last stream writer of the 
query, once the
- * handle becomes unreachable, see [[NativeStreamWriters]].
+ * Writes to a native data source for a streaming write, one micro-batch. As 
for a batch write, its
+ * handle is closed once the micro-batch is committed or aborted. A stream 
writer that is neither
+ * committed nor aborted is closed before the streaming query creates its next 
stream writer, or
+ * once the handle becomes unreachable, see [[NativeStreamWriters]].
  */
 class NativeDataSourceStreamWriter(
     location: NativeLibraryLocation,
@@ -593,17 +587,12 @@ class NativeDataSourceStreamWriter(
       location, name, schema, timeZoneId, writerState, partitionId, taskId, 
epochId)
   }
 
-  // Spark does not abort a committed micro-batch, see ColumnarStreamingWrite.
   override def commit(epochId: Long, messages: Array[WriterCommitMessage]): 
Unit = {
-    call(name, "commit a write to") {
-      library.commit(handle.get, epochId, 
NativeWriterCommitMessage.toBytes(messages))
-    }
+    commitWrite(library, name, handle, epochId, messages)
   }
 
   override def abort(epochId: Long, messages: Array[WriterCommitMessage]): 
Unit = {
-    call(name, "abort a write to") {
-      library.abort(handle.get, epochId, 
NativeWriterCommitMessage.toBytes(messages))
-    }
+    abortWrite(library, name, handle, epochId, messages)
   }
 }
 
@@ -1412,22 +1401,30 @@ object NativeHandle extends Logging {
 }
 
 /**
- * The stream writers of the streaming queries, by query ID. The Data Source 
V2 streaming write
- * has no hook for when the query stops, but a micro-batch streaming query 
creates a new stream
- * writer for each micro-batch, after the previous micro-batch committed or 
aborted its write, and
- * a restarted query creates a new one. So the previous stream writer of a 
query is closed when
- * the query creates a new one, and the last one when it becomes unreachable.
+ * The stream writers of the streaming queries, by query ID, to close those 
that are neither
+ * committed nor aborted: a stream writer closes its handle once its 
micro-batch is committed or
+ * aborted. The Data Source V2 streaming write has no hook for when the query 
stops, but a
+ * micro-batch streaming query creates a new stream writer for each 
micro-batch, and a restarted
+ * query creates a new one. So a previous stream writer of a query that is 
still open is closed
+ * before the query creates a new one, and the last one when it becomes 
unreachable.
  */
 object NativeStreamWriters {
   // Weak, so that the last stream writer of a query can still become 
unreachable.
   private val writers = new ConcurrentHashMap[String, 
WeakReference[NativeHandle]]()
 
-  /** Registers the new stream writer of the query, and closes its previous 
one. */
-  def register(queryId: String, handle: NativeHandle): Unit = {
-    // Forgets the queries whose last stream writer was released.
+  /**
+   * Closes the previous stream writer of the query, before the query creates 
a new one. This has
+   * no effect if that one is already closed.
+   */
+  def closePrevious(queryId: String): Unit = {
+    // Forgets the queries whose last stream writer became unreachable.
     writers.values().removeIf(_.get() == null)
-    Option(writers.put(queryId, new WeakReference(handle))).flatMap(r => 
Option(r.get()))
-      .foreach(_.close())
+    Option(writers.remove(queryId)).flatMap(r => 
Option(r.get())).foreach(_.close())
+  }
+
+  /** Registers the new stream writer of the query. */
+  def register(queryId: String, handle: NativeHandle): Unit = {
+    writers.put(queryId, new WeakReference(handle))
   }
 }
 
@@ -1477,6 +1474,41 @@ object NativeCalls {
   def bytesOrEmpty(bytes: Option[Array[Byte]]): Array[Byte] = {
     bytes.flatMap(Option(_)).getOrElse(Array.emptyByteArray)
   }
+
+  /**
+   * Commits the write of a writer, for the epoch of a micro-batch or -1 for a 
batch write, and
+   * closes the writer. It is not closed if the commit fails: Spark then 
aborts the write, which
+   * closes it. Spark does not abort a committed write, see ColumnarBatchWrite 
and
+   * ColumnarStreamingWrite.
+   */
+  def commitWrite(
+      library: NativeLibrary,
+      name: String,
+      handle: NativeHandle,
+      epochId: Long,
+      messages: Array[WriterCommitMessage]): Unit = {
+    call(name, "commit a write to") {
+      library.commit(handle.get, epochId, 
NativeWriterCommitMessage.toBytes(messages))
+    }
+    handle.close()
+  }
+
+  /**
+   * Aborts the write of a writer, for the epoch of a micro-batch or -1 for a 
batch write, and
+   * closes the writer, also if the abort fails.
+   */
+  def abortWrite(
+      library: NativeLibrary,
+      name: String,
+      handle: NativeHandle,
+      epochId: Long,
+      messages: Array[WriterCommitMessage]): Unit = {
+    Utils.tryWithSafeFinally {
+      call(name, "abort a write to") {
+        library.abort(handle.get, epochId, 
NativeWriterCommitMessage.toBytes(messages))
+      }
+    }(handle.close())
+  }
 }
 
 /** Exchanges schemas with native libraries through the Arrow C data 
interface. */
diff --git 
a/sql/core/src/test/resources/native-datasource/test_native_datasource.cc 
b/sql/core/src/test/resources/native-datasource/test_native_datasource.cc
index 3faee61f8083..69b29ab6b940 100644
--- a/sql/core/src/test/resources/native-datasource/test_native_datasource.cc
+++ b/sql/core/src/test/resources/native-datasource/test_native_datasource.cc
@@ -1807,7 +1807,8 @@ int commitWrite(void* handle, const 
SparkDsFinishWriteInfo* info) {
 // Records the aborted write in _ABORTED for a batch write or a rejected 
writer, or
 // _ABORTED_<epoch> for a streaming one, as "<NULL 
messages>,<messages>,<rejected>": the number of
 // tasks that did not commit, the number of messages, and 1 for a writer whose 
create_writer
-// Spark rejected.
+// Spark rejected. With the option "fail" set to "abort", it fails before it 
records anything,
+// but its writer still records that it is closed.
 int abortWrite(void* handle, const SparkDsFinishWriteInfo* info) {
   auto* writer = fromHandle<Writer>(handle);
   if (writer->abort_called) orderViolation("abort called twice");
@@ -1817,6 +1818,7 @@ int abortWrite(void* handle, const 
SparkDsFinishWriteInfo* info) {
     checkSize("SparkDsFinishWriteInfo", info->size, 
sizeof(SparkDsFinishWriteInfo));
     int64_t epoch_id = info->epoch_id;
     writer->closed_marker = closedMarker(epoch_id);
+    maybeFail(writer->state, "abort");
     bool has_null = false;
     for (const auto& message :
          toByteStrings(info->messages, info->message_lengths, 
info->num_messages, &has_null)) {
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala
index 4bee99a474ef..af01c4980abc 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala
@@ -281,7 +281,11 @@ class NativeDataSourceSuite extends QueryTest with 
SharedSparkSession {
     NativeStreamWriters.register("query", first)
     NativeStreamWriters.register("other query", other)
     assert(released.isEmpty)
+    // Closed before the query creates its next stream writer.
+    NativeStreamWriters.closePrevious("query")
+    assert(released == Seq(1L))
     NativeStreamWriters.register("query", second)
+    NativeStreamWriters.closePrevious("new query")
     assert(released == Seq(1L))
     second.close()
     other.close()
@@ -929,25 +933,56 @@ class NativeDataSourceSuite extends QueryTest with 
SharedSparkSession {
       new NativeDataSource(location, resolved, new 
CaseInsensitiveStringMap(options.toMap.asJava))
     }
     val schema = StructType.fromDDL("id BIGINT")
+    def newBatchWrite(dir: File, options: (String, String)*): 
ColumnarBatchWrite = {
+      val write = new ColumnarBatchWrite(
+        () => dataSource("native_sink", ("path" -> dir.getPath) +: options: _*)
+          .writer(schema, false),
+        schema)
+      write.createBatchWriterFactory(PhysicalWriteInfoImpl(1))
+      write
+    }
+    def newStreamWrite(dir: File, options: (String, String)*): 
ColumnarStreamingWrite = {
+      val write = new ColumnarStreamingWrite("native_sink",
+        () => dataSource("native_sink", ("path" -> dir.getPath) +: options: _*)
+          .streamWriter(schema, false, UUID.randomUUID().toString),
+        schema)
+      write.createStreamingWriterFactory(PhysicalWriteInfoImpl(1))
+      write
+    }
     // The test library records each call that the header rules out, which 
fails the test.
 
-    // A write or a micro-batch that committed is not aborted.
+    // A write or a micro-batch that committed is not aborted, and its writer 
is closed right away.
     val batchDir = Utils.createTempDir()
-    val batchWrite = new ColumnarBatchWrite(
-      () => dataSource("native_sink", "path" -> 
batchDir.getPath).writer(schema, false), schema)
-    batchWrite.createBatchWriterFactory(PhysicalWriteInfoImpl(1))
+    val batchWrite = newBatchWrite(batchDir)
     batchWrite.commit(Array.empty)
     batchWrite.abort(Array.empty)
     assert(new File(batchDir, "_SUCCESS").isFile && !new File(batchDir, 
"_ABORTED").exists())
+    assert(new File(batchDir, "_CLOSED").isFile)
     val streamDir = Utils.createTempDir()
-    val streamWrite = new ColumnarStreamingWrite("native_sink",
-      () => dataSource("native_sink", "path" -> streamDir.getPath)
-        .streamWriter(schema, false, UUID.randomUUID().toString),
-      schema)
-    streamWrite.createStreamingWriterFactory(PhysicalWriteInfoImpl(1))
+    val streamWrite = newStreamWrite(streamDir)
     streamWrite.commit(0, Array.empty)
     streamWrite.abort(0, Array.empty)
     assert(new File(streamDir, "_EPOCH_0").isFile && !new File(streamDir, 
"_ABORTED_0").exists())
+    assert(new File(streamDir, "_CLOSED_0").isFile)
+
+    // A writer whose abort fails is closed all the same.
+    def checkAbortError(abort: => Unit): Unit = checkError(
+      exception = findError(intercept[Exception](abort), 
"NATIVE_DATA_SOURCE_ERROR"),
+      condition = "NATIVE_DATA_SOURCE_ERROR",
+      parameters = Map(
+        "action" -> "abort a write to",
+        "name" -> "native_sink",
+        "msg" -> "injected failure in abort"))
+    val failingBatchDir = Utils.createTempDir()
+    val failingBatchWrite = newBatchWrite(failingBatchDir, "fail" -> "abort")
+    checkAbortError(failingBatchWrite.abort(Array.empty))
+    assert(!new File(failingBatchDir, "_ABORTED").exists())
+    assert(new File(failingBatchDir, "_CLOSED").isFile)
+    val failingStreamDir = Utils.createTempDir()
+    val failingStreamWrite = newStreamWrite(failingStreamDir, "fail" -> 
"abort")
+    checkAbortError(failingStreamWrite.abort(0, Array.empty))
+    assert(!new File(failingStreamDir, "_ABORTED_0").exists())
+    assert(new File(failingStreamDir, "_CLOSED_0").isFile)
 
     // After a write fails, a data writer only aborts and closes the data 
writer of the library.
     val failingDir = Utils.createTempDir()
@@ -995,29 +1030,34 @@ class NativeDataSourceSuite extends QueryTest with 
SharedSparkSession {
     builder.build().toBatch.planInputPartitions()
   }
 
-  nativeTest("abort a micro-batch whose write failed") {
-    val session = newSession(defaultPackage)
-    val dir = Utils.createTempDir()
-    val e = intercept[Exception] {
-      val query = 
session.readStream.format("native_counter").option("max_offset", "4").load()
-        .writeStream
-        .format("native_sink")
-        .option("path", dir.getPath)
-        .option("fail", "write")
-        .option("checkpointLocation", Utils.createTempDir().getPath)
-        .start()
-      try query.processAllAvailable() finally query.stop()
-    }
-    checkError(
-      exception = findError(e, "NATIVE_DATA_SOURCE_ERROR"),
-      condition = "NATIVE_DATA_SOURCE_ERROR",
-      parameters = Map(
-        "action" -> "write to",
-        "name" -> "native_sink",
-        "msg" -> "injected failure in write"))
-    // Spark aborted the first epoch, with a null message for its task, which 
did not commit.
-    assert(Files.readString(new File(dir, "_ABORTED_0").toPath) == "1,1,0")
-    assert(!new File(dir, "_EPOCH_0").exists())
+  Seq(("write", "write to", "1,1,0"), ("commit", "commit a write to", 
"0,1,0")).foreach {
+    case (fail, action, aborted) =>
+      nativeTest(s"abort a micro-batch whose $fail failed") {
+        val session = newSession(defaultPackage)
+        val dir = Utils.createTempDir()
+        val e = intercept[Exception] {
+          val query = 
session.readStream.format("native_counter").option("max_offset", "4").load()
+            .writeStream
+            .format("native_sink")
+            .option("path", dir.getPath)
+            .option("fail", fail)
+            .option("checkpointLocation", Utils.createTempDir().getPath)
+            .start()
+          try query.processAllAvailable() finally query.stop()
+        }
+        checkError(
+          exception = findError(e, "NATIVE_DATA_SOURCE_ERROR"),
+          condition = "NATIVE_DATA_SOURCE_ERROR",
+          parameters = Map(
+            "action" -> action,
+            "name" -> "native_sink",
+            "msg" -> s"injected failure in $fail"))
+        // Spark aborted the first epoch with its writer, which it closed 
afterwards: with a null
+        // message for a task that did not commit, or the message of one that 
did.
+        assert(Files.readString(new File(dir, "_ABORTED_0").toPath) == aborted)
+        assert(!new File(dir, "_EPOCH_0").exists())
+        assert(new File(dir, "_CLOSED_0").isFile)
+      }
   }
 
   nativeTest("continuous processing fails with a native data source") {
@@ -1072,14 +1112,14 @@ class NativeDataSourceSuite extends QueryTest with 
SharedSparkSession {
         
query.asInstanceOf[StreamingQueryWrapper].streamingQuery.lastExecution.executedPlan
       assert(plan.collectFirst { case write: V2TableWriteExec => write.query }
         .exists(_.isInstanceOf[MicroBatchScanExec]), plan)
+      // Each micro-batch creates a new stream writer, which is closed once it 
committed, so the
+      // writer of the last micro-batch is closed too while the query still 
runs.
+      assert((0 to 2).forall(epoch => new File(dir, s"_CLOSED_$epoch").isFile))
     } finally {
       query.stop()
     }
     // Each micro-batch makes 5 more rows available after its start: [0, 5), 
[5, 10) and [10, 12).
     assert((0 to 2).forall(epoch => new File(dir, s"_EPOCH_$epoch").isFile))
-    // Each micro-batch creates a new stream writer, which closes the one of 
the previous
-    // micro-batch. The last one is closed once it is no longer referenced.
-    assert((0 to 1).forall(epoch => new File(dir, s"_CLOSED_$epoch").isFile))
     val written = dir.listFiles().filter(_.getName.startsWith("part-"))
       .flatMap(file => Files.readAllLines(file.toPath).asScala)
     assert(written.sorted.toSeq == (0 until 12).map(_.toString).sorted)


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to