spark-test commented on code in PR #58835:
URL: https://github.com/apache/spark/pull/58835#discussion_r4507657733
##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -914,9 +941,30 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
pythonExec, workerModule, daemonModule, envVars.asScala.toMap,
worker)
}
}
+ awaitWorkerLogsFlushed()
Review Comment:
**Non-blocking (P2):** This wait runs after `releasePythonWorker` has
already put the worker back in the idle pool (lines 938-942). In daemon mode
with worker reuse, another task can take the worker from the pool while this
task's end-of-logs marker is still queued behind other output on the shared
stdout reader. That task records a baseline that does not include the pending
marker, so when the reader counts this task's marker, the next task's own wait
(`count > baseline`) is already satisfied, and it can finish before its own log
block is saved. A timed-out wait has the same effect, because the worker is
pooled with its marker still uncounted. Either way, `python_worker_logs()` can
miss the later task's logs, and no timeout warning is logged for it.
See **Shared repair plan 1** in the review body.
##########
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:
##########
@@ -914,9 +941,30 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
pythonExec, workerModule, daemonModule, envVars.asScala.toMap,
worker)
}
}
+ awaitWorkerLogsFlushed()
eos = true
}
+ /**
+ * When Python worker logging is enabled, block until this task's worker
log blocks have been
+ * captured from the worker's stdout and saved, so a subsequent
`python_worker_logs()` query
+ * observes them. Worker logs are captured on a separate channel from the
task result, so
+ * without this the following query can race the async capture. No-op when
logging is
+ * disabled for this task; on timeout the task still completes and a
warning is logged.
+ */
+ private def awaitWorkerLogsFlushed(): Unit = {
Review Comment:
**Non-blocking (P2):** This wait is only called from the end-of-data branch,
so two other exits that capture worker logs with the same end-of-logs marker
skip it. First, when the Python function raises, the readers take the
`PYTHON_EXCEPTION_THROWN` branch and throw without waiting
(PythonRunner.scala:1449-1450, PythonUDFRunner.scala:135-136,
PythonArrowOutput.scala:141-142). By then `capture_outputs()` has already
written the failing task's log lines and marker in its `finally` block
(worker.py:5236-5250), so a `python_worker_logs()` query run to debug the
failure can miss exactly those lines. Second, `PythonPlannerRunner.runInPython`
sets the session UUID for driver-side workers (UDTF `analyze`, Python data
source lookup, planning, write, and commit, and streaming sink commit) and then
releases or destroys the worker without waiting, whether the call returns a
result or raises (PythonPlannerRunner.scala:151-156, 180). Failures raised
before log capture starts, such as a Python v
ersion mismatch or a module missing during UDF deserialization, capture no log
lines, so they are not affected.
See **Shared repair plan 1** in the review body.
##########
core/src/main/scala/org/apache/spark/api/python/PythonWorkerLogCapture.scala:
##########
@@ -43,6 +43,16 @@ private[python] class PythonWorkerLogCapture(
// Map to track per-worker log writers: workerId(PID) -> (writer, sequenceId)
private val workerLogWriters = new ConcurrentHashMap[String,
(RollingLogWriter, AtomicLong)]()
+ // Per-worker count of end-of-logs sentinels processed. The worker emits
exactly one sentinel
+ // (an empty-payload marker line) at the end of each task, and processing it
closes and saves
+ // that task's log block(s). A task can therefore wait, via
`awaitLogsFlushed`, for this count
+ // to advance past a baseline snapshotted before the task ran, which
guarantees the task's log
+ // blocks are saved and visible to `python_worker_logs()`.
+ private val workerSentinelCounts = new ConcurrentHashMap[String,
AtomicLong]()
Review Comment:
**Non-blocking (P2):** Entries are added the first time each worker PID's
end-of-logs marker is processed (line 166), and nothing removes them:
`removeAndCloseWorkerLogWriter` and `closeAllWriters` touch only
`workerLogWriters`, and the factory's `stopWorker`, idle cleanup, pool
eviction, and `stop` never consult this map. Because the capture lives as long
as its factory, the map keeps one entry (roughly 100 bytes) for every worker
process the session has ever started on the executor, even with the flush
timeout set to 0. With the default worker reuse it grows only with
idle-timeout, eviction, and crash churn. With `spark.python.worker.reuse=false`
or in non-daemon mode, every Python task adds an entry, so a long-lived
executor's map grows toward the host's PID space: on a host with a large
`pid_max` such as 4194304, that is millions of entries and hundreds of
megabytes per session.
**Recommended change:** Give each worker's log-flush bookkeeping the same
lifetime as the worker. Register a worker's sentinel count when the worker
factory creates it, replacing any count left by an earlier process with the
same PID. Count end-of-logs markers only for registered workers: a marker from
a worker that is already gone still closes and saves that worker's log block,
but leaves no count behind. Unregister the worker wherever the factory or a
runner stops using it: closed instead of pooled after its task, evicted or
reaped as idle, stopped or destroyed, on a daemon restart, and when the factory
stops.
**Why this works:** Counts exist only for workers the factory still tracks.
The retained state is therefore bounded by live workers rather than by every
PID ever seen, and a recycled PID starts from a fresh registration instead of
inheriting a dead worker's count.
**Scope:** Tie per-worker log-flush counts to the worker factory's worker
lifecycle.
**Compatibility:** Log-flush attribution for pooled workers and the default
path with worker logging disabled stay unchanged.
**Risks:** Unregistering a worker while a task is still waiting on it would
make that wait run to the timeout, so unregistration must happen only after the
task's wait has finished, including the early-stop wait in the task-completion
listener, or when no wait runs, as for a killed task.
**Constraints:** A pooled worker keeps its registration across tasks, so
that the next task's starting count stays meaningful. Every end-of-logs marker
still closes and saves its worker's log block, including a marker from a worker
that is no longer registered. With worker logging disabled, no capture exists
and nothing changes.
**Success:** Retained sentinel counts never exceed the number of workers the
factory tracks plus those whose task is still finishing. An end-of-logs marker
from a worker that has already been retired leaves no retained count, and that
worker's log block is still saved. Long-running sessions keep no per-worker
state for finished workers, including when worker reuse is disabled or the
flush timeout is 0.
**Verification:**
- **Regression:** Running many logging-enabled tasks with worker reuse
disabled leaves no retained sentinel state for workers that have exited.
- **Regression:** A late end-of-logs marker from a worker retired after a
timed-out wait does not create retained state, and that worker's log lines are
still returned by python_worker_logs().
- **Behavior:** After the cleanup change, a pooled worker's next task still
waits for its own end-of-logs marker.
##########
core/src/test/scala/org/apache/spark/api/python/PythonWorkerLogCaptureSuite.scala:
##########
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.api.python
+
+import java.io.{ByteArrayInputStream, InputStream}
+import java.nio.charset.StandardCharsets
+
+import org.apache.spark.SparkFunSuite
+
+class PythonWorkerLogCaptureSuite extends SparkFunSuite {
+
+ private val marker = "PYTHON_WORKER_LOGGING"
+
+ // Drains the wrapped stream fully, emulating the RedirectThread that reads
worker stdout.
+ private def drain(in: InputStream): Unit = {
+ val buf = new Array[Byte](256)
+ while (in.read(buf) != -1) {}
+ in.close()
+ }
+
+ private def sentinelBytes(pid: String): Array[Byte] =
+ s"$marker:$pid:\n".getBytes(StandardCharsets.ISO_8859_1)
+
+ test("sentinel count starts at zero and awaitLogsFlushed times out before
any sentinel") {
+ val capture = new PythonWorkerLogCapture("session-1")
+ assert(capture.sentinelCount("1234") === 0L)
+ // No sentinel processed yet, so waiting for one beyond baseline 0 must
time out.
+ assert(!capture.awaitLogsFlushed("1234", baseline = 0L, timeoutMs = 50L))
+ }
+
+ test("processing an end-of-logs sentinel advances the count and releases
waiters") {
+ val capture = new PythonWorkerLogCapture("session-1")
+ val pid = "1234"
+
+ // A single end-of-logs sentinel line (empty JSON payload) does not touch
the BlockManager,
Review Comment:
**Nit (P3):** Because every test feeds only empty-payload markers, no log
block is ever written or saved, so moving the count increment ahead of
`removeAndCloseWorkerLogWriter` would keep every assertion green. The
concurrent test does not catch a missing wake-up either. The waiter waits with
a 30 s timeout (line 76), and the main thread joins for 30 s (line 90) after a
poll that gives up after about 1 s (lines 82-87). Without `notifyAll`, the
waiter's re-check at 30 s still sees the count and returns `true` before the
join deadline. No test drives `BasePythonRunner`, the `SparkEnv` and factory
delegators, or the flush-timeout config, so a lookup miss that silently skips
the wait would also go unnoticed.
**Verification:**
- **Regression:** With log lines followed by an end-of-logs marker, the
count advancing implies that the worker's log block is already stored for the
session.
- **Regression:** A waiter blocked with a long timeout returns promptly
after a concurrently processed end-of-logs marker, and the check fails when the
notification is missing.
- **Behavior:** While marker processing is held back, a logging-enabled task
completes only after its block is saved, and tasks with worker logging disabled
or a flush timeout of 0 complete without waiting.
--
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]