You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by ka...@apache.org on 2026/08/26 04:07:36 UTC

(spark) branch branch-4.x updated: [SPARK-58977][SS][PYTHON] Handle state server shutdown before Python connects

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

HeartSaVioR pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.x by this push:
     new e0e60e9c6c76 [SPARK-58977][SS][PYTHON] Handle state server shutdown before Python connects
e0e60e9c6c76 is described below

commit e0e60e9c6c76b5425986e399d1c19fd0c8af4306
Author: Jonathan Gao <jo...@hotmail.com>
AuthorDate: Wed Aug 26 13:07:11 2026 +0900

    [SPARK-58977][SS][PYTHON] Handle state server shutdown before Python connects
    
    ### What changes were proposed in this pull request?
    
    This pull request handles state server shutdown while the listener is still waiting for the Python worker to connect.
    
    The patch makes the following changes:
    
    1. Reorders `TransformWithStateInPySparkPythonRunner.stop()` so that it interrupts the state server listener thread before closing the server socket channel. This matches the existing executor-side cleanup ordering.
    2. Handles expected interruption and channel-closure exceptions thrown by `ServerSocketChannel.accept()` before the Python worker connects.
    3. Preserves the listener thread's interrupt status for interrupt-driven shutdown and transitions the stateful processor handle to `CLOSED`.
    4. Treats `ClosedChannelException`, including its `AsynchronousCloseException` subclass, as an expected shutdown path without incorrectly setting the interrupt status.
    5. Adds regression coverage for the Java NIO exception hierarchy and interrupt semantics.
    6. Adds real loopback `ServerSocketChannel` tests for both interruption before entering `accept()` and interruption while the listener is blocked inside `accept()`. The tests verify bounded listener termination, no escaped exception, channel closure, the `CLOSED` handle state, and no protocol output.
    
    No public APIs or configuration options are added or changed.
    
    ### Why are the changes needed?
    
    When a TransformWithState in PySpark runner is stopped before the Python worker connects to its JVM state server, the listener can still be blocked in `ServerSocketChannel.accept()`.
    
    Previously, the driver-side cleanup closed the server socket channel before interrupting the listener thread. Closing the channel wakes the listener with an expected `AsynchronousCloseException`. Because the pre-connect path did not handle this exception, it escaped `TransformWithStateInPySparkStateServer.run()` and was wrapped as:
    
    ```text
    TransformWithStateInPySpark state server daemon thread exited unexpectedly (crashed)
    ```
    
    This reports an orderly shutdown as an unexpected daemon-thread failure. The same listener implementation is used by the executor-side lifecycle, where interruption can produce `ClosedByInterruptException`.
    
    The patch makes both expected shutdown paths explicit. It interrupts before closing, handles the relevant Java NIO exception hierarchy, restores the interrupt flag only for interrupt-driven shutdown, and transitions the processor handle to its terminal `CLOSED` state.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes.
    
    Previously, stopping a TransformWithState in PySpark query before its Python worker connected could report the expected state server listener shutdown as an unexpected daemon-thread crash.
    
    After this change, the state server listener terminates cleanly during this shutdown window. Expected interruption or channel-closure exceptions no longer surface as a spurious `SparkException`.
    
    This is a bug fix relative to released Spark versions as well as the behavior on the current `master` branch. It does not change the TransformWithState API or successful query execution behavior.
    
    ### How was this patch tested?
    
    Added tests to `TransformWithStateInPySparkStateServerSuite` covering:
    
    1. `InterruptedException`, `InterruptedIOException`, and `ClosedByInterruptException` while waiting for the Python worker, including preservation of the listener thread's interrupt status.
    2. `AsynchronousCloseException` and `ClosedChannelException` while waiting for the Python worker, including verification that the listener thread is not marked interrupted.
    3. A real loopback `ServerSocketChannel` with the listener thread already interrupted before entering `accept()`.
    4. A real loopback `ServerSocketChannel` with the listener confirmed to be blocked inside `accept()` before applying the production-equivalent interrupt-then-close shutdown sequence.
    5. Bounded listener termination, no escaped throwable, server channel closure, transition to `StatefulProcessorHandleState.CLOSED`, and no protocol output for the real-channel shutdown paths.
    
    The following local static checks passed:
    
    ```bash
    git diff --check
    dev/lint-scala
    ```
    
    `dev/lint-scala` completed both the Scalastyle and Scalafmt checks successfully.
    
    The focused suite can be run with:
    
    ```bash
    build/sbt -Phive -Phive-thriftserver \
      "sql/core/testOnly org.apache.spark.sql.execution.python.streaming.TransformWithStateInPySparkStateServerSuite"
    ```
    
    The focused SBT suite could not be executed in the local development environment because Maven Central and the SBT repository hosts failed DNS resolution while retrieving the required SBT launcher and dependencies. The generated partial launcher file was removed from the worktree. The suite is expected to run in GitHub Actions, where the build dependencies are available.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: databricks-gpt-5-6-sol on KiroCrew 0.2.0-customapi.5
    
    Closes #58217 from nahtonaj/fix/spark-58751-listener-shutdown.
    
    Authored-by: Jonathan Gao <jo...@hotmail.com>
    Signed-off-by: Jungtaek Lim <ka...@gmail.com>
    (cherry picked from commit 771e46c7de2f7ec7182f486e17e98c0c05b30b9e)
    Signed-off-by: Jungtaek Lim <ka...@gmail.com>
---
 .../TransformWithStateInPySparkPythonRunner.scala  |   2 +-
 .../TransformWithStateInPySparkStateServer.scala   |  21 +++-
 ...ansformWithStateInPySparkStateServerSuite.scala | 108 ++++++++++++++++++++-
 3 files changed, 126 insertions(+), 5 deletions(-)

diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/streaming/TransformWithStateInPySparkPythonRunner.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/streaming/TransformWithStateInPySparkPythonRunner.scala
index 488ac1a0bd23..0b7e6b938689 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/streaming/TransformWithStateInPySparkPythonRunner.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/streaming/TransformWithStateInPySparkPythonRunner.scala
@@ -333,10 +333,10 @@ class TransformWithStateInPySparkPythonPreInitRunner(
 
   override def stop(): Unit = {
     super.stop()
-    closeServerSocketChannelSilently(stateServerSocket)
     if (daemonThread != null) {
       daemonThread.interrupt()
     }
+    closeServerSocketChannelSilently(stateServerSocket)
   }
 
   private def startStateServer(): Unit = {
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/streaming/TransformWithStateInPySparkStateServer.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/streaming/TransformWithStateInPySparkStateServer.scala
index 4fee6a6e71d3..61df2ff1116a 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/streaming/TransformWithStateInPySparkStateServer.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/streaming/TransformWithStateInPySparkStateServer.scala
@@ -18,7 +18,12 @@
 package org.apache.spark.sql.execution.python.streaming
 
 import java.io.{BufferedInputStream, BufferedOutputStream, DataInputStream, DataOutputStream, EOFException, InterruptedIOException}
-import java.nio.channels.{Channels, ClosedByInterruptException, ServerSocketChannel}
+import java.nio.channels.{
+  Channels,
+  ClosedByInterruptException,
+  ClosedChannelException,
+  ServerSocketChannel
+}
 import java.time.Duration
 
 import scala.collection.mutable
@@ -138,7 +143,19 @@ class TransformWithStateInPySparkStateServer(
   } else new mutable.HashMap[String, Iterator[Long]]()
 
   def run(): Unit = {
-    val listeningSocket = stateServerSocket.accept()
+    val listeningSocket = try {
+      stateServerSocket.accept()
+    } catch {
+      case _: InterruptedException | _: InterruptedIOException | _: ClosedByInterruptException =>
+        logInfo(log"State server listener interrupted before the Python worker connected")
+        Thread.currentThread().interrupt()
+        statefulProcessorHandle.setHandleState(StatefulProcessorHandleState.CLOSED)
+        return
+      case _: ClosedChannelException =>
+        logInfo(log"State server socket closed before the Python worker connected")
+        statefulProcessorHandle.setHandleState(StatefulProcessorHandleState.CLOSED)
+        return
+    }
 
     // SPARK-51667: We have a pattern of sending messages continuously from one side
     // (Python -> JVM, and vice versa) before getting response from other side. Since most
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/streaming/TransformWithStateInPySparkStateServerSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/streaming/TransformWithStateInPySparkStateServerSuite.scala
index e253a6aa45c3..b1d586d2207b 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/streaming/TransformWithStateInPySparkStateServerSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/streaming/TransformWithStateInPySparkStateServerSuite.scala
@@ -16,15 +16,25 @@
  */
 package org.apache.spark.sql.execution.python.streaming
 
-import java.io.DataOutputStream
-import java.nio.channels.ServerSocketChannel
+import java.io.{DataOutputStream, InterruptedIOException}
+import java.net.InetSocketAddress
+import java.nio.channels.{
+  AsynchronousCloseException,
+  ClosedByInterruptException,
+  ClosedChannelException,
+  ServerSocketChannel
+}
+import java.util.concurrent.atomic.AtomicReference
 
 import scala.collection.mutable
+import scala.concurrent.duration._
 
 import com.google.protobuf.ByteString
 import org.mockito.ArgumentMatchers.{any, argThat}
 import org.mockito.Mockito.{mock, times, verify, when}
+import org.mockito.invocation.InvocationOnMock
 import org.scalatest.BeforeAndAfterEach
+import org.scalatest.concurrent.Eventually.{eventually, timeout}
 
 import org.apache.spark.SparkFunSuite
 import org.apache.spark.sql.{Encoder, Row}
@@ -637,6 +647,100 @@ class TransformWithStateInPySparkStateServerSuite extends SparkFunSuite with Bef
     verify(outputStream).writeInt(argThat((x: Int) => x > 0))
   }
 
+  Seq(
+    ("InterruptedException", () => new InterruptedException()),
+    ("InterruptedIOException", () => new InterruptedIOException()),
+    ("ClosedByInterruptException", () => new ClosedByInterruptException())
+  ).foreach { case (name, newException) =>
+    test(s"run handles $name while waiting for the Python worker") {
+      Thread.interrupted()
+      val socket = mock(classOf[ServerSocketChannel])
+      when(socket.accept())
+        .thenAnswer((_: InvocationOnMock) => throw newException())
+
+      try {
+        newStateServer(socket).run()
+        assert(Thread.currentThread().isInterrupted)
+      } finally {
+        Thread.interrupted()
+      }
+
+      verify(statefulProcessorHandle).setHandleState(StatefulProcessorHandleState.CLOSED)
+      verify(outputStream, times(0)).writeInt(any[Int])
+    }
+  }
+
+  Seq(
+    ("AsynchronousCloseException", () => new AsynchronousCloseException()),
+    ("ClosedChannelException", () => new ClosedChannelException())
+  ).foreach { case (name, newException) =>
+    test(s"run handles $name while waiting for the Python worker") {
+      Thread.interrupted()
+      val socket = mock(classOf[ServerSocketChannel])
+      when(socket.accept())
+        .thenAnswer((_: InvocationOnMock) => throw newException())
+
+      newStateServer(socket).run()
+
+      assert(!Thread.currentThread().isInterrupted)
+      verify(statefulProcessorHandle).setHandleState(StatefulProcessorHandleState.CLOSED)
+      verify(outputStream, times(0)).writeInt(any[Int])
+    }
+  }
+
+  Seq(
+    ("before accept", true),
+    ("while blocked in accept", false)
+  ).foreach { case (name, interruptBeforeRun) =>
+    test(s"run handles real channel shutdown $name") {
+      val socket = ServerSocketChannel.open()
+      socket.bind(new InetSocketAddress("127.0.0.1", 0))
+      val failure = new AtomicReference[Throwable]()
+      val listener = new Thread(() => {
+        if (interruptBeforeRun) {
+          Thread.currentThread().interrupt()
+        }
+        try {
+          newStateServer(socket).run()
+        } catch {
+          case t: Throwable => failure.set(t)
+        }
+      })
+
+      try {
+        listener.start()
+        if (!interruptBeforeRun) {
+          eventually(timeout(10.seconds)) {
+            assert(listener.getStackTrace.exists(_.getMethodName == "accept"))
+          }
+          listener.interrupt()
+        }
+        socket.close()
+        listener.join(10000)
+
+        assert(!listener.isAlive)
+        assert(failure.get() == null)
+        assert(!socket.isOpen)
+        verify(statefulProcessorHandle).setHandleState(StatefulProcessorHandleState.CLOSED)
+        verify(outputStream, times(0)).writeInt(any[Int])
+      } finally {
+        listener.interrupt()
+        socket.close()
+        listener.join(10000)
+      }
+    }
+  }
+
+  private def newStateServer(
+      socket: ServerSocketChannel): TransformWithStateInPySparkStateServer = {
+    new TransformWithStateInPySparkStateServer(socket,
+      statefulProcessorHandle, groupingKeySchema, 2,
+      batchTimestampMs, eventTimeWatermarkForEviction,
+      outputStream, valueStateMap, transformWithStateInPySparkDeserializer,
+      listStateMap, mutable.HashMap[String, Iterator[Row]](), mapStateMap,
+      mutable.HashMap[String, Iterator[(Row, Row)]](), expiryTimerIter, listTimerMap)
+  }
+
   private def getIntegerRow(value: Int): Row = {
     new GenericRowWithSchema(Array(value), stateSchema)
   }


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