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


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

Review Comment:
   Moved next to `withPipelinedWriterRunnable`.



##########
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:
   Addressed in 3d5aa099e77 with `ReaderIterator.throwIfWriterFailed()`. The 
check still throws for every recorded writer failure and does not read on; it 
only picks the idle timeout error when the writer failed writing to the worker 
and the handler of the pipelined stream has killed the worker.



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -702,16 +704,82 @@ private[spark] object BasePythonRunner extends Logging {
     }
 
     /**
-     * Throws a [[PythonWorkerException]] if `n`, the result of a read from 
the worker, is the
-     * end of the stream and the worker was killed because of the idle timeout.
+     * Reads from the channel of the worker into `buf`, like 
`worker.channel.read(buf)`. Once
+     * the worker has been killed because of the idle timeout, the end of the 
stream and a
+     * failure of the read both throw a [[PythonWorkerException]] for the idle 
timeout: the
+     * connection of a killed worker can be reset instead of closed, for 
example when the worker
+     * had unread input. A failure of the read with no kill is thrown as is.

Review Comment:
   Updated the docs of `read` and `write` to say which failures are attributed 
to the kill.



##########
core/src/test/scala/org/apache/spark/api/python/BasePythonRunnerSuite.scala:
##########
@@ -975,14 +969,15 @@ class BasePythonRunnerSuite extends SparkFunSuite with 
SharedSparkContext {
           nonBlockingWorkerStatus + "hasInputs = true"))
       assert(handle.destroyCalls.get() === 1)
 
-      // Only the end of the stream fails the read.
-      handler.throwIfKilled(0)
-      handler.throwIfKilled(16)
+      // A read that returns data, or no data yet, does not fail; the end of 
the stream does.
+      assert(handler.readBlocking(0) === 0)
+      assert(handler.readBlocking(16) === 16)
       val e = intercept[PythonWorkerException] {
-        handler.throwIfKilled(-1)
+        handler.readBlocking(-1)

Review Comment:
   The selector cases now drive `read(buf)` to the end of the stream, with and 
without a kill.



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