viirya commented on code in PR #60540:
URL: https://github.com/apache/spark/pull/60540#discussion_r4595103985


##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -1384,12 +1455,30 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
         throw new 
TaskKilledException(context.getKillReason().getOrElse("unknown reason"))
 
       case e: Exception if writer.exception.isDefined =>
-        logError(log"Python worker exited unexpectedly (crashed) - " +
-          log"${MDC(TASK_NAME, taskIdentifier(context))}", e)
-        logError(log"This may have been caused by a prior exception - " +
-          log"${MDC(TASK_NAME, taskIdentifier(context))}",
-          writer.exception.get)
-        throw writer.exception.get
+        val writerException = writer.exception.get
+        e match {
+          // The flag is read only after the exception was seen, which makes 
this consistent
+          // with a writer that fails concurrently; see `Writer.setException`.
+          case killed: PythonWorkerException if writer.failedWritingToWorker =>

Review Comment:
   The path is there, but I could not get it to happen: with a UDF that raises 
on its first batch over `spark.range(0, 50000000, 1, 1)` in pipelined mode, the 
Python traceback was reported in 5 out of 5 runs, since the reader gets the 
exception before the worker exits and the writer fails. It can still happen 
when the reader is not waiting on the worker at that moment. As it is not about 
the idle timeout, I would rather look at it in a follow-up.



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -1384,12 +1455,30 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
         throw new 
TaskKilledException(context.getKillReason().getOrElse("unknown reason"))
 
       case e: Exception if writer.exception.isDefined =>

Review Comment:
   Done in 3d5aa099e77. `ReaderIterator.throwIfWriterFailed()` replaces these 
checks. It still throws whenever the writer has failed, and throws the idle 
timeout error instead when the writer failed writing to the worker and the 
handler of the pipelined stream has killed the worker. For `handleInitResponse` 
nothing changes in practice, since no read comes before it.



##########
core/src/test/scala/org/apache/spark/api/python/BasePythonRunnerSuite.scala:
##########
@@ -1108,7 +1103,307 @@ class BasePythonRunnerSuite extends SparkFunSuite with 
SharedSparkContext {
         "Idle timeout reached for Python worker (timeout: 3 seconds). " +
           "No data received from the worker process - handle.map(_.isAlive) = 
None, " +
           s"$blockingWorkerStatus - $task"))
-      handler.throwIfKilled(-1)
+      assert(handler.readBlocking(-1) === -1)
+    }
+  }
+
+  /**
+   * Closes `peer` so that the other end of the connection sees a reset 
instead of the end of
+   * the stream, like the connection of a worker that is killed while it has 
unread input.
+   */
+  private def reset(peer: SocketChannel): Unit = {
+    peer.setOption[Integer](StandardSocketOptions.SO_LINGER, 0)
+    peer.close()
+  }
+
+  private val idleTimeoutError =
+    "Python worker process terminated due to idle timeout (timeout: 1 seconds)"
+
+  test("a read that fails after the idle timeout killed the worker reports the 
idle timeout") {
+    // Pipelined mode: the read times out, the worker is killed, and the read 
that is tried
+    // again fails with a connection reset.
+    withIdleWorker(blocking = true) { (worker, peer) =>
+      val handle = new RecordingWorkerHandle(
+        diagnostics = Some("worker stack"), onDestroy = () => reset(peer))
+      val handler = new BasePythonRunner.IdleTimeoutHandler(
+        worker, Some(handle), idleTimeoutSeconds = 1, killOnIdleTimeout = true,
+        Some(TaskContext.empty()), idleTimeoutLoggerName)
+      // The handler does not measure how long the read waited, so a short 
timeout is enough.
+      worker.channel.socket().setSoTimeout(10)
+      val in = worker.channel.socket().getInputStream
+      val e = intercept[PythonWorkerException] {
+        handler.readBlocking(in.read())
+      }
+      assert(e.getMessage === s"$idleTimeoutError: worker stack")
+      assert(e.getCause.isInstanceOf[SocketException], e.getCause)
+      assert(handle.destroyCalls.get() === 1)
+    }
+
+    // Selector based streams: the worker is killed, and the read from the 
channel fails with
+    // a connection reset.
+    withIdleWorker(blocking = false) { (worker, peer) =>
+      val handle = new RecordingWorkerHandle(onDestroy = () => reset(peer))
+      val handler = new BasePythonRunner.IdleTimeoutHandler(
+        worker, Some(handle), idleTimeoutSeconds = 1, killOnIdleTimeout = true,
+        None, idleTimeoutLoggerName)
+      handler.onIdleTimeout(hasInputs = false)
+      assert(handle.destroyCalls.get() === 1)
+      handler.select(hasInputs = false)
+      assert(worker.selectionKey.isReadable)
+      val e = intercept[PythonWorkerException] {
+        handler.read(ByteBuffer.allocate(8))
+      }
+      assert(e.getMessage === idleTimeoutError)
+      assert(e.getCause.isInstanceOf[IOException], e.getCause)
+    }
+  }
+
+  test("a read that times out after the idle timeout killed the worker is 
tried again") {
+    withIdleWorker(blocking = true) { (worker, _) =>
+      val handle = new RecordingWorkerHandle()
+      val handler = new BasePythonRunner.IdleTimeoutHandler(
+        worker, Some(handle), idleTimeoutSeconds = 1, killOnIdleTimeout = true,
+        Some(TaskContext.empty()), idleTimeoutLoggerName)
+      var reads = 0
+      var e: PythonWorkerException = null
+      val warnings = idleTimeoutWarnings {
+        e = intercept[PythonWorkerException] {
+          handler.readBlocking {
+            reads += 1
+            if (reads <= 2) throw new SocketTimeoutException("Read timed out") 
else -1
+          }
+        }
+      }
+      // The second timeout comes while the killed worker is still 
terminating. It neither
+      // fails the read nor kills the worker again.
+      assert(reads === 3)
+      assert(handle.destroyCalls.get() === 1)
+      assert(warnings.length === 3)
+      assert(warnings(0).startsWith("Idle timeout reached for Python worker"))
+      assert(warnings(1).startsWith("Terminating Python worker process due to 
idle timeout"))
+      assert(warnings(2).startsWith(
+        "Waiting for Python worker process to terminate after idle timeout"))
+      assert(e.getMessage === idleTimeoutError)
+      assert(e.getCause === null)
+    }
+  }
+
+  test("a write that fails after the idle timeout killed the worker reports 
the idle timeout") {
+    withIdleWorker(blocking = false) { (worker, peer) =>
+      val handle = new RecordingWorkerHandle(onDestroy = () => reset(peer))
+      val handler = new BasePythonRunner.IdleTimeoutHandler(
+        worker, Some(handle), idleTimeoutSeconds = 1, killOnIdleTimeout = true,
+        None, idleTimeoutLoggerName)
+      assert(handler.write(ByteBuffer.wrap(new Array[Byte](4))) === 4)
+      handler.onIdleTimeout(hasInputs = true)
+      // Wait for the reset to arrive.
+      handler.select(hasInputs = true)
+      val e = intercept[PythonWorkerException] {
+        handler.write(ByteBuffer.wrap(new Array[Byte](4)))
+      }
+      assert(e.getMessage === idleTimeoutError)
+      assert(e.getCause.isInstanceOf[IOException], e.getCause)
+    }
+  }
+
+  test("a failure that is not caused by the idle timeout kill is not 
attributed to it") {
+    // No timeout was reached: the worker closed the connection on its own.
+    withIdleWorker(blocking = false) { (worker, peer) =>
+      val handle = new RecordingWorkerHandle()
+      val handler = new BasePythonRunner.IdleTimeoutHandler(
+        worker, Some(handle), idleTimeoutSeconds = 60, killOnIdleTimeout = 
true,
+        Some(TaskContext.empty()), idleTimeoutLoggerName)
+      reset(peer)
+      handler.select(hasInputs = false)
+      val e = intercept[IOException] {
+        handler.read(ByteBuffer.allocate(8))
+      }
+      assert(!e.isInstanceOf[SocketTimeoutException], e)
+      intercept[IOException] {
+        handler.write(ByteBuffer.wrap(new Array[Byte](4)))
+      }
+      assert(handle.destroyCalls.get() === 0)
+    }
+
+    // The timeout was reached but the worker is not killed, so the read is 
tried again and
+    // its failure is not attributed to the idle timeout.
+    Seq(
+      (new RecordingWorkerHandle(), false),
+      (new RecordingWorkerHandle(destroyIssued = false), true),
+      (new RecordingWorkerHandle(alive = false), true)
+    ).foreach { case (handle, killOnIdleTimeout) =>
+      withIdleWorker(blocking = true) { (worker, _) =>
+        val handler = new BasePythonRunner.IdleTimeoutHandler(
+          worker, Some(handle), idleTimeoutSeconds = 1, killOnIdleTimeout = 
killOnIdleTimeout,
+          Some(TaskContext.empty()), idleTimeoutLoggerName)
+        val failure = new IOException("Connection reset")
+        var reads = 0
+        val e = intercept[IOException] {
+          handler.readBlocking {
+            reads += 1
+            throw (if (reads == 1) new SocketTimeoutException("Read timed 
out") else failure)
+          }
+        }
+        assert(e eq failure)
+        assert(reads === 2)
+      }
+    }
+
+    // After the kill, a failure that is not an I/O failure, or that comes 
from this side
+    // closing the channel or interrupting the thread, is thrown as is.
+    withIdleWorker(blocking = false) { (worker, _) =>
+      val handler = new BasePythonRunner.IdleTimeoutHandler(
+        worker, Some(new RecordingWorkerHandle()), idleTimeoutSeconds = 1,
+        killOnIdleTimeout = true, None, idleTimeoutLoggerName)
+      handler.onIdleTimeout(hasInputs = false)
+      Seq(
+        new IllegalStateException("not I/O"),
+        new ClosedByInterruptException(),
+        new AsynchronousCloseException(),
+        new ClosedChannelException()
+      ).foreach { failure =>
+        assert(intercept[Exception](handler.readBlocking(throw failure)) eq 
failure)
+      }
+      worker.channel.close()
+      intercept[ClosedChannelException] {
+        handler.read(ByteBuffer.allocate(8))
+      }
+      intercept[ClosedChannelException] {
+        handler.write(ByteBuffer.wrap(new Array[Byte](4)))
+      }
+    }
+  }
+
+  /**
+   * Runs `f` with a runner, and with a writer of it whose input is written by 
`writeNextInput`
+   * and that writes nothing else. By default it has no input.
+   */
+  private def withRunnerAndWriter(
+      worker: PythonWorker,
+      context: TaskContext,
+      writeNextInput: DataOutputStream => Boolean = _ => false)(
+      f: (PythonRunner, BasePythonRunner[Array[Byte], Array[Byte]]#Writer) => 
Unit): Unit = {
+    val func = SimplePythonFunction(
+      Seq.empty, Collections.emptyMap(), Collections.emptyList(), "python3", 
"3",
+      Collections.emptyList(), null)
+    val runner = new PythonRunner(Seq(ChainedPythonFunctions(Seq(func))), None)
+    val writer = new runner.Writer(SparkEnv.get, worker, Iterator.empty, 0, 
context) {
+      override def open(dataOut: DataOutputStream): Unit = {}
+      override protected def writeCommand(dataOut: DataOutputStream): Unit = {}
+      override def writeNextInputToStream(dataOut: DataOutputStream): Boolean =
+        writeNextInput(dataOut)
+      override def close(dataOut: DataOutputStream): Unit = {}
+    }
+    f(runner, writer)
+  }
+
+  test("ReaderInputStream reports the idle timeout when the read from the 
killed worker " +
+      "fails") {
+    withIdleWorker(blocking = false) { (worker, peer) =>
+      val context = TaskContext.empty()
+      withRunnerAndWriter(worker, context) { (runner, writer) =>
+        val handle = new RecordingWorkerHandle(onDestroy = () => reset(peer))
+        val in = new runner.ReaderInputStream(
+          worker, writer.asInstanceOf[runner.Writer], Some(handle), 
idleTimeoutSeconds = 1,
+          killOnIdleTimeout = true, context)
+        val e = intercept[PythonWorkerException] {
+          in.read(new Array[Byte](8))
+        }
+        assert(e.getMessage === idleTimeoutError)
+        assert(e.getCause.isInstanceOf[IOException], e.getCause)
+        assert(handle.destroyCalls.get() === 1)
+      }
+    }
+  }
+
+  test("the idle timeout is reported when the pipelined writer fails because 
of the kill") {

Review Comment:
   Added `test_udf_kill_on_idle_timeout_while_sending_input` with 
`spark.range(0, 50000000, 1, 1)`, so the writer is blocked sending input when 
the worker is killed.



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -1780,8 +1871,16 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
      */
     private def flushToSocket(bufferStream: DirectByteBufferOutputStream): 
Unit = {
       val buf = bufferStream.toByteBuffer
-      while (buf.hasRemaining) {
-        worker.channel.write(buf) // blocking write
+      try {
+        while (buf.hasRemaining) {
+          worker.channel.write(buf) // blocking write
+        }
+      } catch {
+        // A ClosedChannelException means that this side closed the channel or 
shut down its
+        // output, as in `IdleTimeoutHandler.causedByKill`.
+        case e: IOException if !e.isInstanceOf[ClosedChannelException] =>

Review Comment:
   Done, both use `BasePythonRunner.isFailureOfPeer`.



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -1030,15 +1084,32 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
       context: TaskContext) {
 
     @volatile private var _exception: Throwable = _
+    @volatile private var _failedWritingToWorker: Boolean = false
 
     private val pythonIncludes = 
funcs.flatMap(_.funcs.flatMap(_.pythonIncludes.asScala)).toSet
     private val broadcastVars = 
funcs.flatMap(_.funcs.flatMap(_.broadcastVars.asScala))
 
     /** Contains the throwable thrown while writing the parent iterator to the 
Python process. */
     def exception: Option[Throwable] = Option(_exception)
 
-    /** Records a throwable observed by an external collaborator (e.g. the 
pipelined writer). */
-    private[python] def setException(t: Throwable): Unit = {
+    /**
+     * Whether `exception` is an I/O failure of a write to the socket of the 
Python worker, as
+     * opposed to a failure to produce the input or a write to a channel that 
this side closed.
+     * Only the pipelined writer sets it.
+     */
+    def failedWritingToWorker: Boolean = _failedWritingToWorker
+
+    /**
+     * Records a throwable observed by an external collaborator (e.g. the 
pipelined writer).
+     *
+     * @param whileWritingToWorker whether `t` is an I/O failure of a write to 
the socket of the
+     *                             Python worker.
+     */
+    private[python] def setException(
+        t: Throwable,
+        whileWritingToWorker: Boolean = false): Unit = {

Review Comment:
   Done, the default is gone.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to