gengliangwang opened a new pull request, #60641:
URL: https://github.com/apache/spark/pull/60641
### What changes were proposed in this pull request?
**This PR is stacked on #60640 (SPARK-60733): its first commit is that PR,
and only the second commit is new here.** It needs that PR: the wait that this
PR adds would otherwise hold a task whose thread is in `get_next` of a native
data source until `get_next` returns on its own, since `is_interrupted` only
became true once the completion listeners ran.
Some operators read the input of a task on a thread of their own. This PR
makes the task stop that thread, and wait until it no longer reads the input,
before its completion listeners run, as the writer of pipelined Python UDFs
already does (SPARK-33277, `BasePythonRunner.startPipelinedWriter`). The
readers of native data sources then free the buffers of their last batch when
they are closed, rather than at a later garbage collection.
- **`TaskInputThread`** (new, `core`, `private[spark]`). `start(context,
thread)(stop)` registers a pre-completion listener (SPARK-60113) and starts the
thread. Once the task completes, also when it failed or was killed, the
listener:
- calls `stop(false)`, which makes the thread stop reading soon: a flag
that the thread checks between two rows, and the end of what it may be blocked
on;
- interrupts the thread, unless the task is not interruptible then, as the
kill of a task and the pipelined Python writer do;
- waits until the thread no longer reads the input. After a grace period,
it calls `stop(true)` once, which stops the thread by force. The wait has no
time bound, since giving up would let the completion listeners free what the
thread still reads; it logs a warning every 10 seconds, the first one with the
stack trace of the thread, and interrupts the thread again.
The thread is not started once the task completed: the listener would then
run too late. `TaskInputThread.ProcessStopper` signals a process without
closing its streams (closing its input waits for a thread that is blocked in a
write to it), and by force kills it and the processes that it had started when
it was signaled.
- **`PipedRDD`**. The stdin writer thread is started this way, with a grace
period of 10 seconds. It now checks between two elements whether the task
completed: its `PrintWriter` does not fail when the process is gone, so the
thread used to read the rest of the input. The process is signaled and its
output closed, as `Process.destroy()` did, but not its input, which the thread
closes when it exits.
- **Script transformation** (`BaseScriptTransformationExec`, for Spark and
Hive). The writer thread is started this way. The task waits until the thread
no longer reads the input rows, not until it exits: the thread then still waits
for the script to end. The thread fails rather than end its input when the task
completes, so that the script does not take the rows that it got for its whole
input. The grace period is the time that a script gets to exit,
`spark.sql.scriptTransformation.exitTimeoutInSeconds` (internal, 10 seconds by
default). As before, a script whose whole output the task read is not destroyed.
- **R runner** (`BaseRRunner`). The writer thread is started this way;
stopping it closes its socket, which fails a write that is blocked on an R
worker.
- **`NativePartitionReader`**. `close()` frees the buffers of the last batch
at once, with the stream, the task context and the allocator. This removes
`batchReturned`, `batchCleanable` and the Cleaner action of SPARK-60753, and
the reference that each `NativeColumnVector` kept to its reader so that the
Cleaner would wait for it. `next()` on a closed reader still fails, and a
reader closed while another thread is in `next()` still leaves the release of
the stream to that thread (SPARK-60705).
- **Docs**. `spark_datasource.h` and the docs of the Rust SDK no longer say
that Spark may release the last array of a stream later, from a JVM Cleaner
thread, nor that Spark reads a stream on a thread that the task does not wait
for. An engine that reads a stream in native code may still release it, and its
arrays, after the task ended.
### Why are the changes needed?
The writer thread of script transformation (`TRANSFORM`), the stdin writer
thread of `PipedRDD` and the writer thread of the R runner can still read a
columnar batch after their task completed, while the completion listener of
`DataSourceRDD` closes the reader that returned the batch: under a `LIMIT`, or
when the script exits early. Their listeners destroyed the process and
interrupted the thread, but did not wait for it, and the one of `PipedRDD`
usually ran after the reader was closed, since its thread creates the iterator
of its input.
- The readers of native data sources read the buffers of a batch at their
addresses (SPARK-60753). So a reader that was closed before the end of its
stream could not free its last batch: it left it to a Cleaner, which frees it
at a garbage collection that this off-heap memory does not trigger. Every scan
that ends early, as with `LIMIT`, `show()` or `take()`, held one batch per
partition until then
(https://github.com/apache/spark/pull/59961#discussion_r4500198812). With this
PR, no thread reads the input once the completion listeners run, so the reader
frees the batch at once and the Cleaner is gone, as agreed in that review
(https://github.com/apache/spark/pull/59961#discussion_r4518855898).
- The hazard is not specific to native data sources: with
`spark.sql.columnVector.offheap.enabled`, the vectorized Parquet reader frees
its `OffHeapColumnVector`s when it is closed, which such a thread could then
read.
### Does this PR introduce _any_ user-facing change?
Yes, for `rdd.pipe`, `TRANSFORM` and the R UDFs, when a task ends before
their writer thread read all its input:
- The task now waits for that thread before it completes. The thread stops
between two rows, and an interrupt ends most waits, so this is short. A thread
that is blocked in reading its input in a way that ignores interrupts holds the
task until that read returns, as for pipelined Python UDFs;
`spark.task.reaper.enabled` bounds this for a killed task.
- If that thread is blocked in a write to a process that ignores SIGTERM and
does not read its input, the process and the processes that it started are
killed after 10 seconds (`PipedRDD`) or after
`spark.sql.scriptTransformation.exitTimeoutInSeconds` (`TRANSFORM`). Before,
the thread and the process stayed until the process ended.
- The stdin writer thread of `PipedRDD` no longer reads the rest of its
input after the task completed.
The change to native data sources is not user-facing: they are not released
yet (4.4.0).
### How was this patch tested?
New tests:
- `TaskInputThreadSuite` (11 tests): the thread exits before the completion
listeners run, also the ones that it adds; a thread that `stop` does not end is
interrupted; the forced stop after the grace period; the warnings; no start
once the task completed; waiting only for the reading; the interrupt status of
the completing thread; a failing `stop`; no task; and `ProcessStopper` on a
shell that ignores SIGTERM, and on a command that outlives its shell.
- `PipedRDDSuite`: the stdin writer thread no longer reads an input that is
slow to stop when the completion listener of that input runs, and it stops
reading an input that does not end. The existing test for SPARK-29104 now
checks that the thread is gone when the job ends, without `eventually`.
- `BaseScriptTransformationSuite` (run as `SparkScriptTransformationSuite`
and `HiveScriptTransformationSuite`): the writer thread no longer reads an
input that is slow to stop when the completion listener of that input runs, and
a script that ignores SIGTERM, with a command that does not read its input, is
killed after the exit timeout.
- `NativeDataSourceSuite`:
- "wait for a thread that reads a stream before the task completes"
replaces "release a stream only once get_next returns": the job over `rdd.pipe`
does not end while the stdin writer thread is in `get_next`, and when it ends,
the stream and the task context are released.
- "free the buffers of a closed reader without a GC" also closes a reader
before the end of its stream.
- "free the buffers of a scan when its task completes before the end of
the scan" runs a `LIMIT` and a `TRANSFORM ... LIMIT 1` over a native scan.
- The suite no longer calls `System.gc()` before it checks, after each
test, that the buffers of all the readers are freed.
- Removed: "close a reader while another thread reads the batch that it
returned" and "keep the buffers of a closed reader while its batch is held
without the reader", which tested the deferred free.
With the wait of `TaskInputThread` removed locally, the two new
`PipedRDDSuite` tests, the two new `BaseScriptTransformationSuite` tests and
"wait for a thread that reads a stream before the task completes" fail.
Run locally on the two commits of this PR, on Linux with Temurin 25.0.2 and
g++. The Java version check of the build, which requires 25.0.3 or later for
Java 25, was bypassed (`set every TaskKey[Unit]("checkJavaVersion") := {}`),
with every JVM on the parallel collector
(`JAVA_TOOL_OPTIONS=-XX:+UseParallelGC`), and the `snowflake-jdbc-thin` test
dependency, which the local Maven mirror does not serve, was excluded:
- `build/sbt 'core/testOnly *TaskInputThreadSuite *PipedRDDSuite
*.scheduler.TaskContextSuite *BasePythonRunnerSuite'`: 138 tests passed (11,
14, 68 and 45).
- `build/sbt 'sql/testOnly *SparkScriptTransformationSuite
*NativeDataSourceSuite *NativeColumnVectorSuite
*NativeDataSourceClusterSuite'`: 138 tests passed (36, 89, 11 and 2), and 2 of
`NativeDataSourceSuite` canceled (`native data sources require Java 22 or
later`, which only runs on older Java versions, and `Arrow UDFs on the columns
of a native data source`, which needs pandas).
- `build/sbt -Phive 'hive/testOnly *HiveScriptTransformationSuite'`: 50
tests passed.
- `core/scalastyle`, `core/Test/scalastyle`, `sql/scalastyle`,
`sql/Test/scalastyle`, `catalyst/scalastyle` and `hive/scalastyle`: 0 errors.
`cargo fmt --all -- --check` in `sql/native/rust` passed (Rust 1.85); the other
Rust checks were not run, since only doc comments and the README changed there.
`dev/lint-java` and `dev/mima` were not run.
Not tested: the writer thread of the R runner, whose tests need R.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Fable 5.2)
This pull request and its description were written by Isaac.
--
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]