viirya commented on code in PR #60115:
URL: https://github.com/apache/spark/pull/60115#discussion_r4535556492


##########
python/pyspark/worker_util.py:
##########
@@ -265,6 +265,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[Exception] = None
+
+
+@contextmanager
+def read_in_thread(
+    iterator: Iterable[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 Exception as e:

Review Comment:
   +1 to catching `BaseException` here. With `Exception`, a source that raises 
e.g. `SystemExit` still reaches the `finally` and queues `end` with `error` 
unset, so the consumer sees a clean end of input and the task succeeds on 
truncated data:
   
   ```python
   def src():
       yield 1
       raise SystemExit(3)
   
   with read_in_thread(src(), 2) as it:
       list(it)   # [1], nothing raised
   ```
   
   The base branch behaved the same way and it is unlikely on the reader 
thread, but the failure is silent. `_EndOfInput.error` needs the matching type 
change.



##########
python/pyspark/tests/test_worker.py:
##########
@@ -146,6 +148,79 @@ def test_accumulate_and_propagate_exception(self):
         self.assertEqual(metrics.to_dict(), {"duration": 3})
 
 
+class ReadInThreadTests(unittest.TestCase):
+    """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):
+        def source():
+            yield 1
+            yield 2
+            raise ValueError("source failure")
+
+        with read_in_thread(source(), 1) as it:
+            self.assertEqual(next(it), 1)
+            self.assertEqual(next(it), 2)
+            with self.assertRaisesRegex(ValueError, "source failure"):
+                next(it)
+        self.assert_reader_stopped()
+
+    def test_early_exit_stops_reader_blocked_on_full_queue(self):
+        produced = []
+        release = threading.Event()
+
+        def source():
+            for i in range(3):
+                produced.append(i)
+                yield i
+            # Simulates a next read of the input stream that does not return; 
the reader must
+            # not get here once the consumer has stopped.
+            release.wait()
+            produced.append(3)
+            yield 3
+
+        try:
+            with warnings.catch_warnings(record=True) as caught:
+                warnings.simplefilter("always")
+                with read_in_thread(source(), 1) as it:
+                    self.assertEqual(next(it), 0)
+                    # The reader fills the queue and then blocks on putting 
the next item.
+                    eventually(timeout=10, catch_assertions=True)(
+                        lambda: self.assertEqual(len(produced), 3)
+                    )()
+        finally:
+            release.set()
+        self.assertEqual([w for w in caught if issubclass(w.category, 
RuntimeWarning)], [])
+        self.assert_reader_stopped()
+        self.assertEqual(len(produced), 3)

Review Comment:
   This assertion does not distinguish the regressions the test is for. If I 
remove the stop re-check after `put`, or the drain on exit, `produced` is still 
3 in both cases; the only thing that fails is the warning check, after the 5s 
join. So the warning capture cannot simply be dropped.
   
   A non-blocking source would let the count carry the test and remove 
`release`, the `try/finally` and the warning capture:
   
   ```python
   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)
       eventually(timeout=10, catch_assertions=True)(
           lambda: self.assertEqual(len(produced), 3)
       )()
   self.assertEqual(len(produced), 3)
   self.assert_reader_stopped()
   ```
   
   Without the re-check the reader takes a fourth item, so the count fails; 
without the drain the reader stays blocked in `put`, so `assert_reader_stopped` 
fails.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to