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


##########
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:
   **[1] The same masking still applies to a UDF exception or a worker crash in 
pipelined mode.**
   
   This case gives the reader's error precedence only when it is a 
`PythonWorkerException`. In pipelined mode, a UDF that raises on its first row 
while the writer is blocked in `flushToSocket` hits the same race: `worker.py` 
writes `PYTHON_EXCEPTION_THROWN` and exits with `sys.exit(-1)` without draining 
the remaining input, so the writer fails with `Broken pipe` and records it with 
`whileWritingToWorker = true`. The reader's `PythonException` then falls into 
`case _`, and the task fails with `java.io.IOException: Broken pipe` instead of 
the Python traceback. A worker crash (EOF / connection reset) is masked the 
same way.
   
   Since `failedWritingToWorker` already means that the writer failed only 
because the worker went away, keying this case on the flag alone (`case e if 
writer.failedWritingToWorker`) would cover all of them: report the reader's 
failure (the traceback, or the existing crash message with the diagnostics for 
EOF / `IOException`) and attach the writer's as suppressed. This is not 
specific to the idle timeout, so a follow-up is fine too.



##########
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:
   **[2] The early `writer.exception` checks bypass this precedence.**
   
   `handleInitResponse` (L1355) and the `read()` of each reader (L1950 here, 
`PythonUDFRunner` L125, `PythonArrowOutput` L108) start with `if 
(writer.exception.isDefined) throw writer.exception.get`. At the top level this 
throw is outside the `try`, so it does not reach `handleException` at all. In a 
nested `read()` (e.g. `PythonArrowOutput` at the end of a stream), it reaches 
`handleException` with `e` being the writer's exception itself, which goes to 
`case _`. Either way, the raw writer failure is reported.
   
   For example, `readBlocking` gets a `SocketTimeoutException`, `onIdleTimeout` 
kills the worker, and the retried read still returns the output of a slow UDF 
that arrived just before the kill, so the reader returns a batch normally. 
Meanwhile, the writer records `Broken pipe` because of the kill, and the next 
`read()` throws that `IOException` from the early check, which is the symptom 
that this PR fixes. It may be worth applying the same precedence to these 
checks as well.



##########
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:
   **[5] No test runs the real pipelined path that this PR fixes.**
   
   This test covers the precedence with a hand-built `TestReaderIterator` and a 
direct `setException` call, and the next test covers the flag in 
`flushToSocket` separately. Nothing runs them together: a 
`PipelinedWriterRunnable` blocked in `flushToSocket`, the kill from 
`readBlocking`, and `handleException`. On the Python side, 
`test_udf_kill_on_idle_timeout` in `test_pipelined_udf.py` uses 
`spark.range(1)` ("All input has been sent to the worker by the time it is 
killed"), and `test_udf_exception_propagation` uses `spark.range(10)`. So the 
`Broken pipe` path never runs in CI, and the only verification is the manual 
`spark.range(0, 50000000)` run in the PR description. A pipelined variant with 
more input than the socket buffers hold would catch a regression in the wiring 
of `createPipelinedDataIn` or of the flag.



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -1532,7 +1621,7 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
       while (n == 0) {
         idleTimeoutHandler.select(hasInput || buffer.hasRemaining)
         if (worker.selectionKey.isReadable) {
-          n = worker.channel.read(buf)
+          n = idleTimeoutHandler.read(buf)

Review Comment:
   **[4] A failed write right after a successful read drops the bytes just 
read.**
   
   In one iteration, this loop reads (`n > 0`) and then writes if the key is 
writable. If that write fails, the exception propagates and the bytes just read 
into `buf` are lost. Since `selectedKeys` is never cleared, the ready set of 
the key accumulates, so `isWritable` stays `true` once it has been set, and 
this path is easy to hit.
   
   For example, in non-pipelined mode a UDF writes `PYTHON_EXCEPTION_THROWN` 
and exits, and its connection is reset because of unread input. The read gets 
the exception bytes, the write in the same iteration fails with `Broken pipe`, 
and the task reports `Python worker exited unexpectedly (crashed)` (or the idle 
timeout, after a kill) instead of the Python traceback. This was the same 
before this PR and is timing-dependent, but this PR touches these lines. Not 
letting a write failure discard `n > 0` (e.g. returning `n` and surfacing the 
failure on the next call) would avoid it. `PythonPlannerRunner` L218-L225 has 
the same shape.



##########
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:
   **[8] nit: Placement of `withRunnerAndWriter`.**
   
   It was extracted from `withPipelinedWriterRunnable` (L547), which also uses 
it, but it sits in the middle of the idle timeout tests. Since a change to the 
`Writer` constructor or its abstract members needs both helpers to change 
together, keeping it next to `withPipelinedWriterRunnable` would make that 
easier to see. Feel free to ignore this if you prefer it next to the idle 
timeout tests that use it.



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -1743,7 +1834,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] Follow-up for the `open()` failure.**
   
   As discussed in 
https://github.com/apache/spark/pull/60540#discussion_r4591856971, `run()` 
still goes on after `writer.open(dataOut)` (L1806) recorded a failure in 
`_exception`, and the `ClosedChannelException` of the next `flushToSocket` that 
has data replaces it here. So the root cause (e.g. from `writeBroadcasts` or 
`writeCommand`) is lost. I agree that it can be fixed separately. Could you 
file a JIRA for it and link it here so that it is tracked? Returning right 
after `open` when `writer.exception` is set looks enough.



##########
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:
   **[7] nit: The default value of `whileWritingToWorker` is not used.**
   
   The only production caller (L1837) and the tests all pass it explicitly. 
With the default, a future caller that forgets the flag still compiles, and a 
failed write to the socket is then silently classified as a failure to produce 
the input. Dropping the default makes every caller decide.



##########
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:
   **[6] nit: The "this side closed the channel" check is duplicated.**
   
   `!e.isInstanceOf[ClosedChannelException]` here and in 
`IdleTimeoutHandler.causedByKill` (L769) decide the same thing, and they are 
linked only by comments. If one of them changes (e.g. how 
`AsynchronousCloseException` is treated), the reader's kill attribution and the 
writer's `failedWritingToWorker` disagree, and `handleException` picks the 
wrong error. A small shared helper, e.g. `BasePythonRunner.isFailureOfPeer(e: 
IOException)`, used in both places would keep them in sync.



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