dongjoon-hyun commented on code in PR #60540:
URL: https://github.com/apache/spark/pull/60540#discussion_r4581557643
##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -702,15 +703,53 @@ private[spark] object BasePythonRunner extends Logging {
}
/**
- * Throws a [[PythonWorkerException]] if `n`, the result of a read from
the worker, is the
- * end of the stream and the worker was killed because of the idle timeout.
+ * Runs `op`, which reads from the worker, and returns its result.
+ *
+ * If the read times out, which only a blocking socket with a read timeout
does, the idle
+ * timeout is handled and the read is tried again. Once the worker has
been killed because
+ * of the idle timeout, the end of the stream and a failure of the read
both throw a
+ * [[PythonWorkerException]] for the idle timeout: the connection of a
killed worker can be
+ * reset instead of closed, for example when the worker had unread input.
A failure of the
+ * read with no kill is thrown as is.
*/
- def throwIfKilled(n: Int): Unit = {
+ def read(op: => Int): Int = {
+ var n = 0
+ var done = false
+ while (!done) {
+ try {
+ n = op
+ done = true
+ } catch {
+ case _: SocketTimeoutException =>
+ onIdleTimeout(hasInputs = true)
Review Comment:
**[2] After the kill, a connection that is never closed makes the read wait
forever.**
Once `pythonWorkerKilled` is set, every later `SocketTimeoutException` only
logs "Waiting for ... to terminate after idle timeout" and tries again, even
when `handle.isAlive()` already returns false. If the connection stays open
after the worker has exited, for example because the UDF forked a child process
(e.g. `multiprocessing` with the `fork` start method) that inherited the
socket, neither the end of the stream nor a reset arrives, and the task hangs
until it is killed. The selector streams loop the same way around `select`.
This is the same as before this PR, so it is not a regression. But since
both paths now go through `onIdleTimeout`, it could be the one place to throw
the idle timeout error when a timeout comes after the kill and the handle
reports that the worker is no longer alive. Fine to leave for a separate change.
##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -702,15 +703,53 @@ private[spark] object BasePythonRunner extends Logging {
}
/**
- * Throws a [[PythonWorkerException]] if `n`, the result of a read from
the worker, is the
- * end of the stream and the worker was killed because of the idle timeout.
+ * Runs `op`, which reads from the worker, and returns its result.
+ *
+ * If the read times out, which only a blocking socket with a read timeout
does, the idle
+ * timeout is handled and the read is tried again. Once the worker has
been killed because
+ * of the idle timeout, the end of the stream and a failure of the read
both throw a
+ * [[PythonWorkerException]] for the idle timeout: the connection of a
killed worker can be
+ * reset instead of closed, for example when the worker had unread input.
A failure of the
+ * read with no kill is thrown as is.
*/
- def throwIfKilled(n: Int): Unit = {
+ def read(op: => Int): Int = {
+ var n = 0
+ var done = false
+ while (!done) {
+ try {
+ n = op
+ done = true
+ } catch {
+ case _: SocketTimeoutException =>
+ onIdleTimeout(hasInputs = true)
+ case e: IOException if pythonWorkerKilled =>
Review Comment:
**[3] nit: `IOException` also matches failures that come from the JVM side.**
`ClosedByInterruptException` and `AsynchronousCloseException` are
`IOException`s too (through `ClosedChannelException`). They mean that this side
interrupted the thread or closed the channel, not that the worker reset the
connection. In `BasePythonRunner` that is fine, since `handleException` checks
`context.isInterrupted()` first. `PythonPlannerRunner.runInPython` has no such
check, so if the planning thread is interrupted after the kill, while the
killed worker is still terminating, the error says idle timeout although the
cause is the interrupt. Would `case e: IOException if pythonWorkerKilled &&
!e.isInstanceOf[ClosedChannelException]` keep those as they are? The same
applies to `write` (L744).
##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -973,30 +1012,16 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
// Wrap the socket InputStream to handle idle timeout, matching sync mode
behavior:
// - Log warning on each timeout
- // - If killOnIdleTimeout=true: kill worker, then throw
PythonWorkerException
+ // - If killOnIdleTimeout=true: kill worker, then throw
PythonWorkerException once the
+ // read ends or fails
// - If killOnIdleTimeout=false: log only, retry read (continue waiting)
val idleTimeoutHandler = new IdleTimeoutHandler(
worker, handle, idleTimeoutSeconds, killOnIdleTimeout, Some(context),
logName)
val socketInput = new InputStream {
private val inner = worker.channel.socket().getInputStream
- override def read(): Int = doRead(() => inner.read())
+ override def read(): Int = idleTimeoutHandler.read(inner.read())
override def read(b: Array[Byte], off: Int, len: Int): Int =
- doRead(() => inner.read(b, off, len))
- private def doRead(op: () => Int): Int = {
- var result = 0
- var retry = true
- while (retry) {
- try {
- result = op()
- retry = false
- } catch {
- case _: java.net.SocketTimeoutException =>
- idleTimeoutHandler.onIdleTimeout(hasInputs = true)
- }
- }
- idleTimeoutHandler.throwIfKilled(result)
- result
- }
+ idleTimeoutHandler.read(inner.read(b, off, len))
Review Comment:
**[1] In pipelined mode, the motivating case can still report the writer's
error, depending on timing.**
The PR description lists this under "Not covered", but the example that
motivates the change, a UDF that hangs on its first batch while more input than
the socket buffers hold is still being sent, is exactly the case where the
pipelined writer is still blocked in `flushToSocket` when the worker is killed.
The writer then fails with `Broken pipe` or `Connection reset` and records it
with `writer.setException`, at about the same time as this read fails with the
reset:
- If the writer records its failure first, `handleException` takes `case e:
Exception if writer.exception.isDefined` (L1411). It logs the idle timeout
error as "Python worker exited unexpectedly (crashed)", logs the writer's error
as the prior exception that may have caused it, and rethrows the writer's
`SocketException`.
- If this read reaches `handleException` first, `writer.exception` is still
empty, no case matches the `PythonWorkerException`, and the task fails with the
idle timeout error.
So with `spark.python.udf.pipelined.enabled`, the reported error depends on
which thread records its failure first. In the first order, `killedException`
has also already read and deleted the faulthandler log through
`terminationDiagnostics()`, so its output ends up only in that executor log
line and not in the task failure.
`PythonWorkerException` is only thrown for the idle timeout kill, so could
`handleException` prefer it over a writer that failed with an `IOException`,
e.g. a `case e: PythonWorkerException if
writer.exception.exists(_.isInstanceOf[IOException])` ahead of the writer case
that rethrows `e` with the writer's error added as suppressed? Fine to leave
for a separate change if a JIRA tracks it.
##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -702,15 +703,53 @@ private[spark] object BasePythonRunner extends Logging {
}
/**
- * Throws a [[PythonWorkerException]] if `n`, the result of a read from
the worker, is the
- * end of the stream and the worker was killed because of the idle timeout.
+ * Runs `op`, which reads from the worker, and returns its result.
+ *
+ * If the read times out, which only a blocking socket with a read timeout
does, the idle
+ * timeout is handled and the read is tried again. Once the worker has
been killed because
+ * of the idle timeout, the end of the stream and a failure of the read
both throw a
+ * [[PythonWorkerException]] for the idle timeout: the connection of a
killed worker can be
+ * reset instead of closed, for example when the worker had unread input.
A failure of the
+ * read with no kill is thrown as is.
*/
- def throwIfKilled(n: Int): Unit = {
+ def read(op: => Int): Int = {
+ var n = 0
+ var done = false
+ while (!done) {
+ try {
+ n = op
+ done = true
+ } catch {
+ case _: SocketTimeoutException =>
+ onIdleTimeout(hasInputs = true)
+ case e: IOException if pythonWorkerKilled =>
+ throw killedException(e)
+ }
+ }
if (n == -1 && pythonWorkerKilled) {
- throw new PythonWorkerException(withTerminationDiagnostics(
- "Python worker process terminated due to idle timeout " +
- s"(timeout: $idleTimeoutSeconds seconds)", handle))
+ throw killedException(null)
}
+ n
+ }
+
+ /**
+ * Runs `op`, which writes to the worker, and returns its result. A
failure of the write
+ * after the worker has been killed because of the idle timeout throws a
+ * [[PythonWorkerException]] for the idle timeout; with no kill it is
thrown as is.
+ */
+ def write(op: => Int): Int = {
+ try {
+ op
+ } catch {
+ case e: IOException if pythonWorkerKilled =>
+ throw killedException(e)
+ }
+ }
+
+ private def killedException(cause: Throwable): PythonWorkerException = {
+ new PythonWorkerException(withTerminationDiagnostics(
+ "Python worker process terminated due to idle timeout " +
Review Comment:
**[4] nit: the error message does not use `workerName`.**
For the planner, the log says "Terminating Python planner worker process due
to idle timeout" while the exception says "Python worker process terminated due
to idle timeout". That was the same in `throwIfKilled`, so it is not a
regression. Now that the message is built in one place, `workerName` here would
make the two match. On the other hand, the `analyze` subtest of
`test_udtf_kill_on_timeout` (`test_udtf.py` L3277) and the planner case in
`BasePythonRunnerSuite` pin the current text, so keeping it as is is also fine.
##########
core/src/test/scala/org/apache/spark/api/python/BasePythonRunnerSuite.scala:
##########
@@ -1108,7 +1111,120 @@ 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.read(-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()
+ }
+
+ 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)
+ worker.channel.socket().setSoTimeout(1000)
+ val in = worker.channel.socket().getInputStream
+ val e = intercept[PythonWorkerException] {
+ handler.read(in.read())
Review Comment:
**[8] nit: the tests call `read` and `write` directly, so the wiring of the
three streams is not covered.**
Every new test passes its own `op` to `handler.read` or `handler.write`.
Nothing checks that `ReaderInputStream`, both `read` overloads of the pipelined
`socketInput`, and `PythonPlannerRunner.WorkerInputStream` actually go through
them, and the original bug was in exactly that wiring. A missing or wrong wrap
in one of them (e.g. the single-byte `read()` of the pipelined stream, or the
`channel.write` of `ReaderInputStream`) would still pass this suite and would
show up only in the PySpark tests, and there only depending on timing. If one
of these streams can be built over the test socket, a read through it with a
peer that is reset on `destroy()`, as here, would cover it.
##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -612,9 +612,10 @@ private[spark] object BasePythonRunner extends Logging {
* worker has closed the connection.
Review Comment:
**[6] nit: the first paragraph of the class doc still mentions only the end
of the stream.**
"fails the read once the killed worker has closed the connection"
(L611-L612) does not cover what this PR adds: a reset of the connection, and a
failed write, after the kill also fail with the idle timeout error. The second
paragraph explains it now, but the summary may read better as, e.g., "and fails
the read or the write once the killed worker has closed or reset the
connection".
##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -702,15 +703,53 @@ private[spark] object BasePythonRunner extends Logging {
}
/**
- * Throws a [[PythonWorkerException]] if `n`, the result of a read from
the worker, is the
- * end of the stream and the worker was killed because of the idle timeout.
+ * Runs `op`, which reads from the worker, and returns its result.
+ *
+ * If the read times out, which only a blocking socket with a read timeout
does, the idle
+ * timeout is handled and the read is tried again. Once the worker has
been killed because
+ * of the idle timeout, the end of the stream and a failure of the read
both throw a
+ * [[PythonWorkerException]] for the idle timeout: the connection of a
killed worker can be
+ * reset instead of closed, for example when the worker had unread input.
A failure of the
+ * read with no kill is thrown as is.
*/
- def throwIfKilled(n: Int): Unit = {
+ def read(op: => Int): Int = {
+ var n = 0
+ var done = false
+ while (!done) {
+ try {
+ n = op
+ done = true
+ } catch {
+ case _: SocketTimeoutException =>
Review Comment:
**[7] nit: no test checks that a timeout after the kill is still tried
again.**
`SocketTimeoutException` is an `IOException`, so `read` relies on this case
coming before `case e: IOException if pythonWorkerKilled`. If the two were
swapped or merged, the first timeout after the kill, while the worker is still
terminating, would fail right away with the idle timeout error, and the
"Waiting for ... to terminate after idle timeout" retry would be gone. The new
tests cover a timeout before the kill and a reset after it, so they would still
pass. One more case, e.g. an `op` that throws `SocketTimeoutException` twice
and then returns -1, checking `destroyCalls === 1` and the "Waiting for"
warning, would pin it.
##########
core/src/test/scala/org/apache/spark/api/python/BasePythonRunnerSuite.scala:
##########
@@ -1108,7 +1111,120 @@ 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.read(-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()
+ }
+
+ 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)
+ worker.channel.socket().setSoTimeout(1000)
Review Comment:
**[9] nit: the new tests add about 2 s of real waits.**
The blocking case waits 1 s here for the socket read timeout, and the
selector case waits 1 s in `handler.select` at L1154. `read` does not measure
how long the read took before the `SocketTimeoutException`, so a much smaller
timeout here, e.g. `setSoTimeout(10)`, checks the same thing. The selector case
could call `handler.onIdleTimeout(hasInputs = false)` directly before the
`select` at L1156, as the other tests do since #60507. The timing path of
`select` is already covered by the first test (L962).
##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -1532,7 +1557,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(worker.channel.read(buf))
Review Comment:
**[5] nit: the by-name `op` allocates a closure on every read and write of
the selector streams.**
This `read`, the `write` at L1675, and the two calls in
`PythonPlannerRunner.WorkerInputStream` (L219, L224) each allocate a
`Function0` per call, on paths that run several times per batch and had no
allocation before. It is the same reason as [4] in #60507
(https://github.com/apache/spark/pull/60507#discussion_r4575267643). Since the
handler already holds `worker`, the selector streams could call methods that
take the buffer, e.g. `read(buf: ByteBuffer): Int` and `write(buf: ByteBuffer):
Int` that run `worker.channel.read(buf)` and `worker.channel.write(buf)`
themselves. The by-name form could stay for the pipelined stream only, whose
`doRead` allocated a closure already.
--
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]