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


##########
python/pyspark/sql/tests/pandas/test_pipelined_udf.py:
##########
@@ -250,6 +251,32 @@ def bad_udf(x: pd.Series) -> pd.Series:
         with self.assertRaisesRegex(Exception, "intentional error"):
             self.spark.range(10).select(bad_udf(col("id"))).collect()
 
+    def test_udf_kill_on_idle_timeout(self):
+        """A worker that produces no output within the idle timeout is 
killed."""
+        uds_enabled = self.spark.conf.get(
+            "spark.python.unix.domain.socket.enabled", 
os.environ.get("PYSPARK_UDS_MODE", "false")
+        )
+        if uds_enabled.lower() == "true":
+            self.skipTest("Pipelined mode has no idle timeout over Unix domain 
sockets.")
+
+        with self.sql_conf(
+            {
+                "spark.sql.execution.pyspark.udf.idleTimeoutSeconds": "1s",
+                "spark.sql.execution.pyspark.udf.killOnIdleTimeout": "true",
+            }
+        ):
+
+            @pandas_udf(LongType())
+            def slow_udf(x: pd.Series) -> pd.Series:
+                time.sleep(30)
+                return x
+
+            with self.assertRaisesRegex(
+                Exception,
+                "Python worker process terminated due to idle timeout 
\\(timeout: 1 seconds\\)",
+            ):
+                self.spark.range(1).select(slow_udf(col("id"))).collect()

Review Comment:
   **[1] This test may fail with a cold worker, and it covers only a kill after 
all input was sent.**
   
   The 1 s idle timeout also runs while the worker initializes, and the JVM 
receives nothing from the worker until it has loaded the UDF 
(`report_init_response`). A worker that has not run a pandas UDF yet imports 
pandas and pyarrow during that step. If that takes longer than 1 s, which can 
happen when this test runs on its own or on a busy machine, the worker is 
killed before it has read its input. On Linux, closing a socket with unread 
data sends a reset, so the next read in `doRead` throws an `IOException` 
(connection reset) instead of returning -1. `throwIfKilled` is then never 
reached, the query fails with "Python worker exited unexpectedly (crashed)", 
and `assertRaisesRegex` fails. Within this class the earlier tests usually 
leave a warm worker to reuse, which hides it. A larger timeout, e.g. `3s`, 
together with the 30 s sleep would leave much more room.
   
   Also, with `range(1)` the writer thread has finished before the timeout. 
With more input than the socket buffers hold, the writer is still blocked when 
the worker is killed and fails too, and `handleException` then rethrows 
`writer.exception` (`PythonRunner.scala:1375`), so that case reports the 
writer's error rather than the idle timeout. That was the same before this PR, 
but it may be worth saying in the docstring that the test covers the case where 
all input was sent.



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -592,6 +592,116 @@ private[spark] object BasePythonRunner extends Logging {
       } else log"") +
     log"hasInputs = ${MDC(LogKeys.PYTHON_WORKER_HAS_INPUTS, hasInputs)}"
   }
+
+  /**
+   * Handles the idle timeout of a Python worker on behalf of one stream that 
reads from it:
+   * logs every timeout, kills the worker on the first one if 
`killOnIdleTimeout` is set, and
+   * fails the read once the killed worker has closed the connection.
+   *
+   * The caller decides how a timeout is detected. Streams that wait on the 
worker's selector
+   * use `select`; a stream that relies on the socket read timeout calls 
`onIdleTimeout` when
+   * the read times out. Either way, the stream passes the result of each read 
to
+   * `throwIfKilled`.
+   *
+   * This class is not thread-safe. Use an instance only from the thread that 
reads from the
+   * worker.
+   *
+   * @param context the task that reads from the worker, or None on the 
driver. It is only used
+   *                to identify the task in the log messages.
+   * @param loggerName the name of the logger to use, so that the messages 
stay under the logger
+   *                   of the runner that owns the stream.
+   * @param workerName how the log messages refer to the worker.
+   */
+  private[spark] class IdleTimeoutHandler(
+      worker: PythonWorker,
+      handle: Option[PythonWorkerHandle],
+      idleTimeoutSeconds: Long,
+      killOnIdleTimeout: Boolean,
+      context: Option[TaskContext],
+      loggerName: String,
+      workerName: String = "Python worker") extends Logging {
+
+    private[this] val idleTimeoutMillis: Long = 
TimeUnit.SECONDS.toMillis(idleTimeoutSeconds)
+    private[this] val workerNameMessage =
+      MessageWithContext(workerName, java.util.Collections.emptyMap[String, 
String]())
+    private[this] var pythonWorkerKilled: Boolean = false
+
+    override protected def logName: String = loggerName
+
+    /**
+     * Waits on the selector of the worker for at most the idle timeout, or 
without a limit if
+     * there is no idle timeout, and handles the idle timeout if the wait ran 
into it.
+     *
+     * @param hasInputs whether there is still input to send to the worker, 
for the log message.
+     */
+    def select(hasInputs: => Boolean): Unit = {

Review Comment:
   **[4] nit: `hasInputs` could be a plain `Boolean`.**
   
   With a by-name parameter, each call at L1525 and 
`PythonPlannerRunner.scala:220` allocates a closure over the stream, once per 
`read`. The value cannot change between the call and its use after the selector 
wait, since only the reading thread changes `hasInput` and `buffer`, so a 
strict `Boolean` gives the same message without the allocation. The same 
applies to `onIdleTimeout` (L654).



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -592,6 +592,116 @@ private[spark] object BasePythonRunner extends Logging {
       } else log"") +
     log"hasInputs = ${MDC(LogKeys.PYTHON_WORKER_HAS_INPUTS, hasInputs)}"
   }
+
+  /**
+   * Handles the idle timeout of a Python worker on behalf of one stream that 
reads from it:
+   * logs every timeout, kills the worker on the first one if 
`killOnIdleTimeout` is set, and
+   * fails the read once the killed worker has closed the connection.
+   *
+   * The caller decides how a timeout is detected. Streams that wait on the 
worker's selector
+   * use `select`; a stream that relies on the socket read timeout calls 
`onIdleTimeout` when
+   * the read times out. Either way, the stream passes the result of each read 
to
+   * `throwIfKilled`.
+   *
+   * This class is not thread-safe. Use an instance only from the thread that 
reads from the
+   * worker.
+   *
+   * @param context the task that reads from the worker, or None on the 
driver. It is only used
+   *                to identify the task in the log messages.
+   * @param loggerName the name of the logger to use, so that the messages 
stay under the logger
+   *                   of the runner that owns the stream.
+   * @param workerName how the log messages refer to the worker.
+   */
+  private[spark] class IdleTimeoutHandler(
+      worker: PythonWorker,
+      handle: Option[PythonWorkerHandle],
+      idleTimeoutSeconds: Long,
+      killOnIdleTimeout: Boolean,
+      context: Option[TaskContext],
+      loggerName: String,
+      workerName: String = "Python worker") extends Logging {
+
+    private[this] val idleTimeoutMillis: Long = 
TimeUnit.SECONDS.toMillis(idleTimeoutSeconds)
+    private[this] val workerNameMessage =
+      MessageWithContext(workerName, java.util.Collections.emptyMap[String, 
String]())
+    private[this] var pythonWorkerKilled: Boolean = false
+
+    override protected def logName: String = loggerName
+
+    /**
+     * Waits on the selector of the worker for at most the idle timeout, or 
without a limit if
+     * there is no idle timeout, and handles the idle timeout if the wait ran 
into it.
+     *
+     * @param hasInputs whether there is still input to send to the worker, 
for the log message.
+     */
+    def select(hasInputs: => Boolean): Unit = {
+      val start = System.currentTimeMillis()
+      val selected = worker.selector.select(idleTimeoutMillis)
+      val end = System.currentTimeMillis()
+      if (selected == 0
+        // Avoid logging if no timeout or the selector doesn't wait for the 
idle timeout
+        // as it can return 0 in some case.
+        && idleTimeoutMillis > 0 && (end - start) >= idleTimeoutMillis) {
+        onIdleTimeout(hasInputs)
+      }
+    }
+
+    /**
+     * Called when no data arrived from the worker within the idle timeout.
+     *
+     * @param hasInputs whether there is still input to send to the worker, 
for the log message.
+     */
+    def onIdleTimeout(hasInputs: => Boolean): Unit = {
+      if (pythonWorkerKilled) {
+        logWarning(
+          log"Waiting for " + workerNameMessage +
+          log" process to terminate after idle timeout: " +
+          pythonWorkerStatusMessageWithContext(handle, worker, hasInputs))
+      } else {
+        logWarning(
+          log"Idle timeout reached for " + workerNameMessage + log" (timeout: 
" +
+          log"${MDC(PYTHON_WORKER_IDLE_TIMEOUT, idleTimeoutSeconds)} seconds). 
" +
+          log"No data received from the worker process" +
+          (context match {
+            case Some(c) =>
+              log" - " + pythonWorkerStatusMessageWithContext(handle, worker, 
hasInputs) +
+              log" - ${MDC(TASK_NAME, taskIdentifier(c))}"
+            case None =>
+              log": " + pythonWorkerStatusMessageWithContext(handle, worker, 
hasInputs)
+          }))
+        if (killOnIdleTimeout) {
+          handle.foreach { handle =>
+            if (handle.isAlive()) {
+              logWarning(
+                log"Terminating " + workerNameMessage +
+                log" process due to idle timeout (timeout: " +
+                log"${MDC(PYTHON_WORKER_IDLE_TIMEOUT, idleTimeoutSeconds)} 
seconds)" +
+                (context match {
+                  case Some(c) => log" - ${MDC(TASK_NAME, taskIdentifier(c))}"
+                  case None => log""
+                }))
+              pythonWorkerKilled = handle.destroy()
+            }
+          }
+        }
+      }
+    }
+
+    /**
+     * 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.
+     */
+    def throwIfKilled(n: Int): Unit = {

Review Comment:
   **[2] `throwIfKilled` sees only what the read returned, so the read itself 
stays in each stream.**
   
   Each stream still runs its own read and has to call `throwIfKilled` after 
it, and the handler cannot see a read that throws. For example, if the killed 
worker resets the connection, the read fails with an `IOException` and the 
end-of-stream check never runs, in all three streams. That was the same before 
this PR, so it is not a regression. But since the point of the handler is that 
such a change lands in one place, would it be worth letting the handler run the 
read, e.g. `def read(op: () => Int): Int`? For the pipelined stream it would 
also take over the `SocketTimeoutException` loop of `doRead` (L974-L988), and 
the selector streams could wrap their `worker.channel.read(buf)` the same way. 
Fine to leave for a separate change.



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -592,6 +592,116 @@ private[spark] object BasePythonRunner extends Logging {
       } else log"") +
     log"hasInputs = ${MDC(LogKeys.PYTHON_WORKER_HAS_INPUTS, hasInputs)}"
   }
+
+  /**
+   * Handles the idle timeout of a Python worker on behalf of one stream that 
reads from it:
+   * logs every timeout, kills the worker on the first one if 
`killOnIdleTimeout` is set, and
+   * fails the read once the killed worker has closed the connection.
+   *
+   * The caller decides how a timeout is detected. Streams that wait on the 
worker's selector
+   * use `select`; a stream that relies on the socket read timeout calls 
`onIdleTimeout` when
+   * the read times out. Either way, the stream passes the result of each read 
to
+   * `throwIfKilled`.
+   *
+   * This class is not thread-safe. Use an instance only from the thread that 
reads from the
+   * worker.
+   *
+   * @param context the task that reads from the worker, or None on the 
driver. It is only used
+   *                to identify the task in the log messages.
+   * @param loggerName the name of the logger to use, so that the messages 
stay under the logger
+   *                   of the runner that owns the stream.
+   * @param workerName how the log messages refer to the worker.
+   */
+  private[spark] class IdleTimeoutHandler(
+      worker: PythonWorker,
+      handle: Option[PythonWorkerHandle],
+      idleTimeoutSeconds: Long,
+      killOnIdleTimeout: Boolean,
+      context: Option[TaskContext],
+      loggerName: String,
+      workerName: String = "Python worker") extends Logging {
+
+    private[this] val idleTimeoutMillis: Long = 
TimeUnit.SECONDS.toMillis(idleTimeoutSeconds)
+    private[this] val workerNameMessage =
+      MessageWithContext(workerName, java.util.Collections.emptyMap[String, 
String]())
+    private[this] var pythonWorkerKilled: Boolean = false
+
+    override protected def logName: String = loggerName
+
+    /**
+     * Waits on the selector of the worker for at most the idle timeout, or 
without a limit if
+     * there is no idle timeout, and handles the idle timeout if the wait ran 
into it.
+     *
+     * @param hasInputs whether there is still input to send to the worker, 
for the log message.
+     */
+    def select(hasInputs: => Boolean): Unit = {
+      val start = System.currentTimeMillis()
+      val selected = worker.selector.select(idleTimeoutMillis)
+      val end = System.currentTimeMillis()
+      if (selected == 0
+        // Avoid logging if no timeout or the selector doesn't wait for the 
idle timeout
+        // as it can return 0 in some case.
+        && idleTimeoutMillis > 0 && (end - start) >= idleTimeoutMillis) {
+        onIdleTimeout(hasInputs)
+      }
+    }
+
+    /**
+     * Called when no data arrived from the worker within the idle timeout.
+     *
+     * @param hasInputs whether there is still input to send to the worker, 
for the log message.
+     */
+    def onIdleTimeout(hasInputs: => Boolean): Unit = {
+      if (pythonWorkerKilled) {
+        logWarning(
+          log"Waiting for " + workerNameMessage +
+          log" process to terminate after idle timeout: " +
+          pythonWorkerStatusMessageWithContext(handle, worker, hasInputs))
+      } else {
+        logWarning(
+          log"Idle timeout reached for " + workerNameMessage + log" (timeout: 
" +
+          log"${MDC(PYTHON_WORKER_IDLE_TIMEOUT, idleTimeoutSeconds)} seconds). 
" +
+          log"No data received from the worker process" +
+          (context match {

Review Comment:
   **[3] nit: `context` also picks the separator of the status in the log 
message.**
   
   `context` decides both whether the task is named and whether the status 
follows ` - ` or `: ` (L666-L670), while its doc says it is "only used to 
identify the task in the log messages" (L609-L610). If a later caller passes a 
context to the planner runner, or `None` on an executor path, its message 
format changes as a side effect. Could the doc mention it, or could the 
separator be a parameter of its own?



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -592,6 +592,116 @@ private[spark] object BasePythonRunner extends Logging {
       } else log"") +
     log"hasInputs = ${MDC(LogKeys.PYTHON_WORKER_HAS_INPUTS, hasInputs)}"
   }
+
+  /**
+   * Handles the idle timeout of a Python worker on behalf of one stream that 
reads from it:
+   * logs every timeout, kills the worker on the first one if 
`killOnIdleTimeout` is set, and

Review Comment:
   **[6] nit: the kill is not limited to the first timeout.**
   
   "kills the worker on the first one if `killOnIdleTimeout` is set" holds only 
when `destroy()` issues a termination request. When it returns false, every 
later timeout tries again and logs "Terminating ..." again (L683), which the 
new test "idle timeout reported by a blocking read, as in pipelined mode" 
checks. Maybe: "kills the worker if `killOnIdleTimeout` is set, trying again on 
later timeouts until a termination request has been issued".



##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -592,6 +592,116 @@ private[spark] object BasePythonRunner extends Logging {
       } else log"") +
     log"hasInputs = ${MDC(LogKeys.PYTHON_WORKER_HAS_INPUTS, hasInputs)}"
   }
+
+  /**
+   * Handles the idle timeout of a Python worker on behalf of one stream that 
reads from it:
+   * logs every timeout, kills the worker on the first one if 
`killOnIdleTimeout` is set, and
+   * fails the read once the killed worker has closed the connection.
+   *
+   * The caller decides how a timeout is detected. Streams that wait on the 
worker's selector
+   * use `select`; a stream that relies on the socket read timeout calls 
`onIdleTimeout` when
+   * the read times out. Either way, the stream passes the result of each read 
to
+   * `throwIfKilled`.
+   *
+   * This class is not thread-safe. Use an instance only from the thread that 
reads from the
+   * worker.
+   *
+   * @param context the task that reads from the worker, or None on the 
driver. It is only used
+   *                to identify the task in the log messages.
+   * @param loggerName the name of the logger to use, so that the messages 
stay under the logger
+   *                   of the runner that owns the stream.
+   * @param workerName how the log messages refer to the worker.
+   */
+  private[spark] class IdleTimeoutHandler(
+      worker: PythonWorker,
+      handle: Option[PythonWorkerHandle],
+      idleTimeoutSeconds: Long,
+      killOnIdleTimeout: Boolean,
+      context: Option[TaskContext],
+      loggerName: String,
+      workerName: String = "Python worker") extends Logging {
+
+    private[this] val idleTimeoutMillis: Long = 
TimeUnit.SECONDS.toMillis(idleTimeoutSeconds)
+    private[this] val workerNameMessage =
+      MessageWithContext(workerName, java.util.Collections.emptyMap[String, 
String]())
+    private[this] var pythonWorkerKilled: Boolean = false
+
+    override protected def logName: String = loggerName
+
+    /**
+     * Waits on the selector of the worker for at most the idle timeout, or 
without a limit if
+     * there is no idle timeout, and handles the idle timeout if the wait ran 
into it.
+     *
+     * @param hasInputs whether there is still input to send to the worker, 
for the log message.
+     */
+    def select(hasInputs: => Boolean): Unit = {
+      val start = System.currentTimeMillis()
+      val selected = worker.selector.select(idleTimeoutMillis)
+      val end = System.currentTimeMillis()
+      if (selected == 0
+        // Avoid logging if no timeout or the selector doesn't wait for the 
idle timeout
+        // as it can return 0 in some case.
+        && idleTimeoutMillis > 0 && (end - start) >= idleTimeoutMillis) {
+        onIdleTimeout(hasInputs)
+      }
+    }
+
+    /**
+     * Called when no data arrived from the worker within the idle timeout.
+     *
+     * @param hasInputs whether there is still input to send to the worker, 
for the log message.
+     */
+    def onIdleTimeout(hasInputs: => Boolean): Unit = {
+      if (pythonWorkerKilled) {
+        logWarning(
+          log"Waiting for " + workerNameMessage +
+          log" process to terminate after idle timeout: " +
+          pythonWorkerStatusMessageWithContext(handle, worker, hasInputs))
+      } else {
+        logWarning(
+          log"Idle timeout reached for " + workerNameMessage + log" (timeout: 
" +
+          log"${MDC(PYTHON_WORKER_IDLE_TIMEOUT, idleTimeoutSeconds)} seconds). 
" +
+          log"No data received from the worker process" +
+          (context match {
+            case Some(c) =>
+              log" - " + pythonWorkerStatusMessageWithContext(handle, worker, 
hasInputs) +
+              log" - ${MDC(TASK_NAME, taskIdentifier(c))}"
+            case None =>
+              log": " + pythonWorkerStatusMessageWithContext(handle, worker, 
hasInputs)
+          }))
+        if (killOnIdleTimeout) {
+          handle.foreach { handle =>
+            if (handle.isAlive()) {
+              logWarning(
+                log"Terminating " + workerNameMessage +
+                log" process due to idle timeout (timeout: " +
+                log"${MDC(PYTHON_WORKER_IDLE_TIMEOUT, idleTimeoutSeconds)} 
seconds)" +
+                (context match {
+                  case Some(c) => log" - ${MDC(TASK_NAME, taskIdentifier(c))}"
+                  case None => log""
+                }))
+              pythonWorkerKilled = handle.destroy()
+            }
+          }
+        }
+      }
+    }
+
+    /**
+     * 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.
+     */
+    def throwIfKilled(n: Int): Unit = {
+      if (n == -1 && pythonWorkerKilled) {
+        val base = "Python worker process terminated due to idle timeout " +
+          s"(timeout: $idleTimeoutSeconds seconds)"
+        val msg = handle.flatMap(_.terminationDiagnostics())

Review Comment:
   **[5] nit: the diagnostics suffix is still built the same way in two other 
places.**
   
   `handle.flatMap(_.terminationDiagnostics()).map(error => s"$base: 
$error").getOrElse(base)` is also in `BasePythonRunner.handleException` 
(`PythonRunner.scala:1392`) and in the `IOException` handler of 
`PythonPlannerRunner.runInPython` (`PythonPlannerRunner.scala:169`). Since the 
motivation is that a fix had to be repeated by hand in each copy, a small 
shared helper next to `IdleTimeoutHandler` could serve all three.



##########
core/src/test/scala/org/apache/spark/api/python/BasePythonRunnerSuite.scala:
##########
@@ -883,4 +883,211 @@ class BasePythonRunnerSuite extends SparkFunSuite with 
SharedSparkContext {
       }
     }
   }
+
+  /** A worker handle that records how often it was asked to terminate the 
worker. */
+  private class RecordingWorkerHandle(
+      destroyIssued: Boolean = true,
+      diagnostics: Option[String] = None) extends PythonWorkerHandle {
+    val destroyCalls = new AtomicInteger(0)
+    override def isAlive(): Boolean = true
+    override def destroy(): Boolean = {
+      destroyCalls.incrementAndGet()
+      destroyIssued
+    }
+    override def terminationDiagnostics(): Option[String] = diagnostics
+  }
+
+  /**
+   * Runs `f` with a worker whose channel is one end of a loopback connection, 
and with the
+   * other end. With `blocking`, the worker is set up like in pipelined mode, 
without a selector.
+   * Otherwise the worker only waits for output, like a worker whose input was 
sent completely.
+   */
+  private def withIdleWorker(blocking: Boolean)(f: (PythonWorker, 
SocketChannel) => Unit): Unit = {
+    val server = ServerSocketChannel.open()
+    server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress, 0))
+    val client = SocketChannel.open(server.getLocalAddress)
+    val accepted = server.accept()
+    client.configureBlocking(blocking)
+    val worker = PythonWorker(client).refresh()
+    try {
+      if (!blocking) {
+        worker.selectionKey.interestOps(SelectionKey.OP_READ)
+      }
+      f(worker, accepted)
+    } finally {
+      worker.stop()
+      accepted.close()
+      server.close()
+    }
+  }
+
+  private val idleTimeoutLoggerName = 
"org.apache.spark.api.python.IdleTimeoutTestRunner"
+
+  /** Runs `f` and returns the warnings logged under `idleTimeoutLoggerName`. 
*/
+  private def idleTimeoutWarnings(f: => Unit): Seq[String] = {
+    val logAppender = new LogAppender("idle timeout")
+    withLogAppender(logAppender, loggerNames = Seq(idleTimeoutLoggerName)) {
+      f
+    }
+    logAppender.loggingEvents.toSeq.map { event =>
+      assert(event.getLevel === Level.WARN)
+      assert(event.getLoggerName === idleTimeoutLoggerName)
+      event.getMessage.getFormattedMessage
+    }
+  }
+
+  private val nonBlockingWorkerStatus = "handle.map(_.isAlive) = Some(true), " 
+
+    "channel.isConnected = true, channel.isBlocking = false, selector.isOpen = 
true, " +
+    "selectionKey.isValid = true, selectionKey.interestOps = 1, "
+
+  test("idle timeout on the selector kills the worker once and fails the read 
at the end " +
+      "of the stream") {
+    withIdleWorker(blocking = false) { (worker, _) =>
+      val handle = new RecordingWorkerHandle(diagnostics = Some("worker 
stack"))
+      val handler = new BasePythonRunner.IdleTimeoutHandler(
+        worker, Some(handle), idleTimeoutSeconds = 1, killOnIdleTimeout = true,
+        Some(TaskContext.empty()), idleTimeoutLoggerName)
+      val task = "task 0.0 in stage 0 (TID 0)"
+
+      val firstTimeout = idleTimeoutWarnings {
+        handler.select(hasInputs = false)
+      }
+      assert(firstTimeout === Seq(
+        "Idle timeout reached for Python worker (timeout: 1 seconds). " +
+          "No data received from the worker process - " + 
nonBlockingWorkerStatus +
+          s"hasInputs = false - $task",
+        s"Terminating Python worker process due to idle timeout (timeout: 1 
seconds) - $task"))
+      assert(handle.destroyCalls.get() === 1)
+
+      // Until the worker closes the connection, later timeouts are only 
logged.
+      val secondTimeout = idleTimeoutWarnings {
+        handler.select(hasInputs = true)
+      }
+      assert(secondTimeout === Seq(
+        "Waiting for Python worker process to terminate after idle timeout: " +
+          nonBlockingWorkerStatus + "hasInputs = true"))
+      assert(handle.destroyCalls.get() === 1)
+
+      // Only the end of the stream fails the read.
+      handler.throwIfKilled(0)
+      handler.throwIfKilled(16)
+      val e = intercept[PythonWorkerException] {
+        handler.throwIfKilled(-1)
+      }
+      assert(e.getMessage ===
+        "Python worker process terminated due to idle timeout (timeout: 1 
seconds): worker stack")
+    }
+  }
+
+  test("idle timeout on the selector is not handled when the worker has output 
or when " +
+      "there is no idle timeout") {
+    withIdleWorker(blocking = false) { (worker, peer) =>
+      val handle = new RecordingWorkerHandle()
+      val warnings = idleTimeoutWarnings {
+        peer.write(ByteBuffer.wrap(new Array[Byte](1)))
+        new BasePythonRunner.IdleTimeoutHandler(
+          worker, Some(handle), idleTimeoutSeconds = 1, killOnIdleTimeout = 
true,
+          Some(TaskContext.empty()), idleTimeoutLoggerName).select(hasInputs = 
false)
+        assert(worker.selectionKey.isReadable)
+        // Without an idle timeout the wait has no limit, so the pending 
output ends it.
+        val noTimeoutHandler = new BasePythonRunner.IdleTimeoutHandler(
+          worker, Some(handle), idleTimeoutSeconds = 0, killOnIdleTimeout = 
true,
+          Some(TaskContext.empty()), idleTimeoutLoggerName)
+        noTimeoutHandler.select(hasInputs = false)
+        noTimeoutHandler.throwIfKilled(-1)
+      }
+      assert(warnings.isEmpty)
+      assert(handle.destroyCalls.get() === 0)
+    }
+  }
+
+  test("idle timeout without killOnIdleTimeout only logs, without a task and 
with another " +
+      "worker name") {
+    withIdleWorker(blocking = false) { (worker, _) =>
+      val handle = new RecordingWorkerHandle()
+      val handler = new BasePythonRunner.IdleTimeoutHandler(
+        worker, Some(handle), idleTimeoutSeconds = 1, killOnIdleTimeout = 
false,
+        None, idleTimeoutLoggerName, workerName = "Python planner worker")
+      val expected = "Idle timeout reached for Python planner worker (timeout: 
1 seconds). " +
+        "No data received from the worker process: " + nonBlockingWorkerStatus 
+
+        "hasInputs = true"
+      // Every timeout is logged the same way, since the worker is never 
killed.
+      assert(idleTimeoutWarnings(handler.select(hasInputs = true)) === 
Seq(expected))
+      assert(idleTimeoutWarnings(handler.select(hasInputs = true)) === 
Seq(expected))

Review Comment:
   **[9] nit: these tests spend about 6 s in real 1 s waits.**
   
   There are six 1 s `select` waits: two in "idle timeout on the selector kills 
the worker once ..." and four in this test. After the first test has covered 
the timing path of `select`, the repeated timeouts check only the state of the 
handler, so they could call `onIdleTimeout` directly, as the blocking test does.



##########
core/src/test/scala/org/apache/spark/api/python/BasePythonRunnerSuite.scala:
##########
@@ -883,4 +883,211 @@ class BasePythonRunnerSuite extends SparkFunSuite with 
SharedSparkContext {
       }
     }
   }
+
+  /** A worker handle that records how often it was asked to terminate the 
worker. */
+  private class RecordingWorkerHandle(
+      destroyIssued: Boolean = true,
+      diagnostics: Option[String] = None) extends PythonWorkerHandle {
+    val destroyCalls = new AtomicInteger(0)
+    override def isAlive(): Boolean = true

Review Comment:
   **[7] nit: the `handle.isAlive()` guard is not covered.**
   
   `isAlive()` here always returns true, so no test checks that a handle whose 
process has already exited is not asked to terminate and does not count as 
killed (`PythonRunner.scala:674`). An `alive: Boolean = true` parameter, like 
`destroyIssued`, would allow one more case in the blocking test.



##########
core/src/test/scala/org/apache/spark/api/python/BasePythonRunnerSuite.scala:
##########
@@ -883,4 +883,211 @@ class BasePythonRunnerSuite extends SparkFunSuite with 
SharedSparkContext {
       }
     }
   }
+
+  /** A worker handle that records how often it was asked to terminate the 
worker. */
+  private class RecordingWorkerHandle(
+      destroyIssued: Boolean = true,
+      diagnostics: Option[String] = None) extends PythonWorkerHandle {
+    val destroyCalls = new AtomicInteger(0)
+    override def isAlive(): Boolean = true
+    override def destroy(): Boolean = {
+      destroyCalls.incrementAndGet()
+      destroyIssued
+    }
+    override def terminationDiagnostics(): Option[String] = diagnostics
+  }
+
+  /**
+   * Runs `f` with a worker whose channel is one end of a loopback connection, 
and with the
+   * other end. With `blocking`, the worker is set up like in pipelined mode, 
without a selector.
+   * Otherwise the worker only waits for output, like a worker whose input was 
sent completely.
+   */
+  private def withIdleWorker(blocking: Boolean)(f: (PythonWorker, 
SocketChannel) => Unit): Unit = {
+    val server = ServerSocketChannel.open()
+    server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress, 0))
+    val client = SocketChannel.open(server.getLocalAddress)
+    val accepted = server.accept()
+    client.configureBlocking(blocking)
+    val worker = PythonWorker(client).refresh()

Review Comment:
   **[8] nit: the sockets leak if the setup fails.**
   
   `server`, `client` and `accepted` are opened, and `configureBlocking` and 
`refresh()` run, before the `try`, so an exception there leaves them open. In 
the `finally`, an exception from `worker.stop()` also skips `accepted.close()` 
and `server.close()`. Opening each one under its own `try`/`finally`, or using 
`Utils.tryWithSafeFinally`, would close them in all cases.



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