viirya commented on code in PR #60507:
URL: https://github.com/apache/spark/pull/60507#discussion_r4575377703
##########
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:
Good point, the timeout also covers the worker initialization. Changed it to
`3s` and noted in the docstring that the test covers a kill after 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 = {
+ 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:
Agreed that the handler cannot see a read that throws. Mapping an
`IOException` after the kill to the idle timeout error would change the
behavior on all three paths, so I would like to keep it out of this refactoring
and do it as 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:
Updated the doc of `context` to describe both formats.
##########
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:
Right, and the closure per read was new in this PR. Changed both methods to
take a plain `Boolean`.
##########
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:
Added `BasePythonRunner.withTerminationDiagnostics` and used it in all three
places.
##########
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:
Updated the doc as suggested.
##########
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:
Added an `alive` parameter and a case for a worker that has already exited.
--
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]