You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by do...@apache.org on 2026/10/20 14:25:12 UTC

(spark) branch branch-4.x updated: [SPARK-60113][CORE][SQL] Wait for the pipelined Python UDF writer to exit before task completion cleanup

This is an automated email from the ASF dual-hosted git repository.

dongjoon-hyun pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.x by this push:
     new 4407a0bf9b7a [SPARK-60113][CORE][SQL] Wait for the pipelined Python UDF writer to exit before task completion cleanup
4407a0bf9b7a is described below

commit 4407a0bf9b7a17819597825346d876609b3c8ca1
Author: Liang-Chi Hsieh <vi...@gmail.com>
AuthorDate: Tue Oct 20 07:24:52 2026 -0700

    [SPARK-60113][CORE][SQL] Wait for the pipelined Python UDF writer to exit before task completion cleanup
    
    ### What changes were proposed in this pull request?
    
    In pipelined Python UDF mode (`spark.python.udf.pipelined.enabled`), the listener that stops the writer thread now waits until the writer has actually exited, and it runs before every task completion listener.
    
    1. Add `TaskContext.addTaskPreCompletionListener` (`private[spark]`, abstract; `BarrierTaskContext` delegates). `TaskContextImpl.markTaskCompleted` runs these listeners on its own thread before it marks the task completed, outside the listener invocation used for the other listeners. Only then does it set `completed` (in the same `synchronized` block that finds no more pre-completion listeners) and run the completion listeners as before. While the pre-completion listeners run, a liste [...]
    2. The writer is wrapped in `BasePythonRunner.PipelinedWriterTask`. Its state (not started, running on a thread, or finished) is kept in a single field guarded by the task, and a latch is counted down on every transition to finished. The stop listener is added with `addTaskPreCompletionListener`, and the writer is submitted only if the task has not completed by then. The listener interrupts the writer thread directly and waits on that latch. If it runs before the pool has started the  [...]
    3. The wait has no time bound, the same as the `WriterThread.join()` that the writer thread used before SPARK-44705 (added for SPARK-33277). While it waits, it logs a warning every 10 seconds that names the writer thread (with its stack trace the first time), and it interrupts the writer again, in case code it called consumed the interrupt. Like `Task.kill`, it does not interrupt while `context.interruptible()` is false, which is while some thread of the task, not necessarily the writ [...]
    4. The writer writes through a `CloseShieldOutputStream` (added by SPARK-60305) around its `DirectByteBufferOutputStream`. The Arrow writers write through `Channels.newChannel(dataOut)`, an interruptible channel. When the stop listener interrupts the writer during such a write, the JDK closes that channel and the stream under it on the interrupting thread, and the buffer was freed while the writer still copied into it. Now the buffer is freed only in the writer's own `finally`.
    5. A fatal error of the writer (e.g. `OutOfMemoryError`), including one while it sets up its buffer, is passed to the reader through `writer.setException` with a socket `shutdownOutput()`, and it is logged. Previously the thread pool's `FutureTask` kept it, and the reader waited for the Python worker.
    
    ### Why are the changes needed?
    
    The existing listener does:
    
    ```scala
    writerFuture.cancel(true)
    try { writerFuture.get() } catch { case _: CancellationException | ... => }
    ```
    
    Its comment says this waits for the writer to exit before the listeners that run after it (registered earlier, LIFO) free the memory backing the input rows. But once `cancel(true)` succeeds, `FutureTask.get()` throws `CancellationException` right away and does not wait for the interrupted runnable to return. So the writer can still be serializing a row, or adding it to a `HybridRowQueue` page, when the queue's close listener frees that page. That is a use-after-free, and with off-heap [...]
    
    A task completes while the writer is still running when the output is not fully consumed, for example with a `LIMIT` or when the task fails.
    
    Ordering the writer listener in the completion listener stack is not enough. Listeners run in reverse order of registration, and the writer thread itself adds completion listeners lazily while it pulls the upstream iterator, e.g. `ParquetReaderCallback.initIfNotAlready` of the DSv2 Parquet reader (which closes the vectorized reader and its off-heap column vectors) or the `UnsafeExternalSorter` that `ExternalAppendOnlyUnsafeRowArray` creates once it spills. Those would run before the w [...]
    
    The wait cannot be bounded safely: if the listener gave up, the listeners that run next would still free the memory, and throwing from the listener does not stop them either. Even a writer blocked in upstream I/O that ignores interrupts (e.g. a slow JDBC fetch) adds the row it gets next to the `HybridRowQueue`, whose `InMemoryRowQueue` writes through the page's base object captured at construction, so a freed page would be corrupted even on-heap (`HeapMemoryAllocator` pools pages for  [...]
    
    The pipelined mode was added in 4.3.0 by SPARK-56642, so branch-4.3 and branch-4.x have the same issue. The same interrupt-closes-the-buffer problem also affects the default (non-pipelined) Arrow UDF path, where `Task.kill` interrupts the task thread while it serializes into `ReaderInputStream`'s buffer; SPARK-60305 fixed that separately, since it needs backports to 4.0 through 4.3, and added the `CloseShieldOutputStream` that this change also uses.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No. This fixes a bug in an opt-in mode that is not released yet (4.3.0). For tasks with no pre-completion listener, listener behavior is unchanged.
    
    ### How was this patch tested?
    
    New tests in `BasePythonRunnerSuite`:
    - Task completion stays blocked until a running writer that ignores interrupts exits. Both a cleanup listener added on the task thread before the writer starts and one that the writer thread adds after the stop listener see that the writer has exited. The tests first wait until task completion has reached the writer listener.
    - A listener that the writer thread adds after task completion has started is queued and runs after the writer exits.
    - Stopping interrupts a running writer right away; an interrupt of the stopping thread, whether it arrives during the wait or while stopping, does not stop it and is not passed on; an interrupt pending before stopping is kept.
    - The writer is not interrupted while it creates a resource uninterruptibly, and is interrupted afterwards.
    - A writer stopped before it starts never runs, also when it is stopped twice, when it is started after the task completed, or when it is started while another thread runs the completion listeners. Stopping on the writer thread itself does not wait.
    - A failure to interrupt the writer does not end the wait, and is thrown once the writer has exited.
    - A writer that consumed the first interrupt is interrupted again.
    - An interrupted Arrow-style channel write in a later buffer leaves the buffer usable, through a real `PipelinedWriterRunnable` (with a socket pair standing in for the Python worker).
    - A warning that fails on every tick does not skip the repeated interrupt.
    - A fatal error of a real `PipelinedWriterRunnable` is rethrown, logged, and passed to the reader, and the Python side sees EOF.
    
    New tests in `TaskContextSuite`:
    - Pre-completion listener ordering and failure handling, and a pre-completion listener added after completion running like a completion listener, or failing the task and throwing if it fails. Failures of pre-completion and completion listeners are merged into one exception.
    - While a pre-completion listener runs, listeners added from another thread are only queued and run on the completing thread afterwards, and failure listeners triggered from another thread still run.
    
    Before the fix, a test with the old listener code showed `markTaskCompleted` returning while the writer was still running. Each of the following changes, reverted on its own, makes its test fail: the cancel-then-`get()` wait, adding the stop listener as a pre-completion listener, running the pre-completion listeners before setting `completed`, the close shield, the immediate interrupt, skipping the interrupt during uninterruptible resource creation, the repeated interrupt, clearing an [...]
    
    Also ran the whole `core` test suite, the `sql` suites that use `markTaskFailed`, `markTaskCompleted` or `markInterrupted` (`JdbcTaskInterruptSuite`, `SupportsArchiveFormatSuite`, `JsonSuite`, `ParquetStorageFilterSuite`, `ValueStateSuite`, `RocksDBStateStoreSuite`, `RocksDBStateStoreLockHardeningSuite`, `RocksDBCheckpointFailureInjectionSuite`), and `pyspark.sql.tests.pandas.test_pipelined_udf`.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Opus 5.5)
    
    This pull request and its description were written by Isaac.
    
    Closes #59332 from viirya/SPARK-60113-wait-pipelined-writer.
    
    Authored-by: Liang-Chi Hsieh <vi...@gmail.com>
    Signed-off-by: Dongjoon Hyun <do...@apache.org>
    (cherry picked from commit ca1f5c5752e3a454381c75aca8190099e7d50e81)
    Signed-off-by: Dongjoon Hyun <do...@apache.org>
---
 .../org/apache/spark/BarrierTaskContext.scala      |   6 +
 .../main/scala/org/apache/spark/TaskContext.scala  |  17 +
 .../scala/org/apache/spark/TaskContextImpl.scala   |  98 +++-
 .../org/apache/spark/api/python/PythonRunner.scala | 337 ++++++++++--
 .../spark/api/python/BasePythonRunnerSuite.scala   | 582 ++++++++++++++++++++-
 .../apache/spark/scheduler/TaskContextSuite.scala  | 178 ++++++-
 project/MimaExcludes.scala                         |   2 +
 7 files changed, 1174 insertions(+), 46 deletions(-)

diff --git a/core/src/main/scala/org/apache/spark/BarrierTaskContext.scala b/core/src/main/scala/org/apache/spark/BarrierTaskContext.scala
index cf3ce95c4d1f..f9cf2c4bc0c9 100644
--- a/core/src/main/scala/org/apache/spark/BarrierTaskContext.scala
+++ b/core/src/main/scala/org/apache/spark/BarrierTaskContext.scala
@@ -208,6 +208,12 @@ class BarrierTaskContext private[spark] (
     this
   }
 
+  override private[spark] def addTaskPreCompletionListener(
+      listener: TaskCompletionListener): this.type = {
+    taskContext.addTaskPreCompletionListener(listener)
+    this
+  }
+
   override def addTaskFailureListener(listener: TaskFailureListener): this.type = {
     taskContext.addTaskFailureListener(listener)
     this
diff --git a/core/src/main/scala/org/apache/spark/TaskContext.scala b/core/src/main/scala/org/apache/spark/TaskContext.scala
index a853ea6bf029..34df7d5c6ccc 100644
--- a/core/src/main/scala/org/apache/spark/TaskContext.scala
+++ b/core/src/main/scala/org/apache/spark/TaskContext.scala
@@ -147,6 +147,23 @@ abstract class TaskContext extends Serializable {
     })
   }
 
+  /**
+   * Adds a listener to be executed on task completion before every listener added with
+   * `addTaskCompletionListener`, from any thread and even if that listener was added later, as
+   * long as this listener is added before the task completes. The thread that marks the task
+   * completed runs these listeners first, in reverse order of registration, and only then marks
+   * the task completed (`isCompleted()` becomes true) and runs the completion listeners. While
+   * these listeners run, a completion listener added from another thread is only queued. A
+   * listener added after the task completes, including while the completion listeners run, is
+   * handled like one added with `addTaskCompletionListener` at that point: it runs after the
+   * completion listeners that have already run.
+   *
+   * This is for stopping helper threads that read task resources owned by completion
+   * listeners: the helper thread itself can add such listeners lazily (e.g. when it first
+   * pulls from an upstream iterator), and those would otherwise run first.
+   */
+  private[spark] def addTaskPreCompletionListener(listener: TaskCompletionListener): TaskContext
+
   /**
    * Adds a listener to be executed on task failure (which includes completion listener failure, if
    * the task body did not already fail). Adding a listener to an already failed task will result in
diff --git a/core/src/main/scala/org/apache/spark/TaskContextImpl.scala b/core/src/main/scala/org/apache/spark/TaskContextImpl.scala
index ec4e08abf9a5..dafc938a65c1 100644
--- a/core/src/main/scala/org/apache/spark/TaskContextImpl.scala
+++ b/core/src/main/scala/org/apache/spark/TaskContextImpl.scala
@@ -70,6 +70,13 @@ private[spark] class TaskContextImpl(
    */
   @transient private val onCompleteCallbacks = new Stack[TaskCompletionListener]
 
+  /**
+   * List of callback functions to execute when the task completes, before any of
+   * `onCompleteCallbacks`. `markTaskCompleted()` runs them on its own thread before it sets
+   * `completed`, in reverse order of registration, as they are popped from the stack.
+   */
+  @transient private val onPreCompleteCallbacks = new Stack[TaskCompletionListener]
+
   /** List of callback functions to execute when the task fails. */
   @transient private val onFailureCallbacks = new Stack[TaskFailureListener]
 
@@ -100,6 +107,10 @@ private[spark] class TaskContextImpl(
   // Whether this task is able to be interrupted. Should be protected by `TaskContext.synchronized`.
   private var _interruptible = true
 
+  // Whether `markTaskCompleted()` has been called. It sets `completed` once the pre-completion
+  // listeners have run.
+  private var completionStarted: Boolean = false
+
   // Whether the task has completed.
   private var completed: Boolean = false
 
@@ -128,6 +139,24 @@ private[spark] class TaskContextImpl(
     this
   }
 
+  override private[spark] def addTaskPreCompletionListener(
+      listener: TaskCompletionListener): this.type = {
+    val completedAlready = synchronized {
+      // While `markTaskCompleted()` runs the pre-completion listeners, `completed` is not set yet,
+      // so the new listener is queued and that thread runs it before it sets `completed`.
+      if (!completed) {
+        onPreCompleteCallbacks.push(listener)
+      }
+      completed
+    }
+    if (completedAlready) {
+      // Too late to run before the completion listeners: run it like one added now, i.e. right
+      // away, or next if the completion listeners are still running.
+      addTaskCompletionListener(listener)
+    }
+    this
+  }
+
   override def addTaskFailureListener(listener: TaskFailureListener): this.type = {
     synchronized {
       onFailureCallbacks.push(listener)
@@ -178,16 +207,79 @@ private[spark] class TaskContextImpl(
 
   private[spark] override def markTaskCompleted(error: Option[Throwable]): Unit = {
     synchronized {
-      if (completed) return
-      completed = true
+      if (completionStarted) return
+      completionStarted = true
+    }
+    // Run the pre-completion listeners on this thread before setting `completed`, outside the
+    // listener invocation of `invokeListeners()`. Until `completed` is set, a listener that
+    // another thread adds is only queued, so that thread cannot start running the listeners. That
+    // thread can be one a pre-completion listener stops and waits for, e.g. a pipelined Python UDF
+    // writer that adds listeners lazily while it pulls its input. And since the completion
+    // listeners only run after `completed` is set, they run after every pre-completion listener,
+    // even if another thread is invoking listeners at this point.
+    val preCompletionExceptions = new ArrayBuffer[Throwable](2)
+    def nextPreCompletionListener(): Option[TaskCompletionListener] = synchronized {
+      if (onPreCompleteCallbacks.empty()) {
+        // Set together with finding no more pre-completion listeners, so that one added later
+        // is handed to `addTaskCompletionListener` instead of being left in the stack.
+        completed = true
+        None
+      } else {
+        Some(onPreCompleteCallbacks.pop())
+      }
+    }
+    var listener: Option[TaskCompletionListener] = None
+    while ({listener = nextPreCompletionListener(); listener.nonEmpty}) {
+      invokeTaskPreCompletionListener(listener.get, preCompletionExceptions)
+    }
+
+    try {
+      invokeTaskCompletionListeners(error)
+    } catch {
+      case e: TaskCompletionListenerException if preCompletionExceptions.nonEmpty =>
+        // Merge the completion listeners' own failures, not the exception that wraps them. Any
+        // other error comes from invokeListeners itself (e.g. an OutOfMemoryError) and is left
+        // to propagate, so that the executor still sees a fatal one.
+        preCompletionExceptions ++= e.getSuppressed.toSeq
+    }
+    if (preCompletionExceptions.nonEmpty) {
+      throw newTaskCompletionListenerException(preCompletionExceptions.toSeq, error)
     }
-    invokeTaskCompletionListeners(error)
   }
 
   private[spark] override def getTaskFailure: Option[Throwable] = {
     failureCauseOpt
   }
 
+  /**
+   * Runs a pre-completion listener. If it fails, marks the task failed, like a failing completion
+   * listener does in `invokeListeners()`, and adds the failure to `listenerExceptions`.
+   */
+  private def invokeTaskPreCompletionListener(
+      listener: TaskCompletionListener,
+      listenerExceptions: ArrayBuffer[Throwable]): Unit = {
+    try {
+      listener.onTaskCompletion(this)
+    } catch {
+      case e: Throwable =>
+        try {
+          markTaskFailed(e)
+        } catch {
+          case t: Throwable => e.addSuppressed(t)
+        }
+        listenerExceptions += e
+        logError(log"Error in ${MDC(LISTENER, "TaskPreCompletionListener")}", e)
+    }
+  }
+
+  private def newTaskCompletionListenerException(
+      listenerExceptions: Seq[Throwable],
+      error: Option[Throwable]): TaskCompletionListenerException = {
+    val exception = new TaskCompletionListenerException(listenerExceptions.map(_.getMessage), error)
+    listenerExceptions.foreach(exception.addSuppressed)
+    exception
+  }
+
   private def invokeTaskCompletionListeners(error: Option[Throwable]): Unit = {
     // It is safe to access the reference to `onCompleteCallbacks` without holding the TaskContext
     // lock. `invokeListeners()` acquires the lock before accessing the contents.
diff --git a/core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala b/core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala
index 21a4ac4ba45e..bfed268cd323 100644
--- a/core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala
+++ b/core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala
@@ -22,7 +22,7 @@ import java.net._
 import java.nio.ByteBuffer
 import java.nio.channels.{AsynchronousCloseException, Channels, SelectionKey, ServerSocketChannel, SocketChannel}
 import java.util.UUID
-import java.util.concurrent.{CancellationException, ConcurrentHashMap, ExecutionException, TimeUnit}
+import java.util.concurrent.{ConcurrentHashMap, CountDownLatch, TimeUnit}
 import java.util.concurrent.atomic.AtomicBoolean
 
 import scala.jdk.CollectionConverters._
@@ -36,7 +36,7 @@ import org.apache.spark._
 import org.apache.spark.api.python.PythonFunction.PythonAccumulator
 import org.apache.spark.internal.{Logging, MessageWithContext}
 import org.apache.spark.internal.LogKeys
-import org.apache.spark.internal.LogKeys.{COUNT, PYTHON_WORKER_IDLE_TIMEOUT, SIZE, TASK_NAME, TIME, TOTAL_TIME}
+import org.apache.spark.internal.LogKeys.{COUNT, PYTHON_WORKER_IDLE_TIMEOUT, SIZE, TASK_NAME, THREAD_NAME, TIME, TOTAL_TIME}
 import org.apache.spark.internal.config.{BUFFER_SIZE, EXECUTOR_CORES}
 import org.apache.spark.internal.config.Python._
 import org.apache.spark.rdd.InputFileBlockHolder
@@ -183,6 +183,266 @@ private[spark] object BasePythonRunner extends Logging {
     ThreadUtils.newDaemonCachedThreadPool("python-udf-pipelined-writer")
   }
 
+  /** How often to log while task completion waits for a pipelined writer to exit. */
+  private val pipelinedWriterExitWarnIntervalMs = 10000L
+
+  /**
+   * Runs `writer` on [[pipelinedWriterThreadPool]] and registers a task pre-completion listener
+   * that interrupts it and blocks until it has exited.
+   *
+   * Task completion listeners free memory that the writer may still read or write, e.g. the
+   * pages of the HybridRowQueue that buffers the input rows, or the off-heap column vectors of a
+   * vectorized reader. If the writer were still running at that point, it would be a
+   * use-after-free that can crash the executor (SPARK-33277). The listener is added with
+   * `addTaskPreCompletionListener` so that it runs before all of them, including the ones that
+   * the writer thread adds lazily while it pulls the upstream iterator, which would run first if
+   * this were an ordinary completion listener.
+   *
+   * The listener does not use the `Future` returned by the pool: interrupting the writer through
+   * it takes `Future.cancel(true)`, after which `Future.get()` throws `CancellationException`
+   * immediately instead of waiting for the runnable to return. [[PipelinedWriterTask]] records
+   * the thread running the writer to interrupt it directly, and counts down a latch when the
+   * writer exits or is stopped before it starts.
+   *
+   * The wait has no time bound, so a writer blocked in upstream I/O that ignores interrupts
+   * (e.g. a socket read without a timeout) holds task completion until that I/O returns. This
+   * includes I/O that only a close listener of the upstream reader would unblock, since that
+   * listener now runs after the wait. If such a task is killed, `spark.task.reaper.enabled` with
+   * a positive `spark.task.reaper.killTimeout` bounds how long it may stay in this state, by
+   * killing the executor JVM, except in local mode, where the reaper only logs an error.
+   */
+  private[python] def startPipelinedWriter(writer: Runnable, context: TaskContext): Unit = {
+    val writerTask = new PipelinedWriterTask(writer, context, taskIdentifier(context))
+    // The writer is submitted only if the task has not completed once the listener is added,
+    // which can happen when this runs on a helper thread such as PipedRDD's stdin writer.
+    // `completed` is set only after the pre-completion listeners have run, so if it is still
+    // false here, the listener is a pre-completion one and stops the writer before any completion
+    // listener runs. Otherwise the writer never starts: the listener may then only be queued
+    // behind completion listeners that another thread is running, and would come too late.
+    context.addTaskPreCompletionListener(new TaskCompletionListener {
+      override def onTaskCompletion(context: TaskContext): Unit = writerTask.stopAndAwaitExit()
+    })
+    if (!context.isCompleted()) {
+      pipelinedWriterThreadPool.submit(writerTask)
+    }
+  }
+
+  /** The state of a [[PipelinedWriterTask]]. */
+  private sealed trait PipelinedWriterState
+  private case object PipelinedWriterNotStarted extends PipelinedWriterState
+  private case class PipelinedWriterRunning(thread: Thread) extends PipelinedWriterState
+  /** The writer has exited, or was stopped before it started and will never run. */
+  private case object PipelinedWriterFinished extends PipelinedWriterState
+
+  /**
+   * Wraps a pipelined writer so that task completion can wait until the writer has either
+   * exited or is guaranteed never to run.
+   */
+  private[python] class PipelinedWriterTask(
+      writer: Runnable,
+      context: TaskContext,
+      taskName: String,
+      warnIntervalMs: Long = pipelinedWriterExitWarnIntervalMs)
+    extends Runnable {
+    // Protected by `this`. NotStarted moves to Running when run() starts the writer, or to
+    // Finished when stopAndAwaitExit() gets there first; Running moves to Finished when the
+    // writer exits. `exited` is counted down whenever the state becomes Finished.
+    private var state: PipelinedWriterState = PipelinedWriterNotStarted
+    private val exited = new CountDownLatch(1)
+
+    private def finish(): Unit = synchronized {
+      state = PipelinedWriterFinished
+      exited.countDown()
+    }
+
+    override def run(): Unit = {
+      val start = synchronized {
+        if (state == PipelinedWriterNotStarted) {
+          state = PipelinedWriterRunning(Thread.currentThread())
+          true
+        } else {
+          false
+        }
+      }
+      if (start) {
+        try {
+          writer.run()
+        } catch {
+          case t: Throwable =>
+            // The thread pool's FutureTask would keep this to itself, so log it here.
+            logError(log"Pipelined Python writer of ${MDC(TASK_NAME, taskName)} failed", t)
+            throw t
+        } finally {
+          finish()
+        }
+      }
+    }
+
+    /**
+     * Interrupts `thread`, the thread running the writer, unless it is the current thread, and
+     * not while `context.interruptible()` is false, which `Task.kill` respects too. That flag is
+     * task-wide: it is false while any thread of the task, not necessarily the writer, creates a
+     * resource through `TaskContext.createResourceUninterruptibly`. Must hold the lock of `this`
+     * and see `PipelinedWriterRunning(thread)`, so that the thread still runs the writer. Returns
+     * a failure to interrupt the writer instead of throwing it, so that the caller keeps waiting.
+     */
+    private def interruptWriter(thread: Thread): Option[Throwable] = {
+      if (thread eq Thread.currentThread()) {
+        None
+      } else {
+        try {
+          TaskContext.synchronized {
+            if (context.interruptible()) {
+              thread.interrupt()
+            }
+          }
+          None
+        } catch {
+          case t: Throwable => Some(t)
+        }
+      }
+    }
+
+    /**
+     * Stops the writer and waits until it has exited, or makes sure it never runs. Leaves the
+     * interrupt status of the calling thread as it was on entry. A failure to interrupt the writer
+     * or to log the wait does not end the wait; it is thrown once the writer has exited.
+     */
+    def stopAndAwaitExit(): Unit = {
+      val wasInterrupted = Thread.interrupted()
+      try {
+        var failure: Option[Throwable] = None
+        val runningThread = synchronized {
+          state match {
+            case PipelinedWriterNotStarted =>
+              // The writer never started and now never will.
+              finish()
+              None
+            case PipelinedWriterRunning(thread) =>
+              // Interrupts the writer thread. This unblocks channel.write (the JDK closes the
+              // channel and throws ClosedByInterruptException). Otherwise the writer sees the
+              // interrupt only between calls to writeNextInputToStream, each of which can pull
+              // and serialize a whole batch of input rows (e.g. for the Arrow runners). If
+              // `context.interruptible()` is false, it is interrupted on a later warning instead.
+              failure = interruptWriter(thread)
+              Some(thread)
+            case PipelinedWriterFinished => None
+          }
+        }
+        runningThread.foreach { thread =>
+          if (thread eq Thread.currentThread()) {
+            // TaskContextImpl runs the pre-completion listeners on the thread that marks the task
+            // completed, and a listener added from the writer thread meanwhile is only queued, so
+            // this should not happen. If it does, the writer can only exit after this returns,
+            // so waiting would never end. Nothing stops the writer either: once the remaining
+            // listeners, which run on this thread right after this one, have freed the memory it
+            // uses, the writer goes back to pulling and writing input until it fails.
+            logError(log"Task completion listeners of ${MDC(TASK_NAME, taskName)} run on its " +
+              log"pipelined Python writer thread while the writer is running; not waiting " +
+              log"for the writer to exit, which may lead to a use-after-free.",
+              new Exception("Stack trace of the pipelined Python writer thread"))
+          } else {
+            failure = awaitExit(thread, failure)
+          }
+        }
+        failure.foreach(e => throw e)
+      } finally {
+        Thread.interrupted()
+        if (wasInterrupted) {
+          Thread.currentThread().interrupt()
+        }
+      }
+    }
+
+    /**
+     * Waits until the writer running on `thread` has exited. Returns `firstFailure` if defined,
+     * else the first failure of the periodic warnings and interrupts, which do not end the wait.
+     */
+    private def awaitExit(thread: Thread, firstFailure: Option[Throwable]): Option[Throwable] = {
+      // Wait without a time bound. The completion listeners that run next free memory that
+      // the writer may still access: even a writer blocked in upstream I/O that ignores
+      // interrupts adds the row it gets next to the HybridRowQueue. Giving up here would allow
+      // that use-after-free, and failing this listener would not stop those listeners either.
+      // The price is that task completion is held for as long as such upstream I/O blocks.
+      //
+      // The writer is interrupted again on every warning, in case code it called consumed the
+      // interrupt without stopping the writer, e.g. an upstream iterator that caught an
+      // InterruptedException. The writer would then go on and block in channel.write, since
+      // nothing reads the Python worker's output anymore. The warnings keep their own schedule,
+      // so that interrupts of this thread do not put them off.
+      //
+      // An interrupt of this thread that arrives during the wait (e.g. a task kill) does not stop
+      // it and is not passed on (see stopAndAwaitExit): the kill is already recorded in the
+      // TaskContext, and the flag would make the blocking channel and lock operations of the
+      // completion listeners that run next fail and skip cleanup.
+      val intervalNs = TimeUnit.MILLISECONDS.toNanos(warnIntervalMs)
+      val startNs = System.nanoTime()
+      var nextWarningNs = startNs + intervalNs
+      var warned = false
+      var failure = firstFailure
+      while (exited.getCount > 0) {
+        try {
+          val remainingNs = nextWarningNs - System.nanoTime()
+          if (remainingNs > 0) {
+            exited.await(remainingNs, TimeUnit.NANOSECONDS)
+          } else {
+            // Best effort: a failure here, e.g. an OutOfMemoryError while logging, must not end
+            // the wait, and a failing warning must not skip the interrupt. The wait itself is not
+            // covered, so that a lasting failure does not spin.
+            try {
+              warnStillWaiting(thread, startNs, withStackTrace = !warned)
+              warned = true
+            } catch {
+              case t: Throwable if !t.isInstanceOf[InterruptedException] =>
+                failure = failure.orElse(Some(t))
+            }
+            try {
+              val interruptFailure = synchronized {
+                state match {
+                  case PipelinedWriterRunning(_) => interruptWriter(thread)
+                  case _ => None
+                }
+              }
+              failure = failure.orElse(interruptFailure)
+            } catch {
+              case t: Throwable if !t.isInstanceOf[InterruptedException] =>
+                failure = failure.orElse(Some(t))
+            }
+            nextWarningNs = System.nanoTime() + intervalNs
+          }
+        } catch {
+          case _: InterruptedException => // Keep waiting; see above.
+        }
+      }
+      failure
+    }
+
+    /**
+     * Logs that the wait for the writer running on `thread` goes on. With `withStackTrace`, also
+     * logs where the writer is, taken outside the lock and dropped if the writer exited
+     * meanwhile, since the pool thread may already run something else.
+     */
+    private def warnStillWaiting(thread: Thread, startNs: Long, withStackTrace: Boolean): Unit = {
+      val stackTrace = if (withStackTrace) Some(thread.getStackTrace) else None
+      if (exited.getCount > 0) {
+        val waitedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)
+        val message = log"Still waiting for the pipelined Python writer of " +
+          log"${MDC(TASK_NAME, taskName)} on thread ${MDC(THREAD_NAME, thread.getName)} to " +
+          log"exit after ${MDC(TOTAL_TIME, waitedMs)} ms; task completion cleanup is " +
+          log"blocked until it does. A writer blocked in I/O that ignores interrupts keeps it " +
+          log"blocked until that I/O returns."
+        stackTrace match {
+          case Some(trace) =>
+            val writerStack = new Exception(s"Stack trace of thread ${thread.getName}")
+            writerStack.setStackTrace(trace)
+            logWarning(message, writerStack)
+          case None =>
+            logWarning(message)
+        }
+      }
+    }
+  }
+
   private[spark] lazy val faultHandlerLogDir = Utils.createTempDir(namePrefix = "faulthandler")
 
   /**
@@ -539,26 +799,8 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
     worker.channel.configureBlocking(true)
     worker.refresh() // re-initializes (no selector in blocking mode)
 
-    val writerRunnable = new PipelinedWriterRunnable(worker, writer, bufferSize, context)
-    val writerFuture = BasePythonRunner.pipelinedWriterThreadPool.submit(writerRunnable)
-
-    // Wait for the writer to actually exit before letting subsequent task completion listeners
-    // run. Subsequent listeners (registered earlier, executed later under LIFO) free off-heap
-    // memory backing the input rows; if the writer is still serializing such a row when free
-    // happens, we get a use-after-free segfault (SPARK-33277). cancel(true) is enough to unblock
-    // a writer stuck on channel.write (JDK closes the SocketChannel and throws
-    // ClosedByInterruptException on interrupt), so this get() returns promptly in normal cases;
-    // the worst case is a bounded wait for the writer to finish serializing the current row or
-    // batch and observe the interrupt flag at the top of its loop.
-    context.addTaskCompletionListener[Unit] { _ =>
-      writerFuture.cancel(true)
-      try {
-        writerFuture.get()
-      } catch {
-        case _: CancellationException | _: ExecutionException | _: InterruptedException =>
-          // Expected: cancel(true) raced ahead, or writer exited via _exception path.
-      }
-    }
+    BasePythonRunner.startPipelinedWriter(
+      new PipelinedWriterRunnable(worker, writer, bufferSize, context), context)
 
     // Unix domain socket channels expose no java.net.Socket, so socket() throws
     // UnsupportedOperationException and SO_TIMEOUT-based idle detection is unavailable.
@@ -1327,13 +1569,20 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
     private val parentInputFileBlockHolder = InputFileBlockHolder.getThreadLocalValue()
 
     override def run(): Unit = {
-      // Propagate TaskContext and InputFileBlockHolder to the pool thread so that
-      // upstream operators work correctly.
-      TaskContext.setTaskContext(context)
-      InputFileBlockHolder.setThreadLocalValue(parentInputFileBlockHolder)
-      val bufferStream = new DirectByteBufferOutputStream(bufferSize)
-      var dataOut = new DataOutputStream(bufferStream)
+      var bufferStream: DirectByteBufferOutputStream = null
       try {
+        // Propagate TaskContext and InputFileBlockHolder to the pool thread so that
+        // upstream operators work correctly.
+        TaskContext.setTaskContext(context)
+        InputFileBlockHolder.setThreadLocalValue(parentInputFileBlockHolder)
+        bufferStream = new DirectByteBufferOutputStream(bufferSize)
+        // The writer writes through a stream that does not close bufferStream: the Arrow writers
+        // write through an interruptible channel, which the thread stopping this writer would
+        // otherwise close, freeing the buffer while this thread still copies into it (see
+        // CloseShieldOutputStream). bufferStream is closed only in the finally below.
+        val writerStream = new CloseShieldOutputStream(bufferStream)
+        var dataOut = new DataOutputStream(writerStream)
+
         // Write command/metadata (partition index, task context, broadcasts, UDF definition).
         writer.open(dataOut)
         flushToSocket(bufferStream)
@@ -1349,21 +1598,22 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
             flushToSocket(bufferStream)
             // Like ReaderInputStream, use a new stream for every buffer. The writers measure
             // pythonDataSent with DataOutputStream.size(), which saturates at Int.MaxValue.
-            dataOut = new DataOutputStream(bufferStream)
+            dataOut = new DataOutputStream(writerStream)
           }
         }
       } catch {
         case _: InterruptedException =>
-          // Task cancelled via Future.cancel(true)
+          // Interrupted by the task completion listener that stops the writer.
           Thread.currentThread().interrupt()
         case _: java.nio.channels.ClosedByInterruptException =>
-          // Task cancelled while blocked in channel.write(). The channel is
-          // automatically closed by the JVM, which will cause Python to receive
-          // EOF and the reader thread to get IOException.
+          // Interrupted the same way, during a write to an interruptible channel, which the JDK
+          // closes: worker.channel in flushToSocket, or the Channels.newChannel(dataOut) that the
+          // Arrow writers write through, in which case the socket stays open (see
+          // CloseShieldOutputStream).
           Thread.currentThread().interrupt()
-        case NonFatal(t) =>
+        case t: Throwable =>
           // InterruptedException and ClosedByInterruptException are matched above; what
-          // remains here is genuine non-fatal failure that needs to be propagated to the
+          // remains here is genuine failure that needs to be propagated to the
           // reader through writer.exception + a socket EOF.
           writer.setException(t)
           // Shut down the socket output so Python receives EOF and terminates.
@@ -1374,13 +1624,22 @@ private[spark] abstract class BasePythonRunner[IN, OUT](
           if (worker.channel.isConnected) {
             Utils.tryLog(worker.channel.shutdownOutput())
           }
+          // Also rethrow a fatal error (e.g. OutOfMemoryError) so that PipelinedWriterTask
+          // logs it. It is then reported twice, by that log on this thread and by the reader
+          // rethrowing it on the task thread; passing it to the reader is what keeps the task
+          // from waiting for the Python worker with no cause recorded.
+          if (!NonFatal(t)) {
+            throw t
+          }
       } finally {
         TaskContext.unset()
         InputFileBlockHolder.unset()
-        try {
-          bufferStream.close()
-        } catch {
-          case _: Exception => // ignore
+        if (bufferStream != null) {
+          try {
+            bufferStream.close()
+          } catch {
+            case _: Exception => // ignore
+          }
         }
       }
     }
diff --git a/core/src/test/scala/org/apache/spark/api/python/BasePythonRunnerSuite.scala b/core/src/test/scala/org/apache/spark/api/python/BasePythonRunnerSuite.scala
index 87a242835021..1ea85e2910bb 100644
--- a/core/src/test/scala/org/apache/spark/api/python/BasePythonRunnerSuite.scala
+++ b/core/src/test/scala/org/apache/spark/api/python/BasePythonRunnerSuite.scala
@@ -17,17 +17,24 @@
 
 package org.apache.spark.api.python
 
-import java.io.{ByteArrayInputStream, ByteArrayOutputStream, DataInputStream, DataOutputStream, EOFException}
+import java.io.{ByteArrayInputStream, ByteArrayOutputStream, Closeable, DataInputStream, DataOutputStream, EOFException}
 import java.net.{InetAddress, InetSocketAddress}
 import java.nio.ByteBuffer
-import java.nio.channels.{Channels, ServerSocketChannel, SocketChannel}
+import java.nio.channels.{Channels, ClosedByInterruptException, ServerSocketChannel, SocketChannel}
 import java.nio.charset.StandardCharsets
 import java.util.Collections
 import java.util.concurrent.{CountDownLatch, TimeUnit}
+import java.util.concurrent.atomic.{AtomicInteger, AtomicReference}
 
 import scala.collection.mutable.ArrayBuffer
+import scala.concurrent.duration._
+
+import com.google.common.util.concurrent.Uninterruptibles
+import org.apache.logging.log4j.Level
+import org.scalatest.concurrent.Eventually.{eventually, timeout}
 
 import org.apache.spark.{SharedSparkContext, SparkEnv, SparkException, SparkFunSuite, TaskContext}
+import org.apache.spark.util.TaskCompletionListener
 
 class BasePythonRunnerSuite extends SparkFunSuite with SharedSparkContext {
 
@@ -56,6 +63,577 @@ class BasePythonRunnerSuite extends SparkFunSuite with SharedSparkContext {
     }
   }
 
+  /**
+   * A writer that, once started, runs `onStart` and then keeps running until `release` is
+   * counted down, ignoring interrupts the way a writer in the middle of copying a row into a
+   * HybridRowQueue page does.
+   */
+  private class UninterruptibleWriter(
+      onStart: UninterruptibleWriter => Unit = _ => ()) extends Runnable {
+    val started = new CountDownLatch(1)
+    val release = new CountDownLatch(1)
+    @volatile var exited = false
+
+    override def run(): Unit = {
+      try {
+        onStart(this)
+        started.countDown()
+        awaitIgnoringInterrupts(release)
+      } finally {
+        exited = true
+      }
+    }
+  }
+
+  /** Waits for `latch`, ignoring interrupts like a writer in the middle of a row copy. */
+  private def awaitIgnoringInterrupts(latch: CountDownLatch): Unit =
+    Uninterruptibles.awaitUninterruptibly(latch)
+
+  /** Blocks until this thread is interrupted, like a writer that exits on an interrupt. */
+  private def awaitInterrupt(): Unit = {
+    try {
+      new CountDownLatch(1).await()
+    } catch {
+      case _: InterruptedException =>
+    }
+  }
+
+  /** Adds a completion listener that records whether `writer` had exited when it ran. */
+  private def addCleanupListener(
+      context: TaskContext,
+      writer: UninterruptibleWriter): AtomicReference[Option[Boolean]] = {
+    val exitedBeforeCleanup = new AtomicReference[Option[Boolean]](None)
+    context.addTaskCompletionListener[Unit] { _ => exitedBeforeCleanup.set(Some(writer.exited)) }
+    exitedBeforeCleanup
+  }
+
+  /**
+   * Adds a pre-completion listener that runs right before the one added by
+   * `startPipelinedWriter`, so that the test knows task completion has reached the writer.
+   */
+  private def addReachedListener(context: TaskContext): CountDownLatch = {
+    val reached = new CountDownLatch(1)
+    context.addTaskPreCompletionListener(new TaskCompletionListener {
+      override def onTaskCompletion(context: TaskContext): Unit = reached.countDown()
+    })
+    reached
+  }
+
+  private def startThread(body: => Unit): Thread = {
+    val thread = new Thread(() => body)
+    thread.setDaemon(true)
+    thread.start()
+    thread
+  }
+
+  test("SPARK-60113: task completion waits for the pipelined writer to exit") {
+    val context = TaskContext.empty()
+    val stopListenerAdded = new CountDownLatch(1)
+    @volatile var cleanupAddedByWriter: AtomicReference[Option[Boolean]] = null
+    val writer = new UninterruptibleWriter(self => {
+      // Like an upstream reader that adds its close listener when the writer first pulls it.
+      // Waits so that it is always added after the stop listener, as when the writer pulls its
+      // input after startPipelinedWriter returns, which an ordinary completion listener for the
+      // stop would let run first.
+      awaitIgnoringInterrupts(stopListenerAdded)
+      cleanupAddedByWriter = addCleanupListener(context, self)
+    })
+    // Like the listener that closes the HybridRowQueue, added on the task thread before the
+    // writer starts.
+    val cleanupAddedBefore = addCleanupListener(context, writer)
+    var completion: Thread = null
+    try {
+      BasePythonRunner.startPipelinedWriter(writer, context)
+      stopListenerAdded.countDown()
+      assert(writer.started.await(1, TimeUnit.MINUTES))
+      val reached = addReachedListener(context)
+
+      completion = startThread(context.markTaskCompleted(None))
+      assert(reached.await(1, TimeUnit.MINUTES))
+      // Task completion must stay blocked while the writer is still running.
+      completion.join(500)
+      assert(completion.isAlive)
+      assert(cleanupAddedBefore.get.isEmpty)
+      assert(cleanupAddedByWriter.get.isEmpty)
+    } finally {
+      stopListenerAdded.countDown()
+      writer.release.countDown()
+    }
+    completion.join(TimeUnit.MINUTES.toMillis(1))
+    assert(!completion.isAlive)
+    assert(cleanupAddedBefore.get === Some(true))
+    assert(cleanupAddedByWriter.get === Some(true))
+  }
+
+  test("SPARK-60113: a listener the writer adds once completion has started waits for it") {
+    val context = TaskContext.empty()
+    val addNow = new CountDownLatch(1)
+    val added = new CountDownLatch(1)
+    // Whether the writer had exited, and the thread, when the listener added by the writer ran.
+    val lateCleanup = new AtomicReference[Option[(Boolean, Thread)]](None)
+    val writerStarted = new CountDownLatch(1)
+    val release = new CountDownLatch(1)
+    // Like a writer that adds a listener when it pulls more input after completion has started.
+    val lateWriter: Runnable = new Runnable {
+      @volatile var exited = false
+      override def run(): Unit = {
+        try {
+          writerStarted.countDown()
+          awaitIgnoringInterrupts(addNow)
+          context.addTaskCompletionListener[Unit] { _ =>
+            lateCleanup.set(Some((exited, Thread.currentThread())))
+          }
+          added.countDown()
+          awaitIgnoringInterrupts(release)
+        } finally {
+          exited = true
+        }
+      }
+    }
+    var completion: Thread = null
+    try {
+      BasePythonRunner.startPipelinedWriter(lateWriter, context)
+      assert(writerStarted.await(1, TimeUnit.MINUTES))
+      val reached = addReachedListener(context)
+
+      completion = startThread(context.markTaskCompleted(None))
+      assert(reached.await(1, TimeUnit.MINUTES))
+      addNow.countDown()
+      assert(added.await(1, TimeUnit.MINUTES))
+      // The writer thread only queued the listener: task completion still waits for the writer.
+      completion.join(500)
+      assert(completion.isAlive)
+      assert(lateCleanup.get.isEmpty)
+    } finally {
+      addNow.countDown()
+      release.countDown()
+    }
+    completion.join(TimeUnit.MINUTES.toMillis(1))
+    assert(!completion.isAlive)
+    assert(lateCleanup.get === Some((true, completion)))
+  }
+
+  test("SPARK-60113: an interrupt does not stop the wait and is not passed to later listeners") {
+    val context = TaskContext.empty()
+    val writer = new UninterruptibleWriter
+    val cleanup = addCleanupListener(context, writer)
+    val interruptedInCleanup = new AtomicReference[Option[Boolean]](None)
+    context.addTaskCompletionListener[Unit] { _ =>
+      interruptedInCleanup.set(Some(Thread.currentThread().isInterrupted))
+    }
+    var completion: Thread = null
+    try {
+      BasePythonRunner.startPipelinedWriter(writer, context)
+      assert(writer.started.await(1, TimeUnit.MINUTES))
+      val reached = addReachedListener(context)
+
+      completion = startThread(context.markTaskCompleted(None))
+      assert(reached.await(1, TimeUnit.MINUTES))
+      // Interrupt the completion thread once it blocks in the wait, e.g. a task kill that lands
+      // while the listeners run.
+      eventually(timeout(1.minute)) {
+        assert(completion.getState == Thread.State.TIMED_WAITING)
+      }
+      completion.interrupt()
+      completion.join(500)
+      assert(completion.isAlive)
+      assert(cleanup.get.isEmpty)
+    } finally {
+      writer.release.countDown()
+    }
+    completion.join(TimeUnit.MINUTES.toMillis(1))
+    assert(!completion.isAlive)
+    assert(cleanup.get === Some(true))
+    assert(interruptedInCleanup.get === Some(false))
+  }
+
+  test("SPARK-60113: a writer started after the task completed never runs") {
+    // Like startPipelinedWriter called on a helper thread (e.g. PipedRDD's stdin writer) after
+    // the task completed: the stop listener runs at once and keeps the writer from starting.
+    val context = TaskContext.empty()
+    context.markTaskCompleted(None)
+    val ran = new CountDownLatch(1)
+    BasePythonRunner.startPipelinedWriter(() => ran.countDown(), context)
+    assert(!ran.await(500, TimeUnit.MILLISECONDS))
+  }
+
+  test("SPARK-60113: a writer started while another thread runs the listeners never runs") {
+    // Like startPipelinedWriter called on a helper thread (e.g. PipedRDD's stdin writer) after
+    // the task completed, while the completing thread runs the completion listeners: the stop
+    // listener is then only queued, so the writer must not be submitted at all.
+    val context = TaskContext.empty()
+    val ran = new CountDownLatch(1)
+    context.addTaskCompletionListener[Unit] { _ =>
+      val helper =
+        startThread(BasePythonRunner.startPipelinedWriter(() => ran.countDown(), context))
+      helper.join(TimeUnit.MINUTES.toMillis(1))
+      assert(!helper.isAlive)
+    }
+    context.markTaskCompleted(None)
+    assert(!ran.await(500, TimeUnit.MILLISECONDS))
+  }
+
+  test("SPARK-60113: a failure to interrupt the writer does not end the wait") {
+    val writer = new UninterruptibleWriter
+    val writerTask = new BasePythonRunner.PipelinedWriterTask(
+      writer, TaskContext.empty(), "test task", warnIntervalMs = 100)
+    val interruptFailure = new IllegalStateException("cannot interrupt")
+    // The first interrupt and the ones on every warning fail.
+    val writerThread = new Thread(() => writerTask.run()) {
+      override def interrupt(): Unit = throw interruptFailure
+    }
+    writerThread.setDaemon(true)
+    writerThread.start()
+    val stopFailure = new AtomicReference[Option[Throwable]](None)
+    var stopper: Thread = null
+    try {
+      assert(writer.started.await(1, TimeUnit.MINUTES))
+      stopper = startThread {
+        try {
+          writerTask.stopAndAwaitExit()
+        } catch {
+          case t: Throwable => stopFailure.set(Some(t))
+        }
+      }
+      // Several warnings pass, and their interrupts fail, while the writer still runs.
+      stopper.join(500)
+      assert(stopper.isAlive)
+      assert(stopFailure.get.isEmpty)
+    } finally {
+      writer.release.countDown()
+    }
+    stopper.join(TimeUnit.MINUTES.toMillis(1))
+    assert(!stopper.isAlive)
+    // Thrown once the writer has exited.
+    assert(writer.exited)
+    assert(stopFailure.get === Some(interruptFailure))
+    writerThread.join(TimeUnit.MINUTES.toMillis(1))
+  }
+
+  test("SPARK-60113: a pipelined writer stopped before it starts never runs") {
+    val writer = new UninterruptibleWriter
+    val writerTask =
+      new BasePythonRunner.PipelinedWriterTask(writer, TaskContext.empty(), "test task")
+    // The pool has not started the writer yet: stopping must not wait for it.
+    writerTask.stopAndAwaitExit()
+    // Stopping again does not wait either.
+    writerTask.stopAndAwaitExit()
+    // Even if the pool thread reaches the task afterwards, the writer must not run. Release it
+    // up front so that a writer that wrongly runs fails the test instead of hanging it.
+    writer.release.countDown()
+    writerTask.run()
+    assert(writer.started.getCount === 1)
+    assert(!writer.exited)
+  }
+
+  test("SPARK-60113: a fatal error of the pipelined writer is logged") {
+    val writerTask = new BasePythonRunner.PipelinedWriterTask(
+      // scalastyle:off throwerror
+      () => throw new LinkageError("fatal writer error"), TaskContext.empty(), "test task")
+      // scalastyle:on throwerror
+    val logAppender = new LogAppender("pipelined writer failure")
+    withLogAppender(logAppender) {
+      intercept[LinkageError] {
+        writerTask.run()
+      }
+    }
+    assert(logAppender.loggingEvents.exists { event =>
+      event.getLevel == Level.ERROR &&
+        event.getMessage.getFormattedMessage.contains("Pipelined Python writer of test task") &&
+        event.getThrown.getMessage == "fatal writer error"
+    })
+    // The writer has exited, so stopping does not wait.
+    writerTask.stopAndAwaitExit()
+  }
+
+  test("SPARK-60113: stopping on the writer thread itself does not wait for the writer") {
+    val taskRef = new AtomicReference[BasePythonRunner.PipelinedWriterTask]()
+    val stopReturned = new CountDownLatch(1)
+    val interruptedAfterStop = new AtomicReference[Option[Boolean]](None)
+    val writerTask = new BasePythonRunner.PipelinedWriterTask(() => {
+      // Like task completion listeners handed to the writer thread while it pulls its input.
+      taskRef.get.stopAndAwaitExit()
+      interruptedAfterStop.set(Some(Thread.currentThread().isInterrupted))
+      stopReturned.countDown()
+    }, TaskContext.empty(), "test task")
+    taskRef.set(writerTask)
+    val writerThread = startThread(writerTask.run())
+    assert(stopReturned.await(1, TimeUnit.MINUTES))
+    // Stopping leaves the interrupt status of the thread it runs on as it was, so that the
+    // listeners that run next on it can clean up.
+    assert(interruptedAfterStop.get === Some(false))
+    writerThread.join(TimeUnit.MINUTES.toMillis(1))
+    assert(!writerThread.isAlive)
+    // The writer has exited, so stopping from another thread does not wait either.
+    writerTask.stopAndAwaitExit()
+  }
+
+  /**
+   * Runs a writer that consumes the first interrupt and stops at the second one, on a thread made
+   * by `newThread`, stops it, and returns the failure that stopping threw, if any. Fails if
+   * stopping does not return.
+   */
+  private def stopWriterThatConsumesAnInterrupt(
+      newThread: Runnable => Thread): (Int, Option[Throwable]) = {
+    val interrupts = new AtomicInteger(0)
+    val writerTask = new BasePythonRunner.PipelinedWriterTask(() => {
+      // Like upstream code that catches the first InterruptedException and carries on, and then
+      // blocks again (e.g. in channel.write), where the next interrupt stops it.
+      val blocker = new CountDownLatch(1)
+      var stopped = false
+      while (!stopped) {
+        try {
+          blocker.await()
+        } catch {
+          case _: InterruptedException =>
+            stopped = interrupts.incrementAndGet() >= 2
+        }
+      }
+    }, TaskContext.empty(), "test task", warnIntervalMs = 100)
+    val writerThread = newThread(() => writerTask.run())
+    writerThread.setDaemon(true)
+    writerThread.start()
+    eventually(timeout(1.minute)) {
+      assert(writerThread.getState == Thread.State.WAITING)
+    }
+
+    val stopFailure = new AtomicReference[Option[Throwable]](None)
+    val stopper = startThread {
+      try {
+        writerTask.stopAndAwaitExit()
+      } catch {
+        case t: Throwable => stopFailure.set(Some(t))
+      }
+    }
+    stopper.join(TimeUnit.MINUTES.toMillis(1))
+    assert(!stopper.isAlive)
+    writerThread.join(TimeUnit.MINUTES.toMillis(1))
+    (interrupts.get, stopFailure.get)
+  }
+
+  test("SPARK-60113: the writer is interrupted again if it consumed the interrupt") {
+    val (interrupts, stopFailure) = stopWriterThatConsumesAnInterrupt(new Thread(_))
+    assert(interrupts >= 2)
+    assert(stopFailure.isEmpty)
+  }
+
+  test("SPARK-60113: a failing warning does not skip the repeated interrupt") {
+    // The warning fails on every tick, since it takes the writer thread's stack trace.
+    val warningFailure = new IllegalStateException("cannot take the stack trace")
+    val (interrupts, stopFailure) = stopWriterThatConsumesAnInterrupt { runnable =>
+      new Thread(runnable) {
+        override def getStackTrace: Array[StackTraceElement] = throw warningFailure
+      }
+    }
+    assert(interrupts >= 2)
+    assert(stopFailure === Some(warningFailure))
+  }
+
+  test("SPARK-60113: an interrupt pending before stopping the writer is kept") {
+    // The writer never started.
+    val notStarted =
+      new BasePythonRunner.PipelinedWriterTask(() => (), TaskContext.empty(), "test task")
+    // The writer runs and exits once interrupted.
+    val running = new BasePythonRunner.PipelinedWriterTask(() => {
+      awaitInterrupt()
+    }, TaskContext.empty(), "test task")
+    val writerThread = startThread(running.run())
+    eventually(timeout(1.minute)) {
+      assert(writerThread.getState == Thread.State.WAITING)
+    }
+
+    Seq(notStarted, running).foreach { writerTask =>
+      val interruptedAfterStop = new AtomicReference[Option[Boolean]](None)
+      val stopper = startThread {
+        Thread.currentThread().interrupt()
+        writerTask.stopAndAwaitExit()
+        interruptedAfterStop.set(Some(Thread.currentThread().isInterrupted))
+      }
+      stopper.join(TimeUnit.MINUTES.toMillis(1))
+      assert(interruptedAfterStop.get === Some(true))
+    }
+    writerThread.join(TimeUnit.MINUTES.toMillis(1))
+  }
+
+  test("SPARK-60113: stopping interrupts a running writer right away") {
+    // A writer that exits once interrupted, with no warning (and so no repeated interrupt)
+    // before the test times out.
+    val writerTask = new BasePythonRunner.PipelinedWriterTask(() => {
+      awaitInterrupt()
+    }, TaskContext.empty(), "test task", warnIntervalMs = TimeUnit.MINUTES.toMillis(10))
+    val writerThread = startThread(writerTask.run())
+    eventually(timeout(1.minute)) {
+      assert(writerThread.getState == Thread.State.WAITING)
+    }
+    val stopper = startThread(writerTask.stopAndAwaitExit())
+    stopper.join(TimeUnit.MINUTES.toMillis(1))
+    assert(!stopper.isAlive)
+    writerThread.join(TimeUnit.MINUTES.toMillis(1))
+    assert(!writerThread.isAlive)
+  }
+
+  test("SPARK-60113: an interrupt that arrives while stopping the writer is not passed on") {
+    val writerTask =
+      new BasePythonRunner.PipelinedWriterTask(() => (), TaskContext.empty(), "test task")
+    val interruptedAfterStop = new AtomicReference[Option[Boolean]](None)
+    var stopper: Thread = null
+    writerTask.synchronized {
+      // Blocks on the task's lock, where the interrupt then arrives.
+      stopper = startThread {
+        writerTask.stopAndAwaitExit()
+        interruptedAfterStop.set(Some(Thread.currentThread().isInterrupted))
+      }
+      eventually(timeout(1.minute)) {
+        assert(stopper.getState == Thread.State.BLOCKED)
+      }
+      stopper.interrupt()
+    }
+    stopper.join(TimeUnit.MINUTES.toMillis(1))
+    assert(!stopper.isAlive)
+    assert(interruptedAfterStop.get === Some(false))
+  }
+
+  test("SPARK-60113: the writer is not interrupted while it creates a resource uninterruptibly") {
+    val context = TaskContext.empty()
+    val inBuilder = new CountDownLatch(1)
+    val releaseBuilder = new CountDownLatch(1)
+    val interruptedInBuilder = new AtomicReference[Option[Boolean]](None)
+    val writerTask = new BasePythonRunner.PipelinedWriterTask(() => {
+      // Like an upstream scan that opens a file through createResourceUninterruptibly.
+      context.createResourceUninterruptibly {
+        inBuilder.countDown()
+        var interrupted = false
+        var done = false
+        while (!done) {
+          try {
+            done = releaseBuilder.await(1, TimeUnit.MINUTES)
+          } catch {
+            case _: InterruptedException => interrupted = true
+          }
+        }
+        interruptedInBuilder.set(Some(interrupted || Thread.currentThread().isInterrupted))
+        new Closeable {
+          override def close(): Unit = {}
+        }
+      }
+      // Then blocks until it is interrupted.
+      awaitInterrupt()
+    }, context, "test task", warnIntervalMs = 100)
+    val writerThread = startThread(writerTask.run())
+    var stopper: Thread = null
+    try {
+      assert(inBuilder.await(1, TimeUnit.MINUTES))
+      stopper = startThread(writerTask.stopAndAwaitExit())
+      // Several warnings pass while the writer is in the builder.
+      stopper.join(500)
+      assert(stopper.isAlive)
+    } finally {
+      releaseBuilder.countDown()
+    }
+    stopper.join(TimeUnit.MINUTES.toMillis(1))
+    assert(!stopper.isAlive)
+    assert(interruptedInBuilder.get === Some(false))
+    writerThread.join(TimeUnit.MINUTES.toMillis(1))
+  }
+
+  /**
+   * Runs a real `PipelinedWriterRunnable` whose input is written by `writeNextInput`, against a
+   * socket pair standing in for the Python worker, using the suite's shared SparkContext. Reads
+   * from the Python side of the socket through its input stream time out after a minute. Then
+   * calls `check` with the writer and the Python side of the socket. `run` runs the runnable and
+   * may expect it to throw.
+   */
+  private def withPipelinedWriterRunnable(
+      writeNextInput: DataOutputStream => Boolean)(
+      run: Runnable => Unit)(
+      check: (BasePythonRunner[Array[Byte], Array[Byte]]#Writer, SocketChannel) => Unit): Unit = {
+    val func = SimplePythonFunction(
+      Seq.empty, Collections.emptyMap(), Collections.emptyList(), "python3", "3",
+      Collections.emptyList(), null)
+    val runner = new PythonRunner(Seq(ChainedPythonFunctions(Seq(func))), None)
+    val server = ServerSocketChannel.open()
+    try {
+      server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress, 0))
+      val channel = SocketChannel.open(server.getLocalAddress)
+      val pythonSide = server.accept()
+      try {
+        // So that reads through the socket adaptor fail instead of blocking forever.
+        pythonSide.socket().setSoTimeout(TimeUnit.MINUTES.toMillis(1).toInt)
+        val context = TaskContext.empty()
+        val worker = PythonWorker(channel)
+        val writer = new runner.Writer(SparkEnv.get, worker, Iterator.empty, 0, context) {
+          override def open(dataOut: DataOutputStream): Unit = {}
+          override protected def writeCommand(dataOut: DataOutputStream): Unit = {}
+          override def writeNextInputToStream(dataOut: DataOutputStream): Boolean =
+            writeNextInput(dataOut)
+          override def close(dataOut: DataOutputStream): Unit = {}
+        }
+        run(new runner.PipelinedWriterRunnable(worker, writer, 1024, context))
+        check(writer, pythonSide)
+      } finally {
+        pythonSide.close()
+        channel.close()
+      }
+    } finally {
+      server.close()
+    }
+  }
+
+  test("SPARK-60113: a fatal error of the pipelined writer is passed to the reader") {
+    withPipelinedWriterRunnable { _ =>
+      // scalastyle:off throwerror
+      throw new LinkageError("fatal writer error")
+      // scalastyle:on throwerror
+    } { runnable =>
+      intercept[LinkageError] {
+        runnable.run()
+      }
+    } { (writer, pythonSide) =>
+      // The reader rethrows the error instead of waiting for the Python worker, which sees the
+      // end of its input.
+      assert(writer.exception.map(_.getMessage) === Some("fatal writer error"))
+      assert(pythonSide.socket().getInputStream.read() === -1)
+    }
+  }
+
+  test("SPARK-60113: an interrupted Arrow-style write leaves the writer's buffer usable") {
+    var calls = 0
+    withPipelinedWriterRunnable { dataOut =>
+      calls += 1
+      if (calls == 1) {
+        // Fills the first buffer, so that the interrupted write below goes through the stream
+        // that the writer creates after flushing it.
+        dataOut.write(new Array[Byte](2000))
+        true
+      } else {
+        // Like an Arrow writer, which writes through Channels.newChannel(dataOut), interrupted by
+        // the thread that stops the writer.
+        Thread.currentThread().interrupt()
+        try {
+          Channels.newChannel(dataOut).write(ByteBuffer.wrap(Array[Byte](1, 2)))
+        } catch {
+          case _: ClosedByInterruptException =>
+        } finally {
+          Thread.interrupted()
+        }
+        // Fails if the interrupt freed the buffer behind dataOut.
+        dataOut.writeInt(42)
+        false
+      }
+    } { runnable =>
+      runnable.run()
+    } { (writer, pythonSide) =>
+      assert(writer.exception.isEmpty)
+      val input = new DataInputStream(pythonSide.socket().getInputStream)
+      input.readFully(new Array[Byte](2000))
+      // The bytes copied by the interrupted write, which the JDK copies after closing the
+      // stream, and then the next write.
+      assert(input.readByte() === 1)
+      assert(input.readByte() === 2)
+      assert(input.readInt() === 42)
+    }
+  }
+
   test("SPARK-60343: pipelined writer uses a new DataOutputStream for every buffer") {
     val func = SimplePythonFunction(Seq.empty, Collections.emptyMap(), Collections.emptyList(),
       "python3", "3", Collections.emptyList(), null)
diff --git a/core/src/test/scala/org/apache/spark/scheduler/TaskContextSuite.scala b/core/src/test/scala/org/apache/spark/scheduler/TaskContextSuite.scala
index d9bfbe2b5f24..a0b59f453a6e 100644
--- a/core/src/test/scala/org/apache/spark/scheduler/TaskContextSuite.scala
+++ b/core/src/test/scala/org/apache/spark/scheduler/TaskContextSuite.scala
@@ -18,10 +18,11 @@
 package org.apache.spark.scheduler
 
 import java.util.Properties
-import java.util.concurrent.Semaphore
-import java.util.concurrent.atomic.AtomicInteger
+import java.util.concurrent.{ConcurrentLinkedQueue, CountDownLatch, Semaphore, TimeUnit}
+import java.util.concurrent.atomic.{AtomicInteger, AtomicReference}
 
 import scala.collection.mutable.ArrayBuffer
+import scala.jdk.CollectionConverters._
 
 import org.mockito.ArgumentMatchers.{any, eq => mockitoEq}
 import org.mockito.Mockito._
@@ -757,6 +758,179 @@ class TaskContextSuite extends SparkFunSuite with BeforeAndAfter with LocalSpark
     assert(invocationOrder === Seq("C", "B", "A", "D"))
   }
 
+  test("SPARK-60113: pre-completion listeners run before all completion listeners") {
+    val context = TaskContext.empty()
+    val invocationOrder = ArrayBuffer.empty[String]
+
+    def makeLoggingListener(id: String): TaskCompletionListener = new TaskCompletionListener {
+      override def onTaskCompletion(context: TaskContext): Unit = {
+        invocationOrder += id
+      }
+    }
+    context.addTaskCompletionListener(makeLoggingListener("A"))
+    context.addTaskPreCompletionListener(makeLoggingListener("P1"))
+    context.addTaskPreCompletionListener(makeLoggingListener("P2"))
+    // Added after the pre-completion listeners, e.g. lazily by the thread they stop. Had P1 and
+    // P2 been added with addTaskCompletionListener, B would run before them.
+    context.addTaskCompletionListener(makeLoggingListener("B"))
+
+    context.markTaskCompleted(None)
+    assert(invocationOrder === Seq("P2", "P1", "B", "A"))
+    // Called immediately once the task has completed, like completion listeners.
+    context.addTaskPreCompletionListener(makeLoggingListener("P3"))
+    assert(invocationOrder === Seq("P2", "P1", "B", "A", "P3"))
+  }
+
+  test("SPARK-60113: completion listeners run even if a pre-completion listener fails") {
+    val context = TaskContext.empty()
+    val listener = mock(classOf[TaskCompletionListener])
+    context.addTaskCompletionListener(listener)
+    context.addTaskPreCompletionListener(new TaskCompletionListener {
+      override def onTaskCompletion(context: TaskContext): Unit = throw new Exception("pre")
+    })
+
+    val e = intercept[TaskCompletionListenerException] {
+      context.markTaskCompleted(None)
+    }
+    assert(e.getMessage.contains("pre"))
+    verify(listener, times(1)).onTaskCompletion(any())
+    assert(context.isFailed())
+  }
+
+  test("SPARK-60113: failures of pre-completion and completion listeners are both reported") {
+    val context = TaskContext.empty()
+    val post = new Exception("post")
+    val pre = new Exception("pre")
+    context.addTaskCompletionListener(new TaskCompletionListener {
+      override def onTaskCompletion(context: TaskContext): Unit = throw post
+    })
+    context.addTaskPreCompletionListener(new TaskCompletionListener {
+      override def onTaskCompletion(context: TaskContext): Unit = throw pre
+    })
+
+    val e = intercept[TaskCompletionListenerException] {
+      context.markTaskCompleted(None)
+    }
+    assert(e.getMessage.contains("pre"))
+    assert(e.getMessage.contains("post"))
+    // The completion listener's own failure, not the exception that wraps it.
+    assert(e.getSuppressed.toSeq === Seq(pre, post))
+  }
+
+  test("SPARK-60113: a pre-completion listener added after completion runs as a completion one") {
+    val context = TaskContext.empty()
+    val invocations = new ConcurrentLinkedQueue[(String, Thread)]()
+    context.addTaskCompletionListener(loggingListener(invocations, "A"))
+    context.addTaskCompletionListener(new TaskCompletionListener {
+      override def onTaskCompletion(context: TaskContext): Unit = {
+        invocations.add(("B", Thread.currentThread()))
+        // Added from a second thread while this thread runs the completion listeners: it is
+        // queued like a completion listener, and this thread runs it next, after this one.
+        val thread = new Thread(() => {
+          context.addTaskPreCompletionListener(loggingListener(invocations, "P"))
+        })
+        thread.setDaemon(true)
+        thread.start()
+        thread.join(TimeUnit.MINUTES.toMillis(1))
+        assert(!thread.isAlive)
+        assert(invocations.asScala.toSeq === Seq(("B", Thread.currentThread())))
+      }
+    })
+
+    context.markTaskCompleted(None)
+    val completing = Thread.currentThread()
+    assert(invocations.asScala.toSeq ===
+      Seq(("B", completing), ("P", completing), ("A", completing)))
+    // Added once all listeners have run: it runs right away on the adding thread.
+    context.addTaskPreCompletionListener(loggingListener(invocations, "Q"))
+    assert(invocations.asScala.toSeq.last === (("Q", completing)))
+  }
+
+  test("SPARK-60113: a failing pre-completion listener added after completion fails the task") {
+    val context = TaskContext.empty()
+    context.markTaskCompleted(None)
+    val error = new Exception("late pre-completion listener")
+    val e = intercept[TaskCompletionListenerException] {
+      context.addTaskPreCompletionListener(new TaskCompletionListener {
+        override def onTaskCompletion(context: TaskContext): Unit = throw error
+      })
+    }
+    assert(e.getMessage.contains("late pre-completion listener"))
+    assert(e.getSuppressed.toSeq === Seq(error))
+    assert(context.isFailed())
+  }
+
+  test("SPARK-60113: listeners added while pre-completion listeners run are queued") {
+    val context = TaskContext.empty()
+    val invocations = new ConcurrentLinkedQueue[(String, Thread)]()
+    context.addTaskCompletionListener(loggingListener(invocations, "A"))
+    val completion = completeWhilePreCompletionListenerBlocks(context) {
+      // Like the writer adding listeners lazily while the pre-completion listener waits for it:
+      // the task has not completed yet, so these calls only queue them, and the adding thread
+      // cannot start running the listeners.
+      context.addTaskCompletionListener(loggingListener(invocations, "B"))
+      context.addTaskPreCompletionListener(loggingListener(invocations, "P"))
+      assert(!context.isCompleted())
+      assert(invocations.isEmpty)
+    }
+    assert(context.isCompleted())
+    assert(invocations.asScala.toSeq ===
+      Seq(("P", completion), ("B", completion), ("A", completion)))
+  }
+
+  test("SPARK-60113: failure listeners run while pre-completion listeners run") {
+    val context = TaskContext.empty()
+    val failureListenerThread = new AtomicReference[Thread]()
+    context.addTaskFailureListener(new TaskFailureListener {
+      override def onTaskFailure(context: TaskContext, error: Throwable): Unit =
+        failureListenerThread.set(Thread.currentThread())
+    })
+    completeWhilePreCompletionListenerBlocks(context) {
+      // E.g. a kill whose interrupt listener fails while the pre-completion listener waits for a
+      // writer. This thread is not held up by the waiting listener and runs the failure listeners.
+      context.markTaskFailed(new Exception("failed elsewhere"))
+      assert(failureListenerThread.get eq Thread.currentThread())
+    }
+  }
+
+  /** A completion listener that records its id and the thread it runs on in `invocations`. */
+  private def loggingListener(
+      invocations: ConcurrentLinkedQueue[(String, Thread)],
+      id: String): TaskCompletionListener = new TaskCompletionListener {
+    override def onTaskCompletion(context: TaskContext): Unit = {
+      invocations.add((id, Thread.currentThread()))
+    }
+  }
+
+  /**
+   * Marks `context` completed on a new thread, runs `body` while a pre-completion listener of it
+   * blocks, like the one that waits for a pipelined Python UDF writer to exit, and returns that
+   * thread once the completion has finished.
+   */
+  private def completeWhilePreCompletionListenerBlocks(context: TaskContextImpl)(
+      body: => Unit): Thread = {
+    val inPreCompletion = new CountDownLatch(1)
+    val release = new CountDownLatch(1)
+    context.addTaskPreCompletionListener(new TaskCompletionListener {
+      override def onTaskCompletion(context: TaskContext): Unit = {
+        inPreCompletion.countDown()
+        release.await(1, TimeUnit.MINUTES)
+      }
+    })
+    val completion = new Thread(() => context.markTaskCompleted(None))
+    completion.setDaemon(true)
+    completion.start()
+    try {
+      assert(inPreCompletion.await(1, TimeUnit.MINUTES))
+      body
+    } finally {
+      release.countDown()
+    }
+    completion.join(TimeUnit.MINUTES.toMillis(1))
+    assert(!completion.isAlive)
+    completion
+  }
+
   test("SPARK-46480: Add isFailed in TaskContext") {
     val context = TaskContext.empty()
     var isFailed = false
diff --git a/project/MimaExcludes.scala b/project/MimaExcludes.scala
index d3447361ff01..473cc851c410 100644
--- a/project/MimaExcludes.scala
+++ b/project/MimaExcludes.scala
@@ -48,6 +48,8 @@ object MimaExcludes {
 
   // Exclude rules for 4.3.x from 4.2.0 (add 4.3-specific filters below as needed).
   lazy val v43excludes: Seq[Problem => Boolean] = v42excludes ++ Seq(
+    // [SPARK-60113][CORE][SQL] Add TaskContext.addTaskPreCompletionListener
+    ProblemFilters.exclude[ReversedMissingMethodProblem]("org.apache.spark.TaskContext.addTaskPreCompletionListener"),
     // [SPARK-54879] Add exitCode field to ApplicationAttemptInfo
     ProblemFilters.exclude[DirectMissingMethodProblem]("org.apache.spark.status.api.v1.ApplicationAttemptInfo.tupled"),
     ProblemFilters.exclude[DirectMissingMethodProblem]("org.apache.spark.status.api.v1.ApplicationAttemptInfo.curried"),


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org