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

HeartSaVioR 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 19448ae85406 [SPARK-60609][SS][PYTHON][FOLLOWUP] Handle any 
non-iterator iterable returned by SimpleDataSourceStreamReader.read() in offset 
validation
19448ae85406 is described below

commit 19448ae8540697920a21d3ad4f7eec375701e143
Author: Vinod KC <[email protected]>
AuthorDate: Thu Nov 12 12:11:20 2026 +0900

    [SPARK-60609][SS][PYTHON][FOLLOWUP] Handle any non-iterator iterable 
returned by SimpleDataSourceStreamReader.read() in offset validation
    
    ### What changes were proposed in this pull request?
    
    This is a follow-up to #59855 (SPARK-60609). That PR converted only `list` 
results of `SimpleDataSourceStreamReader.read()` before the `end == start` 
offset validation in `_SimpleStreamReaderWrapper.add_result_to_cache`:
    
    ```python
    # read() may return a list instead of an iterator.
    if isinstance(it, list):
        it = iter(it)
    ```
    
    This PR normalizes anything that is not already an iterator instead:
    
    ```python
    # read() may return any iterable instead of an iterator. Look __next__ up on
    # the type, as next() does, so instance __getattr__ hooks and instance
    # attributes cannot misroute the check below.
    if not hasattr(type(it), "__next__"):
        it = iter(it)
    ```
    
    The guard looks `__next__` up on `type(it)` rather than on the instance, 
mirroring how `next()` itself resolves the method (implicit special-method 
lookup skips instance attributes and `__getattr__` hooks). An instance 
attribute named `__next__` or a `__getattr__` hook that answers (or raises for) 
`__next__` therefore cannot make a non-iterator pass the guard and then crash 
on `next()`, and cannot make the guard itself raise; such results are converted 
and validated as the plain itera [...]
    
    ### Why are the changes needed?
    
    Other non-iterator iterables that `read()` can return (tuples, ranges, 
deques, custom classes that define only `__iter__`) still hit `next(it)` 
unconverted and fail with `TypeError: '<type>' object is not an iterator` when 
`end == start`, for example:
    
    ```python
    class MyReader(SimpleDataSourceStreamReader):
        def read(self, start: dict):
            # idle poll: no new data
            return ((), start)  # TypeError: 'tuple' object is not an iterator
    ```
    
    These same values are cached and read back through `getCache` without issue 
when the offset advances, matching pre-SPARK-55416 behavior, so the "any 
iterable" rationale of #59855 applies to them too. An idle poll returning an 
empty tuple or range currently fails the whole query instead of being treated 
as no new data.
    
    The `hasattr(type(it), "__next__")` guard keeps objects that implement only 
`__next__` (which `next()` accepts directly) working exactly as before, unlike 
an unconditional `iter(it)` or an `isinstance(it, collections.abc.Iterator)` 
check, which would start rejecting them. It also avoids narrowing the 
conversion to `isinstance(it, collections.abc.Iterable)`, which would mishandle 
`__getitem__`-only iterables that `iter()` accepts.
    
    #### Compatibility check across released versions
    
    This is a regression introduced by SPARK-55416 (75424734ea1 on master, 
backported to branch-4.0 in v4.0.3 and branch-4.1 in v4.1.2), not merely a 
coverage gap. Before SPARK-55416, nothing in the pipeline required an actual 
iterator: `latestOffset` cached the result without touching it, and `getCache` 
wraps cached entries in `itertools.chain`, which accepts any iterable.
    
    Every GA tag from 4.0.0 to 4.3.0 was verified by running that tag's 
`_SimpleStreamReaderWrapper` directly (via `latestOffset` -> `getCache` -> 
iteration, the runner's consumption path). The 14 tags share three 
byte-identical variants of `datasource_internal.py`, and each variant was 
executed, so every cell below is an actual run (a standalone repro of the 
affected code path, not the full test suites on those versions):
    
    | `read()` result | 4.0.0 - 4.0.2, 4.1.0 - 4.1.1 (pre-SPARK-55416) | 4.0.3 
- 4.0.5, 4.1.2 - 4.1.4, 4.2.0 - 4.2.1, 4.3.0 (SPARK-55416) | branch-4.1/4.2/4.3 
tips (SPARK-55416 + #59855, unreleased) | master + this PR |
    |---|---|---|---|---|
    | empty tuple, `end == start` (idle poll) | OK, no rows | `TypeError` | 
`TypeError` | OK, no cache entry |
    | non-empty tuple, `end == start` | OK, rows delivered | `TypeError` | 
`TypeError` | `SIMPLE_STREAM_READER_OFFSET_DID_NOT_ADVANCE` |
    | non-empty list, `end == start` | OK, rows delivered | `TypeError` | OK / 
`SIMPLE_STREAM_READER_OFFSET_DID_NOT_ADVANCE` | 
`SIMPLE_STREAM_READER_OFFSET_DID_NOT_ADVANCE` |
    | non-empty range, `end == start` | OK, rows delivered | `TypeError` | 
`TypeError` | `SIMPLE_STREAM_READER_OFFSET_DID_NOT_ADVANCE` |
    | any of the above, offset advanced | OK, rows delivered | OK, rows 
delivered | OK, rows delivered | OK, rows delivered |
    
    `dict` was verified as well and behaves mechanically like tuple/range 
(iterating yields its keys); it is omitted from the table since a dict is not a 
meaningful batch of rows, but it confirms the guard restores pre-SPARK-55416 
behavior uniformly for every iterable rather than cherry-picking types.
    
    Notes:
    - SPARK-55416 introduced the first and only `next()` call on the raw result 
of `read()` (the `end == start` validation), which is where non-iterator 
iterables started crashing.
    - #59855 (the list case) is not in any GA release yet either: it was 
backported to the branch-4.1/4.2/4.3 tips on Oct 29, after v4.2.1 and v4.3.0 
were tagged, so those backports ship with the next patch releases. branch-4.0 
has not received the #59855 backport, so 4.0.3+ currently fails for lists as 
well.
    - Once the next 4.1.x/4.2.x/4.3.x patch releases pick up #59855, the list 
case is fixed there but every other non-iterator iterable keeps failing with 
`TypeError` until this PR is backported.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, it fixes a regression from SPARK-55416: a 
`SimpleDataSourceStreamReader` whose
    `read()` returns a non-list, non-iterator iterable — such as a tuple, 
range, deque,
    or an object whose class defines only `__iter__` — with an unchanged end 
offset
    worked in 4.0.2, 4.1.1, and earlier, but fails with `TypeError` in 4.0.3 to 
4.0.5,
    4.1.2 to 4.1.4, 4.2.0, 4.2.1, and 4.3.0. With this PR, an empty result is 
accepted
    as no new data and a non-empty one raises
    `SIMPLE_STREAM_READER_OFFSET_DID_NOT_ADVANCE`. Compared to unreleased 
`master`, an
    idle poll returning e.g. `((), start)` currently fails the query with 
`TypeError`
    and is now treated as no new data; compared to released versions, this 
restores the
    pre-SPARK-55416 behavior.
    
    ### How was this patch tested?
    
    Two new unit tests in 
`python/pyspark/sql/tests/test_python_streaming_datasource.py`:
    
    - `test_simple_stream_reader_returns_non_iterator_iterables`: `tuple`, 
`range`,
      `deque`, a class that defines only `__iter__`, and a class that defines 
only
      `__getitem__`, each in all three cases (non-empty with an advanced offset 
cached
      and readable via `getCache`, empty with `end == start` accepted without 
caching,
      non-empty with `end == start` raising 
`SIMPLE_STREAM_READER_OFFSET_DID_NOT_ADVANCE`),
      plus an object that implements only `__next__`, which `next()` accepts 
directly.
    - `test_simple_stream_reader_next_lookup_uses_type`: results whose 
instances answer
      or raise on `__next__` — a `__getattr__` hook returning `None`, one 
raising
      `KeyError`, and an instance `__next__` attribute — are treated as the 
plain
      iterables they are (empty accepted, non-empty raising the offset 
validation
      error), and an iterator proxy forwarding `__getattr__` and `__iter__` to 
an
      iterator is converted with `iter()` and validated on the paths where the 
guard
      runs (the cache readback copies entries with `copy.copy`, which a proxy 
rebuilt
      without `__init__` cannot survive, so it is not exercised there).
    
    Both tests live in the shared `BasePythonStreamingDataSourceTestsMixin`, so 
they run
    in both the classic and the Spark Connect suites. The existing
    `test_simple_stream_reader_returns_list` from #59855 still passes unchanged.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Yes, Generated-by: Claude Code (Claude Opus 5.5)
    
    Closes #60315 from vinodkc/SPARK-60609-followup-iterable-normalization.
    
    Authored-by: Vinod KC <[email protected]>
    Signed-off-by: Jungtaek Lim <[email protected]>
    
    
    skip-checks: true
---
 python/pyspark/sql/datasource_internal.py          |   6 +-
 .../sql/tests/test_python_streaming_datasource.py  | 193 +++++++++++++++++++++
 2 files changed, 197 insertions(+), 2 deletions(-)

diff --git a/python/pyspark/sql/datasource_internal.py 
b/python/pyspark/sql/datasource_internal.py
index 06d98af1403a..b1143f9bab50 100644
--- a/python/pyspark/sql/datasource_internal.py
+++ b/python/pyspark/sql/datasource_internal.py
@@ -105,8 +105,10 @@ class _SimpleStreamReaderWrapper(DataSourceStreamReader):
         if end_str != start_str:
             self.cache.append(PrefetchedCacheEntry(start, end, it))
             return
-        # read() may return a list instead of an iterator.
-        if isinstance(it, list):
+        # read() may return any iterable instead of an iterator. Look __next__ 
up on
+        # the type, as next() does, so instance __getattr__ hooks and instance
+        # attributes cannot misroute the check below.
+        if not hasattr(type(it), "__next__"):
             it = iter(it)
         try:
             next(it)
diff --git a/python/pyspark/sql/tests/test_python_streaming_datasource.py 
b/python/pyspark/sql/tests/test_python_streaming_datasource.py
index 6b6baf76eb73..e29ccc3188a8 100644
--- a/python/pyspark/sql/tests/test_python_streaming_datasource.py
+++ b/python/pyspark/sql/tests/test_python_streaming_datasource.py
@@ -604,6 +604,199 @@ class BasePythonStreamingDataSourceTestsMixin:
             "SIMPLE_STREAM_READER_OFFSET_DID_NOT_ADVANCE",
         )
 
+    def test_simple_stream_reader_returns_non_iterator_iterables(self):
+        """read() returning a non-iterator iterable (e.g. tuple, range) is 
handled like a list."""
+        from collections import deque
+
+        from pyspark.sql.datasource_internal import _SimpleStreamReaderWrapper
+
+        class IterableOnly:
+            """An iterable that implements __iter__ but not __next__."""
+
+            def __init__(self, rows):
+                self._rows = rows
+
+            def __iter__(self):
+                return iter(self._rows)
+
+        class NextOnly:
+            """Implements only __next__ without __iter__, which next() 
accepts."""
+
+            def __init__(self, rows):
+                self._rows = iter(rows)
+
+            def __next__(self):
+                return next(self._rows)
+
+        class GetitemOnly:
+            """An iterable that implements only __getitem__, without __iter__ 
or __next__."""
+
+            def __init__(self, rows):
+                self._rows = rows
+
+            def __getitem__(self, index):
+                return self._rows[index]
+
+        class NonIteratorIterableReader(SimpleDataSourceStreamReader):
+            def __init__(self, rows, to_result, advance):
+                self.rows = rows
+                self.to_result = to_result
+                self.advance = advance
+
+            def initialOffset(self):
+                return {"offset": 0}
+
+            def read(self, start: dict):
+                end = {"offset": start["offset"] + len(self.rows)} if 
self.advance else start
+                return (self.to_result(self.rows), end)
+
+            def readBetweenOffsets(self, start: dict, end: dict):
+                return iter([])
+
+            def commit(self, end: dict):
+                pass
+
+        start = {"offset": 0}
+        # Examples of non-iterator iterables that read() may return instead of 
an iterator.
+        # GetitemOnly is included because it is the one kind that a guard 
narrowing the
+        # conversion to isinstance(it, Iterable) would mishandle.
+        non_iterator_results = [
+            tuple,
+            lambda rows: range(len(rows)),
+            lambda rows: deque(rows),
+            IterableOnly,
+            GetitemOnly,
+        ]
+
+        for to_result in non_iterator_results:
+            # Non-empty iterable with an advanced end offset is cached and 
readable.
+            wrapper = _SimpleStreamReaderWrapper(
+                NonIteratorIterableReader([0, 1], to_result, advance=True)
+            )
+            end = wrapper.latestOffset(start, ReadAllAvailable())
+            self.assertEqual(end, {"offset": 2})
+            self.assertEqual(list(wrapper.getCache(start, end)), [0, 1])
+
+            # Empty iterable with end == start is allowed and not cached.
+            wrapper = _SimpleStreamReaderWrapper(
+                NonIteratorIterableReader([], to_result, advance=False)
+            )
+            end = wrapper.latestOffset(start, ReadAllAvailable())
+            self.assertEqual(end, start)
+            self.assertEqual(len(wrapper.cache), 0)
+
+            # Non-empty iterable with end == start raises the offset 
validation error.
+            wrapper = _SimpleStreamReaderWrapper(
+                NonIteratorIterableReader([0], to_result, advance=False)
+            )
+            with self.assertRaises(PySparkException) as cm:
+                wrapper.latestOffset(start, ReadAllAvailable())
+            self.assertEqual(
+                cm.exception.getCondition(),
+                "SIMPLE_STREAM_READER_OFFSET_DID_NOT_ADVANCE",
+            )
+
+        # Objects that implement only __next__ keep being accepted by next() 
directly.
+        wrapper = _SimpleStreamReaderWrapper(NonIteratorIterableReader([], 
NextOnly, advance=False))
+        end = wrapper.latestOffset(start, ReadAllAvailable())
+        self.assertEqual(end, start)
+        self.assertEqual(len(wrapper.cache), 0)
+
+        wrapper = _SimpleStreamReaderWrapper(
+            NonIteratorIterableReader([0], NextOnly, advance=False)
+        )
+        with self.assertRaises(PySparkException) as cm:
+            wrapper.latestOffset(start, ReadAllAvailable())
+        self.assertEqual(
+            cm.exception.getCondition(),
+            "SIMPLE_STREAM_READER_OFFSET_DID_NOT_ADVANCE",
+        )
+
+    def test_simple_stream_reader_next_lookup_uses_type(self):
+        """The __next__ check uses the type, so __getattr__ hooks and instance 
attributes
+        on the result cannot misroute the empty/non-empty validation."""
+        from pyspark.sql.datasource_internal import _SimpleStreamReaderWrapper
+
+        class GetattrReturnsList(list):
+            def __getattr__(self, name):
+                return None
+
+        class GetattrRaisesList(list):
+            def __getattr__(self, name):
+                raise KeyError(name)
+
+        class IteratorProxy:
+            def __init__(self, rows):
+                self._rows = iter(rows)
+
+            def __getattr__(self, name):
+                return getattr(self._rows, name)
+
+            def __iter__(self):
+                return self._rows
+
+        def with_instance_next(rows):
+            # An instance __next__ attribute must not be consulted by the 
check.
+            result = GetattrReturnsList(rows)
+            result.__next__ = lambda: (_ for _ in 
()).throw(AssertionError("unused"))
+            return result
+
+        class HookedResultReader(SimpleDataSourceStreamReader):
+            def __init__(self, rows, to_result, advance):
+                self.rows = rows
+                self.to_result = to_result
+                self.advance = advance
+
+            def initialOffset(self):
+                return {"offset": 0}
+
+            def read(self, start: dict):
+                end = {"offset": start["offset"] + len(self.rows)} if 
self.advance else start
+                return (self.to_result(self.rows), end)
+
+            def readBetweenOffsets(self, start: dict, end: dict):
+                return iter([])
+
+            def commit(self, end: dict):
+                pass
+
+        start = {"offset": 0}
+        # Instance lookups answer __next__ (or raise for it), but the type 
does not
+        # define it, so the result must be treated as the plain iterable it is.
+        for to_result in [GetattrReturnsList, GetattrRaisesList, 
with_instance_next]:
+            # Empty result with end == start is allowed and not cached.
+            wrapper = _SimpleStreamReaderWrapper(HookedResultReader([], 
to_result, advance=False))
+            end = wrapper.latestOffset(start, ReadAllAvailable())
+            self.assertEqual(end, start)
+            self.assertEqual(len(wrapper.cache), 0)
+
+            # Non-empty result with end == start raises the offset validation 
error,
+            # not a TypeError and not an exception escaping from a hook.
+            wrapper = _SimpleStreamReaderWrapper(HookedResultReader([0], 
to_result, advance=False))
+            with self.assertRaises(PySparkException) as cm:
+                wrapper.latestOffset(start, ReadAllAvailable())
+            self.assertEqual(
+                cm.exception.getCondition(),
+                "SIMPLE_STREAM_READER_OFFSET_DID_NOT_ADVANCE",
+            )
+
+        # A proxy forwarding __getattr__ and __iter__ to an iterator is 
converted with
+        # iter() and validated like any other iterable. It is only checked on 
paths
+        # where the guard runs: the cache readback copies entries with 
copy.copy,
+        # which a proxy rebuilt without __init__ cannot survive.
+        wrapper = _SimpleStreamReaderWrapper(HookedResultReader([0], 
IteratorProxy, advance=False))
+        with self.assertRaises(PySparkException) as cm:
+            wrapper.latestOffset(start, ReadAllAvailable())
+        self.assertEqual(
+            cm.exception.getCondition(),
+            "SIMPLE_STREAM_READER_OFFSET_DID_NOT_ADVANCE",
+        )
+
+        wrapper = _SimpleStreamReaderWrapper(HookedResultReader([], 
IteratorProxy, advance=False))
+        end = wrapper.latestOffset(start, ReadAllAvailable())
+        self.assertEqual(end, start)
+        self.assertEqual(len(wrapper.cache), 0)
+
     def test_stream_writer(self):
         input_dir = 
tempfile.TemporaryDirectory(prefix="test_data_stream_write_input")
         output_dir = 
tempfile.TemporaryDirectory(prefix="test_data_stream_write_output")


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

Reply via email to