dongjoon-hyun commented on code in PR #60540:
URL: https://github.com/apache/spark/pull/60540#discussion_r4591856947


##########
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:
   **[1] The writer's error can still win if it is recorded between the two 
case guards.**
   
   `handleException` reads the state of the writer twice, in two case guards: 
`writer.failedWritingToWorker` here, and then `writer.exception.isDefined` in 
the next case (L1465). In the motivating case, both threads fail on the same 
reset after the kill. If the writer runs `setException` between the two reads, 
this guard sees `false`, the next one sees the exception, and the task fails 
with the writer's `Broken pipe` again, logged as "Python worker exited 
unexpectedly (crashed)". The order in `setException` (L1110) does not help 
here, since this case reads the flag before the exception.
   
   The window is only between the two guards, so it is much rarer than before. 
It could be closed by checking the flag only after seeing the exception, in one 
case, e.g.:
   
   ```scala
   case e: Exception if writer.exception.isDefined =>
     e match {
       case pwe: PythonWorkerException if writer.failedWritingToWorker =>
         writer.exception.foreach(pwe.addSuppressed)
         throw pwe
       case _ =>
         // the current logging
         throw writer.exception.get
     }
   ```
   
   Then a reader that sees the exception also sees the flag, which is what the 
comment at L1110 relies on.
   



##########
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:
   **[5] nit: `withRunnerAndWriter` repeats the setup of 
`withPipelinedWriterRunnable`.**
   
   Both build the same `SimplePythonFunction` and `PythonRunner`, and an 
anonymous `runner.Writer` with the same no-op `open`, `writeCommand` and 
`close` (L551-L571), and differ only in `writeNextInputToStream`. A 
`writeNextInput: DataOutputStream => Boolean = _ => false` parameter here would 
let `withPipelinedWriterRunnable` build its runner and writer through this 
helper, so that a change to the constructor or the abstract members of `Writer` 
is made in one place.
   



##########
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:
   **[3] A failure in `open()` is replaced by the failure of the next write.**
   
   This was the same before this PR, but the new flag now also marks it as a 
failed write to the worker. In pipelined mode, `open()` writes to 
`bufferStream`, and when it fails (e.g. in `writeBroadcasts` or 
`writeCommand`), it stores the error in `_exception`, shuts down the socket 
output (L1256-L1259), and returns normally. `run()` then goes on, and the next 
`flushToSocket`, after up to one buffer of input has been read, writes to the 
shut-down output and throws a `ClosedChannelException`. That reaches this 
`setException` with `whileWritingToWorker = true` and replaces the error from 
`open()`, so the reader rethrows the `ClosedChannelException` and the actual 
cause is lost. Would returning right after `writer.open(dataOut)` when 
`writer.exception` is set keep the cause? Fine to leave for a separate change.
   



##########
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:
   **[4] nit: a nested `read()` adds the error of the writer as suppressed more 
than once.**
   
   `PythonArrowOutput.read()` calls `read()` again inside its `try` (L123, 
L142, L145), and each level ends with `catch handleException` (L153). If the 
kill happens in a nested call, e.g. while waiting for the next control data 
after an Arrow stream ended (L122-L123), the same `PythonWorkerException` 
passes through this case once per level, and `addSuppressed` does not skip an 
exception that is already there. The task error then lists the writer's `Broken 
pipe` as suppressed twice or more. Adding it only when `e.getSuppressed` does 
not contain it yet would avoid that.
   



##########
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:
   **[2] nit: `failedInSocketWrite` is also set for a `ClosedChannelException` 
from this side.**
   
   `causedByKill` (L768) now leaves out the `ClosedChannelException` family, 
since it means that this side closed the channel or shut down its output, not 
that the worker went away. This catch sets the flag for any `IOException`, 
including those. So a write that fails because this side shut down the output, 
e.g. after `open()` failed as in [3], is recorded as a failed write to the 
worker, which the doc of `failedWritingToWorker` (L1096-L1097) contrasts with 
"a failure to produce the input". The kill destroys the process and does not 
close `worker.channel`, so the failure of the writer caused by the kill is 
still a plain `IOException`, and `ClosedByInterruptException` is matched in 
`run()` before `setException`. Would `case e: IOException if 
!e.isInstanceOf[ClosedChannelException]` keep the two consistent?
   



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