Yicong-Huang commented on code in PR #60115:
URL: https://github.com/apache/spark/pull/60115#discussion_r4543400795
##########
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:
Fixed in 5f08088: `_read` catches `BaseException` and `_EndOfInput.error` is
typed to match (`worker_util.py:364`); the source-error test now also covers
`SystemExit`.
##########
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:
Done in 5f08088, using your version: the source never blocks, so a missing
stop re-check fails the count and a missing drain fails `assert_reader_stopped`
(`test_worker.py:187`).
--
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]