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


##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -1383,6 +1453,15 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
         logDebug("Exception thrown after task interruption", e)
         throw new 
TaskKilledException(context.getKillReason().getOrElse("unknown reason"))
 
+      case e: PythonWorkerException if writer.failedWritingToWorker =>

Review Comment:
   Right, the two guards read the writer's state in the opposite order to 
`setException`. It is one case now: it checks `writer.exception` first and 
reads the flag only after that, so a reader that sees the exception also sees 
the flag.



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -1780,8 +1861,14 @@ 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 {
+        case e: IOException =>
+          failedInSocketWrite = true

Review Comment:
   Good catch, done. `flushToSocket` leaves out `ClosedChannelException` the 
same way `causedByKill` does, and there is a test where this side shuts down 
the output before the write.



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -1743,7 +1824,7 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
           // InterruptedException and ClosedByInterruptException are matched 
above; what
           // remains here is genuine failure that needs to be propagated to the
           // reader through writer.exception + a socket EOF.
-          writer.setException(t)
+          writer.setException(t, whileWritingToWorker = failedInSocketWrite)

Review Comment:
   Agreed that the cause from `open()` is lost. With [2] the 
`ClosedChannelException` is no longer marked as a failed write to the worker, 
so this PR does not change that case anymore. I would rather fix the lost cause 
separately, since it is not related to the idle timeout.



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -1383,6 +1453,15 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
         logDebug("Exception thrown after task interruption", e)
         throw new 
TaskKilledException(context.getKillReason().getOrElse("unknown reason"))
 
+      case e: PythonWorkerException if writer.failedWritingToWorker =>
+        // The worker was killed because of the idle timeout while the 
pipelined writer was
+        // still sending input to it, so the writer failed as well. That 
failure is a result of
+        // the kill and not its cause: report the idle timeout. A writer that 
failed to produce
+        // the input is handled below and takes precedence, since the worker 
may have stopped
+        // responding because of it.
+        writer.exception.foreach(e.addSuppressed)

Review Comment:
   Done. The writer's error is added only if it is not among the suppressed 
ones yet, and the test handles the same exception twice.



##########
core/src/test/scala/org/apache/spark/api/python/BasePythonRunnerSuite.scala:
##########
@@ -1108,7 +1111,284 @@ 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 that has no input and 
writes nothing to
+   * `worker`.
+   */
+  private def withRunnerAndWriter(worker: PythonWorker, context: TaskContext)(

Review Comment:
   Done. `withRunnerAndWriter` takes `writeNextInput`, and 
`withPipelinedWriterRunnable` builds its runner and writer through it.



-- 
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