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

Yicong-Huang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new 6fc96471ae29 [SPARK-60901][PYTHON] Stop polling in the pipelined UDF 
input reader
6fc96471ae29 is described below

commit 6fc96471ae2936a2a2706eafa3100e55ea3c602c
Author: Yicong Huang <[email protected]>
AuthorDate: Thu Nov 12 01:08:18 2026 +0000

    [SPARK-60901][PYTHON] Stop polling in the pipelined UDF input reader
    
    ### What changes were proposed in this pull request?
    
    `invoke_udf` duplicated its processing path for the pipelined UDF mode 
added in SPARK-56642, with the background input reader inlined in it. This PR 
keeps one processing body (`func` -> `dump_stream` -> `close`) and moves the 
reader into a `read_in_thread(iterator, queue_depth)` context manager in 
`worker_util.py`, so pipelined mode only decides whether the input goes through 
it:
    - The reader blocks on `put` instead of `put(timeout=0.1)` with a stop 
check between attempts. The consumer sets the stop flag and then drains the 
queue on exit, so a blocked `put` is always released (follows up on 
https://github.com/apache/spark/pull/55552#discussion_r3170740296).
    - One end-of-input marker carries the reader exception, replacing the 
`reader_error` list plus sentinel pair. It now also carries non-`Exception` 
errors such as `SystemExit`, which previously ended the input silently.
    - The Arrow serializers get `flush_per_batch` from the handler when they 
are created, instead of `worker.py` setting the private `_flush_per_batch` on 
the handler's serializer.
    
    Unchanged: the input stream is never closed (worker reuse), lazy per-group 
iterators are materialized on the reader thread, reader exceptions are 
re-raised in the main thread, shutdown order and the bounded join with its 
warning are the same, and the non-pipelined path is unchanged.
    
    ### Why are the changes needed?
    
    A single processing path is simpler to maintain, and the reader can now be 
tested without a JVM. Dropping the timed retry also removes the reader's 
periodic wake-ups on a full queue.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No.
    
    ### How was this patch tested?
    
    - New `ReadInThreadTests` in `pyspark.tests.test_worker` (no JVM): a reader 
error is re-raised in the consumer, early consumer exit releases a reader 
blocked on a full queue without another read, and a join timeout warns.
    - `pyspark.sql.tests.pandas.test_pipelined_udf`, 
`pyspark.sql.tests.test_pipelined_shuffle`, 
`pyspark.sql.tests.test_python_worker_env`, `pyspark.tests.test_worker`, 
`pyspark.sql.tests.test_udf_profiler` pass.
    - ASV `bench_pipelined_udf.py` before/after (`local[1]`; one representative 
run of two, the other consistent apart from one noisy run on an unchanged 
path), no regression:
    
    ```text
    benchmark                      pipelined  before       after        diff
    time_scalar_udf  (100k)        False      62.5+-6ms    61.3+-6ms    -1.9%
    time_scalar_udf  (100k)        True       66.6+-5ms    67.2+-6ms    +0.9%
    time_scalar_udf  (1M)          False      170+-8ms     166+-10ms    -2.4%
    time_scalar_udf  (1M)          True       298+-20ms    302+-10ms    +1.3%
    time_multi_udf   (100k)        False      91.0+-8ms    86.6+-7ms    -4.8%
    time_multi_udf   (100k)        True       81.0+-10ms   78.7+-8ms    -2.8%
    time_multi_udf   (1M)          False      204+-10ms    199+-7ms     -2.5%
    time_multi_udf   (1M)          True       291+-20ms    278+-30ms    -4.5%
    time_large_data                False      597+-30ms    594+-20ms    -0.5%
    time_large_data                True       1.14+-0.03s  1.14+-0.05s   0.0%
    time_wide_row_udf (1024 cols)  False      140+-9ms     143+-7ms     +2.1%
    time_wide_row_udf (1024 cols)  True       133+-8ms     134+-7ms     +0.8%
    time_wide_row_udf (4096 cols)  False      257+-7ms     269+-7ms     +4.7%
    time_wide_row_udf (4096 cols)  True       259+-10ms    261+-8ms     +0.8%
    ```
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    
    
    Closes #60115 from Yicong-Huang/SPARK-60901.
    
    Authored-by: Yicong Huang <[email protected]>
    Signed-off-by: Yicong-Huang <[email protected]>
    
    
    skip-checks: true
---
 python/pyspark/eval_handlers/_arrow.py             |   2 +
 python/pyspark/eval_handlers/_base.py              |  13 ++-
 .../tests/test_arrow_eval_type_handlers.py         |   3 +
 .../tests/test_base_eval_type_handlers.py          |   6 ++
 python/pyspark/tests/test_worker.py                |  74 ++++++++++++-
 python/pyspark/worker.py                           | 115 +++------------------
 python/pyspark/worker_util.py                      |  86 ++++++++++++++-
 7 files changed, 195 insertions(+), 104 deletions(-)

diff --git a/python/pyspark/eval_handlers/_arrow.py 
b/python/pyspark/eval_handlers/_arrow.py
index 2480e5a21e67..7989c09cd504 100644
--- a/python/pyspark/eval_handlers/_arrow.py
+++ b/python/pyspark/eval_handlers/_arrow.py
@@ -29,6 +29,7 @@ from __future__ import annotations
 
 import inspect
 import itertools
+import os
 import time
 from collections.abc import Iterator
 from typing import TYPE_CHECKING, Any
@@ -870,6 +871,7 @@ class 
ArrowBatchedUDFArrowHandler(BatchEvalTypeHandler["pa.RecordBatch"]):
     def serializer(self) -> ArrowStreamSerializer:
         return ArrowStreamSerializer(
             write_start_stream=True,
+            flush_per_batch=os.environ.get("SPARK_PIPELINED_UDF") == "1",
             collect_timing=self._runner_conf.detailed_timing_enabled,
         )
 
diff --git a/python/pyspark/eval_handlers/_base.py 
b/python/pyspark/eval_handlers/_base.py
index 98e9c91b6830..46a7751076aa 100644
--- a/python/pyspark/eval_handlers/_base.py
+++ b/python/pyspark/eval_handlers/_base.py
@@ -22,6 +22,7 @@ package ``__init__`` and the concrete-handler submodules can 
both import it.
 """
 
 import functools
+import os
 from abc import ABCMeta, abstractmethod
 from collections.abc import Iterator
 from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generic, Optional
@@ -330,7 +331,9 @@ class 
BatchEvalTypeHandler(EvalTypeHandler["pa.RecordBatch", OutputBatch]):
 
     @property
     def serializer(self) -> Serializer:
-        return ArrowStreamSerializer(write_start_stream=True)
+        return ArrowStreamSerializer(
+            write_start_stream=True, 
flush_per_batch=os.environ.get("SPARK_PIPELINED_UDF") == "1"
+        )
 
 
 class GroupedEvalTypeHandler(EvalTypeHandler[GroupedBatch, OutputBatch]):
@@ -338,7 +341,9 @@ class GroupedEvalTypeHandler(EvalTypeHandler[GroupedBatch, 
OutputBatch]):
 
     @property
     def serializer(self) -> Serializer:
-        return ArrowStreamGroupSerializer(write_start_stream=True)
+        return ArrowStreamGroupSerializer(
+            write_start_stream=True, 
flush_per_batch=os.environ.get("SPARK_PIPELINED_UDF") == "1"
+        )
 
 
 class CoGroupedEvalTypeHandler(EvalTypeHandler[CoGroupedBatch, OutputBatch]):
@@ -346,4 +351,6 @@ class 
CoGroupedEvalTypeHandler(EvalTypeHandler[CoGroupedBatch, OutputBatch]):
 
     @property
     def serializer(self) -> Serializer:
-        return ArrowStreamCoGroupSerializer(write_start_stream=True)
+        return ArrowStreamCoGroupSerializer(
+            write_start_stream=True, 
flush_per_batch=os.environ.get("SPARK_PIPELINED_UDF") == "1"
+        )
diff --git 
a/python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py 
b/python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py
index 7022daaadb01..6ed4e8ce7f3a 100644
--- a/python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py
+++ b/python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py
@@ -202,6 +202,9 @@ class 
ArrowBatchedUDFArrowHandlerTests(ArrowEvalTypeHandlerTestCase):
     def test_serializer(self):
         handler = self._handler((lambda a: a, [0], {}, LongType()))
         self.assertIsInstance(handler.serializer, ArrowStreamSerializer)
+        for value, flush in (("0", False), ("1", True)):
+            with patch.dict(os.environ, {"SPARK_PIPELINED_UDF": value}):
+                self.assertEqual(handler.serializer._flush_per_batch, flush)
 
     def test_detailed_timing_uses_handler_gate(self):
         metrics = WorkerMetrics()
diff --git a/python/pyspark/eval_handlers/tests/test_base_eval_type_handlers.py 
b/python/pyspark/eval_handlers/tests/test_base_eval_type_handlers.py
index b3e0438569ce..6677043cebe5 100644
--- a/python/pyspark/eval_handlers/tests/test_base_eval_type_handlers.py
+++ b/python/pyspark/eval_handlers/tests/test_base_eval_type_handlers.py
@@ -106,6 +106,12 @@ class EvalTypeHandlerTests(PySparkBaseTestCase):
         self.assertIsInstance(
             _CoGrouped([], RunnerConf({}), None).serializer, 
ArrowStreamCoGroupSerializer
         )
+        # Pipelined mode flushes each output batch.
+        for handler_cls in (_Batch, _Grouped, _CoGrouped):
+            handler = handler_cls([], RunnerConf({}), None)
+            for value, flush in (("0", False), ("1", True)):
+                with patch.dict(os.environ, {"SPARK_PIPELINED_UDF": value}):
+                    self.assertEqual(handler.serializer._flush_per_batch, 
flush)
 
     def test_run_produces_output(self):
         class _Doubler(BatchEvalTypeHandler["pa.RecordBatch"]):
diff --git a/python/pyspark/tests/test_worker.py 
b/python/pyspark/tests/test_worker.py
index ea62bbf55c63..104d2406ca49 100644
--- a/python/pyspark/tests/test_worker.py
+++ b/python/pyspark/tests/test_worker.py
@@ -16,6 +16,7 @@
 #
 import importlib
 import io
+import itertools
 import json
 import os
 import signal
@@ -53,13 +54,19 @@ from pyspark.serializers import (
 )
 from pyspark.sql.types import LongType, StructField, StructType
 from pyspark.taskcontext import TaskContext
-from pyspark.testing.utils import QuietTest, ReusedPySparkTestCase, eventually
+from pyspark.testing.utils import (
+    PySparkBaseTestCase,
+    QuietTest,
+    ReusedPySparkTestCase,
+    eventually,
+)
 from pyspark.util import PythonEvalType
 from pyspark.worker_metrics import WorkerMetrics
 
 with patch.dict(os.environ, {"SPARK_PYTHON_RUNTIME": "PYTHON_WORKER"}):
     from pyspark import worker_util
     from pyspark.worker import main as worker_main
+    from pyspark.worker_util import read_in_thread
 
 
 class WorkerMetricsTests(unittest.TestCase):
@@ -152,6 +159,71 @@ class WorkerMetricsTests(unittest.TestCase):
         self.assertEqual(metrics.to_dict(), {"duration": 3})
 
 
+class ReadInThreadTests(PySparkBaseTestCase):
+    """Tests for reading the worker input in a background thread, run without 
a JVM."""
+
+    READER_NAME = "pyspark-pipelined-reader"
+
+    def assert_reader_stopped(self):
+        names = [t.name for t in threading.enumerate()]
+        self.assertNotIn(self.READER_NAME, names)
+
+    def test_source_error_is_reraised_after_preceding_items(self):
+        for error in (ValueError("source failure"), SystemExit(3)):
+            with self.subTest(error=type(error).__name__):
+
+                def source():
+                    yield 1
+                    yield 2
+                    raise error
+
+                with read_in_thread(source(), 1) as it:
+                    self.assertEqual(next(it), 1)
+                    self.assertEqual(next(it), 2)
+                    with self.assertRaises(type(error)):
+                        next(it)
+                self.assert_reader_stopped()
+
+    def test_early_exit_stops_reader_blocked_on_full_queue(self):
+        produced = []
+
+        def source():
+            for i in itertools.count():
+                produced.append(i)
+                yield i
+
+        with read_in_thread(source(), 1) as it:
+            self.assertEqual(next(it), 0)
+            # One item is queued and the reader blocks putting the next one.
+            eventually(timeout=10, catch_assertions=True)(
+                lambda: self.assertEqual(len(produced), 3)
+            )()
+        # The reader reads nothing after the stop and exits.
+        self.assertEqual(len(produced), 3)
+        self.assert_reader_stopped()
+
+    def test_warns_when_reader_does_not_exit(self):
+        release = threading.Event()
+
+        def source():
+            yield 0
+            # Simulates a read of the input stream that does not return.
+            release.wait()
+            yield 1
+
+        try:
+            with patch.object(threading.Thread, "join", lambda *args, 
**kwargs: None):
+                with self.assertWarnsRegex(RuntimeWarning, "did not exit 
within 5s"):
+                    with read_in_thread(source(), 2) as it:
+                        self.assertEqual(next(it), 0)
+        finally:
+            release.set()
+        for t in threading.enumerate():
+            if t.name == self.READER_NAME:
+                t.join(timeout=10)
+        self.assert_reader_stopped()
+
+
 class WorkerInitResponseTests(unittest.TestCase):
     """Tests for the init response the worker sends before any output, run 
without a JVM."""
 
diff --git a/python/pyspark/worker.py b/python/pyspark/worker.py
index f56b982199e6..72cb0359e1c0 100644
--- a/python/pyspark/worker.py
+++ b/python/pyspark/worker.py
@@ -27,7 +27,6 @@ import json
 import os
 import sys
 import traceback
-import warnings
 from typing import Any, BinaryIO, Optional
 
 from pyspark import shuffle
@@ -68,6 +67,7 @@ from pyspark.worker_util import (
     get_sock_file_to_executor,
     pickleSer,
     read_command,
+    read_in_thread,
     send_accumulator_updates,
     setup_broadcasts,
     setup_memory_limits,
@@ -243,111 +243,28 @@ def invoke_udf(message_receiver: SparkMessageReceiver, 
outfile: BinaryIO):
         # Fetch the input data stream
         input_data_stream = message_receiver.get_data_stream()
 
-        def process():
-            iterator = deserializer.load_stream(input_data_stream)
-            out_iter = func(split_index, iterator)
-            try:
-                serializer.dump_stream(out_iter, outfile)
-            finally:
-                if hasattr(out_iter, "close"):
-                    out_iter.close()
+        is_pipelined = os.environ.get("SPARK_PIPELINED_UDF") == "1"
+        # Pipelined reads can overlap UDF work, so mark these task reports for 
filtering.
+        metrics.set("pythonNumPipelinedTasks", int(is_pipelined))
 
-        def pipelined_process():
-            """
-            Pipelined variant of process() that pre-fetches input batches in a 
background
-            reader thread while the main thread computes the UDF and writes 
output.
-            This allows input deserialization to overlap with UDF computation.
-            """
-            import queue
-            import threading
-
-            queue_depth = 
int(os.environ.get("SPARK_PIPELINED_UDF_QUEUE_DEPTH", "2"))
-            _SENTINEL = object()
-            input_queue = queue.Queue(maxsize=queue_depth)
-            reader_error = [None]
-            # Event to signal the reader thread to stop (set by main thread on
-            # exception or completion). The reader checks this after each 
failed
-            # put attempt instead of polling with a timeout.
-            stop_event = threading.Event()
-
-            def _reader_thread():
-                try:
-                    for batch in deserializer.load_stream(input_data_stream):
-                        # Some serializers (e.g., ArrowStreamGroupSerializer) 
yield lazy
-                        # iterators that still read from the input stream. 
Materialize them here so
-                        # the main thread can consume them without touching 
the stream.
-                        if hasattr(batch, "__next__"):
-                            batch = list(batch)
-                        # Block on put, but wake up when stop_event is set.
-                        # stop_event.wait() returns immediately if already set.
-                        while not stop_event.is_set():
-                            try:
-                                input_queue.put(batch, timeout=0.1)
-                                break
-                            except queue.Full:
-                                continue
-                        if stop_event.is_set():
-                            return
-                except Exception as e:
-                    reader_error[0] = e
-                finally:
-                    # Enqueue sentinel so the consumer knows we're done.
-                    while not stop_event.is_set():
-                        try:
-                            input_queue.put(_SENTINEL, timeout=0.1)
-                            break
-                        except queue.Full:
-                            continue
-
-            t = threading.Thread(
-                target=_reader_thread, name="pyspark-pipelined-reader", 
daemon=True
-            )
-            t.start()
-
-            def _queued_iter():
-                while True:
-                    item = input_queue.get()
-                    if item is _SENTINEL:
-                        if reader_error[0] is not None:
-                            raise reader_error[0]
-                        return
-                    yield item
-
-            out_iter = func(split_index, _queued_iter())
+        def process(iterator):
+            out_iter = func(split_index, iterator)
             try:
                 serializer.dump_stream(out_iter, outfile)
             finally:
                 if hasattr(out_iter, "close"):
                     out_iter.close()
-                # Signal reader thread to stop, drain the queue so it can 
unblock,
-                # then wait for it to finish.
-                stop_event.set()
-                try:
-                    while not input_queue.empty():
-                        input_queue.get_nowait()
-                except Exception:
-                    pass
-                # If the reader is still blocked in input_data_stream.read(), 
the stop_event
-                # check only fires between put attempts -- it cannot interrupt 
a syscall.
-                # Force-closing the stream here would break worker reuse (the 
next task uses
-                # the same socket fd), so we settle for a bounded join and a 
loud warning
-                # so an undetected leak shows up in the worker log.
-                t.join(timeout=5)
-                if t.is_alive():
-                    warnings.warn(
-                        "pipelined reader thread did not exit within 5s; "
-                        "it may still be blocked in input_data_stream.read() 
and could "
-                        "read data intended for a subsequent reused-worker 
task. "
-                        "Consider disabling spark.python.worker.reuse if this 
recurs.",
-                        RuntimeWarning,
-                    )
 
-        is_pipelined = os.environ.get("SPARK_PIPELINED_UDF") == "1"
-        # Pipelined reads can overlap UDF work, so mark these task reports for 
filtering.
-        metrics.set("pythonNumPipelinedTasks", int(is_pipelined))
-        if is_pipelined and hasattr(serializer, "_flush_per_batch"):
-            serializer._flush_per_batch = True
-        run_process = pipelined_process if is_pipelined else process
+        def run_process():
+            iterator = deserializer.load_stream(input_data_stream)
+            if is_pipelined:
+                # Read input batches ahead in a background thread so that 
reading them overlaps
+                # with computing the UDF and writing its output.
+                queue_depth = 
int(os.environ.get("SPARK_PIPELINED_UDF_QUEUE_DEPTH", "2"))
+                with read_in_thread(iterator, queue_depth) as queued_iterator:
+                    process(queued_iterator)
+            else:
+                process(iterator)
 
         sampling_profiler_enabled = runner_conf.udf_profiler == "sampling"
 
diff --git a/python/pyspark/worker_util.py b/python/pyspark/worker_util.py
index 416f58c73087..c477247eb311 100644
--- a/python/pyspark/worker_util.py
+++ b/python/pyspark/worker_util.py
@@ -28,7 +28,7 @@ import warnings
 import zipimport
 from contextlib import contextmanager
 from inspect import currentframe, getframeinfo
-from typing import IO, Any, Generator, Optional, Union, overload
+from typing import IO, Any, Generator, Iterator, Optional, Union, overload
 
 from pyspark.messages import ZeroCopyByteStream
 
@@ -316,6 +316,90 @@ def send_accumulator_updates(outfile: IO) -> None:
         pickleSer._write_with_length((aid, accum._value), outfile)
 
 
+class _EndOfInput:
+    """Last item ``read_in_thread`` queues, carrying the exception that ended 
the source."""
+
+    __slots__ = ("error",)
+
+    def __init__(self) -> None:
+        self.error: Optional[BaseException] = None
+
+
+@contextmanager
+def read_in_thread(
+    iterator: Iterator[Any], queue_depth: int
+) -> Generator[Iterator[Any], None, None]:
+    """
+    Read ``iterator`` in a background thread and yield an iterator over the 
same items. The
+    reader runs ahead of the caller by up to ``queue_depth`` queued items plus 
the one it is
+    waiting to enqueue.
+
+    This lets reading and deserializing the input overlap with the caller's 
work. Items that are
+    themselves iterators (e.g. lazy per-group iterators that still read the 
input stream) are
+    materialized into lists on the reader thread, so the caller never reads 
the stream. An
+    exception raised by ``iterator`` is re-raised to the caller once the items 
before it are
+    consumed.
+
+    On exit the reader is stopped and joined for up to 5 seconds. The input is 
never closed, as
+    the stream it reads may be reused by the next task of a reused worker; if 
the reader is still
+    blocked reading it, a RuntimeWarning is emitted instead.
+    """
+    import queue
+    import threading
+
+    item_queue: queue.Queue = queue.Queue(maxsize=queue_depth)
+    stop_event = threading.Event()
+    end = _EndOfInput()
+
+    def _read() -> None:
+        # A put that blocks on a full queue is released by the drain on exit, 
after which the
+        # stop check returns.
+        try:
+            for item in iterator:
+                if hasattr(item, "__next__"):
+                    item = list(item)
+                item_queue.put(item)
+                if stop_event.is_set():
+                    return
+        except BaseException as e:
+            end.error = e
+        finally:
+            if not stop_event.is_set():
+                item_queue.put(end)
+
+    def _consume() -> Iterator[Any]:
+        while True:
+            item = item_queue.get()
+            if item is end:
+                if end.error is not None:
+                    raise end.error
+                return
+            yield item
+
+    reader = threading.Thread(target=_read, name="pyspark-pipelined-reader", 
daemon=True)
+    reader.start()
+    try:
+        yield _consume()
+    finally:
+        # Stop the reader and drain the queue to unblock a pending put. A 
reader blocked in a
+        # read of the input stream only sees the stop between items, so the 
join is bounded.
+        stop_event.set()
+        try:
+            while not item_queue.empty():
+                item_queue.get_nowait()
+        except queue.Empty:
+            pass
+        reader.join(timeout=5)
+        if reader.is_alive():
+            warnings.warn(
+                "pipelined reader thread did not exit within 5s; "
+                "it may still be blocked in input_data_stream.read() and could 
"
+                "read data intended for a subsequent reused-worker task. "
+                "Consider disabling spark.python.worker.reuse if this recurs.",
+                RuntimeWarning,
+            )
+
+
 class Conf:
     def __init__(self, infile_or_dict: Optional[Union[dict[str, str], IO]] = 
None) -> None:
         self._conf: dict[str, Any] = {}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to