dongjoon-hyun commented on code in PR #60543:
URL: https://github.com/apache/spark/pull/60543#discussion_r4582996567


##########
python/pyspark/eval_handlers/_arrow.py:
##########
@@ -591,13 +593,111 @@ def run(self, split_index: int, data: 
Iterator[GroupedBatch]) -> Iterator[pa.Rec
             yield ArrowBatchTransformer.enforce_schema(batch, 
self._return_schema)
 
 
+# Python scalar types whose values are immutable; see 
``_is_immutable_python_value``.
+_IMMUTABLE_PYTHON_SCALAR_TYPES = frozenset(
+    [
+        type(None),
+        bool,
+        int,
+        float,
+        str,
+        bytes,
+        decimal.Decimal,
+        datetime.date,
+        datetime.datetime,
+        datetime.time,
+        datetime.timedelta,
+    ]
+)
+
+
+def _python_values_are_immutable(arrow_type: pa.DataType) -> bool:
+    """Whether every Python value that converts to ``arrow_type`` is an 
immutable scalar, such
+    as an ``int``, a ``Decimal`` or a ``datetime``. A value of any other type 
can be a mutable
+    object: a ``bytearray`` for a string or binary type, or a ``list`` or 
``dict`` for a nested
+    type."""
+    import pyarrow as pa
+
+    types = pa.types
+    return (
+        types.is_null(arrow_type)
+        or types.is_boolean(arrow_type)
+        or types.is_integer(arrow_type)
+        or types.is_floating(arrow_type)
+        or types.is_decimal(arrow_type)
+        or types.is_date(arrow_type)
+        or types.is_time(arrow_type)
+        or types.is_timestamp(arrow_type)
+        or types.is_duration(arrow_type)
+        or types.is_interval(arrow_type)
+    )
+
+
+def _is_immutable_python_value(value: Any) -> bool:
+    """Whether ``value`` is an immutable scalar, such as a ``str`` or 
``bytes``, or a tuple of
+    them, so that nothing can update it in place."""
+    if type(value) is tuple:

Review Comment:
   The exact type checks here treat some immutable values as mutable:
   - a `Row` or a namedtuple, a common way to return a `StructType` result;
   - numpy scalars such as `np.float64` and `np.int64` in a tuple.
   
   Over a growing frame, such results are then converted one row at a time. 
With pyarrow 26, a `struct<mn: double, mx: double>` UDAF over a growing frame 
of 20k rows took 0.130s when `finish` returned a `Row`, and 0.039s when it 
returned the same values as a plain tuple (about 3.3x).
   
   pyarrow reads only the items of a tuple subclass, so `isinstance(value, 
tuple)` is safe here. Numpy scalars (`np.generic`) are immutable too, so they 
could be accepted as well. A 0-d `np.ndarray` is not an `np.generic`, so it 
would still be flushed.



##########
python/pyspark/sql/aggregator.py:
##########
@@ -116,7 +124,11 @@ def zero(self) -> Tuple[Any, ...]:
 
     @abstractmethod
     def reduce(self, buffer: Tuple[Any, ...], value: Tuple[Any, ...]) -> 
Tuple[Any, ...]:
-        """Fold a single input row ``value`` into ``buffer`` and return the 
updated buffer."""
+        """Fold a single input row ``value`` into ``buffer`` and return the 
updated buffer.
+
+        It may update mutable fields of ``buffer`` (e.g. a list) in place and 
return it, as long

Review Comment:
   This condition is not enough on its own. In the PARTIAL stage, the 
aggregators that read the same input column get the same Python objects from 
one `to_pylist()` call (`pylist_by_offset` in 
`ArrowGroupedAggIncrementalPartialUDFHandler.run`). So a `reduce` that keeps an 
input value as a buffer field and then updates it in place also changes the 
input and the buffers of the other aggregators.
   
   For example, take a `reduce` that returns `(value[0],)` when `buffer[0]` is 
`None` and does `buffer[0].extend(value[0])` otherwise. Two such aggregators 
over the same array column, with the inputs `[1]` and `[2]` in one group, both 
get `[1, 2, 2]` instead of `[1, 2]`. I reproduced this with 
`ArrowGroupedAggIncrementalPartialUDFHandler`.
   
   Could you also say that `reduce` must not modify `value` or keep its mutable 
objects in `buffer`?



##########
python/pyspark/util.py:
##########
@@ -726,8 +726,11 @@ class PythonEvalType:
     SQL_GROUPED_AGG_ARROW_INCREMENTAL_PARTIAL_UDF: 
"ArrowGroupedAggIncrementalPartialUDFType" = 255
     SQL_GROUPED_AGG_ARROW_INCREMENTAL_FINAL_UDF: 
"ArrowGroupedAggIncrementalFinalUDFType" = 256
 
-    # Window aggregation with an incremental ``Aggregator``. A window has no 
shuffle, so each
-    # frame's rows are folded with ``reduce`` (from ``zero``) and finished 
with ``finish``.
+    # Window aggregation with an incremental ``Aggregator``. A window 
partition is evaluated
+    # within one task, so there is no PARTIAL/FINAL split and no ``merge``: 
each frame is folded

Review Comment:
   nit: "each frame is folded with ``reduce`` from ``zero``" contradicts the 
next sentence: while the lower bound stays fixed, a bounded frame extends the 
previous row's buffer instead of folding from `zero`. This brings back the 
"fresh fold per frame" description that this PR corrects in the handler 
docstring. How about something like "each frame's rows are folded with 
``reduce`` and ``finish`` produces its value"?



##########
python/pyspark/eval_handlers/_arrow.py:
##########
@@ -591,13 +593,111 @@ def run(self, split_index: int, data: 
Iterator[GroupedBatch]) -> Iterator[pa.Rec
             yield ArrowBatchTransformer.enforce_schema(batch, 
self._return_schema)
 
 
+# Python scalar types whose values are immutable; see 
``_is_immutable_python_value``.
+_IMMUTABLE_PYTHON_SCALAR_TYPES = frozenset(
+    [
+        type(None),
+        bool,
+        int,
+        float,
+        str,
+        bytes,
+        decimal.Decimal,
+        datetime.date,
+        datetime.datetime,
+        datetime.time,
+        datetime.timedelta,
+    ]
+)
+
+
+def _python_values_are_immutable(arrow_type: pa.DataType) -> bool:
+    """Whether every Python value that converts to ``arrow_type`` is an 
immutable scalar, such
+    as an ``int``, a ``Decimal`` or a ``datetime``. A value of any other type 
can be a mutable
+    object: a ``bytearray`` for a string or binary type, or a ``list`` or 
``dict`` for a nested
+    type."""
+    import pyarrow as pa
+
+    types = pa.types
+    return (
+        types.is_null(arrow_type)
+        or types.is_boolean(arrow_type)
+        or types.is_integer(arrow_type)
+        or types.is_floating(arrow_type)
+        or types.is_decimal(arrow_type)
+        or types.is_date(arrow_type)
+        or types.is_time(arrow_type)
+        or types.is_timestamp(arrow_type)
+        or types.is_duration(arrow_type)
+        or types.is_interval(arrow_type)
+    )
+
+
+def _is_immutable_python_value(value: Any) -> bool:
+    """Whether ``value`` is an immutable scalar, such as a ``str`` or 
``bytes``, or a tuple of
+    them, so that nothing can update it in place."""
+    if type(value) is tuple:
+        return all(_is_immutable_python_value(v) for v in value)
+    return type(value) in _IMMUTABLE_PYTHON_SCALAR_TYPES
+
+
+class _WindowAggResults:
+    """Collects the per-row ``finish`` results of one window aggregate into an 
Arrow array.
+
+    A result can share state with the buffer that it was finished from, e.g. 
the list that
+    ``reduce`` appends to, and ``reduce`` may update that buffer in place for 
later rows. The
+    results are held as Python values and converted in batches: ``flush``, 
called before
+    ``reduce`` updates the buffer that the pending results were finished from, 
converts them if
+    any of them may share state with it. Every ``_COMBINE_CHUNKS`` such chunks 
are combined
+    into one array, so that the per-array overhead of the small chunks stays 
bounded.
+    """
+
+    _COMBINE_CHUNKS = 1024
+
+    def __init__(self, arrow_type: pa.DataType, may_be_mutable: bool) -> None:
+        self._arrow_type = arrow_type
+        # Whether a Python value of ``arrow_type`` can be mutable at all.
+        self._may_be_mutable = may_be_mutable
+        self._pending: list[Any] = []
+        self._pending_may_share_state = False
+        self._chunks: list[pa.Array] = []  # each combined from 
``_COMBINE_CHUNKS`` small chunks
+        self._small_chunks: list[pa.Array] = []
+
+    def append(self, result: Any) -> None:
+        self._pending.append(result)
+        if self._may_be_mutable and not _is_immutable_python_value(result):
+            self._pending_may_share_state = True
+
+    def flush(self) -> None:
+        """Convert the pending results if any of them may share state with a 
buffer."""
+        if not self._pending_may_share_state:
+            return
+        import pyarrow as pa
+
+        self._small_chunks.append(pa.array(self._pending, 
type=self._arrow_type))
+        self._pending = []
+        self._pending_may_share_state = False
+        if len(self._small_chunks) == self._COMBINE_CHUNKS:
+            self._chunks.append(pa.concat_arrays(self._small_chunks))
+            self._small_chunks = []
+
+    def to_array(self) -> pa.Array:
+        import pyarrow as pa
+
+        chunks = self._chunks + self._small_chunks
+        chunks.append(pa.array(self._pending, type=self._arrow_type))
+        return pa.chunked_array(chunks, type=self._arrow_type).combine_chunks()

Review Comment:
   This is a follow-up to my earlier `combine_chunks()` suggestion. It 
allocates new buffers and copies the data even when there is only one chunk: 
with pyarrow 15.0.0 and 26, `pa.chunked_array([a]).combine_chunks()` has a 
different data buffer address from `a`. So in the most common case, where 
nothing is flushed (scalar or immutable results), the whole result column is 
copied once more. A flushed value is copied up to three times: by `pa.array`, 
by `pa.concat_arrays` every 1024 chunks, and here.
   
   How about returning `pa.array(self._pending, type=self._arrow_type)` 
directly when `self._chunks` and `self._small_chunks` are both empty?



##########
python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py:
##########
@@ -775,12 +813,67 @@ def test_sliding_frame_refolds_from_zero(self):
         self.assertEqual(out[0].column("_0").to_pylist(), [1, 3, 5, 7])
         self.assertEqual(agg.reduce_calls, 1 + 1 + 2 + 2)
 
+    def test_bounded_frame_results_do_not_share_the_running_buffer(self):
+        # Rows 0-3 extend the running buffer, row 4 has row 3's frame, and row 
5 refolds from
+        # ``zero``. ``reduce`` updates the buffer in place and ``finish`` 
returns it, so every
+        # row must keep its own frame's value, for string, binary and nested 
result types.
+        batch = self._batch(begin=[0, 0, 0, 0, 0, 2], end=[1, 2, 3, 4, 4, 6], 
v=[1, 2, 3, 4, 5, 6])
+        digits = ["1", "12", "123", "1234", "1234", "3456"]
+        cases = [
+            (StringType(), _InPlaceCollector(), digits),
+            (BinaryType(), _InPlaceCollector(), [d.encode() for d in digits]),
+            (
+                ArrayType(LongType()),
+                _InPlaceCollector(as_list=True),
+                [[int(c) for c in d] for d in digits],
+            ),
+        ]
+        for return_type, agg, expected in cases:
+            with self.subTest(return_type=return_type):
+                handler = ArrowWindowAggIncrementalUDFHandler(
+                    udf_descs=[self._udf(agg, [0, 1, 2], 
return_type=return_type)],
+                    runner_conf=RunnerConf({"window_bound_types": "bounded"}),
+                    eval_conf=None,
+                )
+                out = list(handler.run(0, self._one_group(batch)))
+                self.assertEqual(out[0].column("_0").to_pylist(), expected)
+
     def test_invalid_bound_type_raises(self):
         handler = self._handler(_SumAggregator(), "bogus", [0])
         with self.assertRaises(PySparkRuntimeError):
             list(handler.run(0, self._one_group(self._batch(v=[1]))))
 
 
[email protected](not have_pyarrow, pyarrow_requirement_message)
+class WindowAggResultsTests(PySparkBaseTestCase):
+    def test_flush_converts_only_values_that_may_share_state(self):
+        # ``flush`` converts a pending mutable value, so a later in-place 
update of it does not
+        # change the result. Immutable values stay pending.
+        results = _WindowAggResults(pa.binary(), may_be_mutable=True)
+        results.append(b"x")
+        results.append(None)
+        results.flush()
+        self.assertEqual(results._small_chunks, [])

Review Comment:
   nit: `_small_chunks` here and `_chunks`/`_small_chunks` in L872-873 are 
private state, so a refactoring that keeps the behavior breaks these tests, 
e.g. the single-chunk shortcut in the comment on L689 or a different combine 
threshold. How about checking only the observable behavior, i.e. the 
`to_array()` result and that a later in-place update does not change it? 
L860-862 already check the latter.



##########
python/pyspark/eval_handlers/_arrow.py:
##########
@@ -591,13 +593,111 @@ def run(self, split_index: int, data: 
Iterator[GroupedBatch]) -> Iterator[pa.Rec
             yield ArrowBatchTransformer.enforce_schema(batch, 
self._return_schema)
 
 
+# Python scalar types whose values are immutable; see 
``_is_immutable_python_value``.
+_IMMUTABLE_PYTHON_SCALAR_TYPES = frozenset(
+    [
+        type(None),
+        bool,
+        int,
+        float,
+        str,
+        bytes,
+        decimal.Decimal,
+        datetime.date,
+        datetime.datetime,
+        datetime.time,
+        datetime.timedelta,
+    ]
+)
+
+
+def _python_values_are_immutable(arrow_type: pa.DataType) -> bool:
+    """Whether every Python value that converts to ``arrow_type`` is an 
immutable scalar, such
+    as an ``int``, a ``Decimal`` or a ``datetime``. A value of any other type 
can be a mutable
+    object: a ``bytearray`` for a string or binary type, or a ``list`` or 
``dict`` for a nested
+    type."""
+    import pyarrow as pa
+
+    types = pa.types
+    return (
+        types.is_null(arrow_type)
+        or types.is_boolean(arrow_type)
+        or types.is_integer(arrow_type)

Review Comment:
   `is_integer` lets an integer result type skip `flush`, but pyarrow converts 
any object with `__index__` to an integer type, including a mutable 0-d numpy 
array (`pa.array([np.zeros((), dtype=np.int64)], type=pa.int64())` gives 
`[0]`). Then `_result_may_be_mutable` is `False`, so the aliasing that this PR 
fixes still happens there.
   
   For example, take a `LongType` UDAF whose `zero()` returns `(np.zeros((), 
dtype=np.int64),)`, whose `reduce` does `acc = buffer[0]; acc += value[0]`, and 
whose `finish` returns `buffer[0]`. Over 
`rowsBetween(Window.unboundedPreceding, Window.currentRow)` with `v` = 1, 2, 3, 
it gives `[6, 6, 6]` instead of `[1, 3, 6]`. I reproduced this by running this 
handler with pyarrow 26. pyarrow 15.0.0 converts even a 1-element ndarray to 
`int64`, so which values pass this check also depends on the pyarrow version.
   
   Since `_is_immutable_python_value` already checks each value, how about 
relying on it alone? A 0-d array is not in `_IMMUTABLE_PYTHON_SCALAR_TYPES`, so 
it would be flushed.



##########
python/pyspark/eval_handlers/_arrow.py:
##########
@@ -591,13 +593,111 @@ def run(self, split_index: int, data: 
Iterator[GroupedBatch]) -> Iterator[pa.Rec
             yield ArrowBatchTransformer.enforce_schema(batch, 
self._return_schema)
 
 
+# Python scalar types whose values are immutable; see 
``_is_immutable_python_value``.
+_IMMUTABLE_PYTHON_SCALAR_TYPES = frozenset(
+    [
+        type(None),
+        bool,
+        int,
+        float,
+        str,
+        bytes,
+        decimal.Decimal,
+        datetime.date,
+        datetime.datetime,
+        datetime.time,
+        datetime.timedelta,
+    ]
+)
+
+
+def _python_values_are_immutable(arrow_type: pa.DataType) -> bool:

Review Comment:
   nit: This type-based check, with the `may_be_mutable` / 
`_result_may_be_mutable` plumbing, duplicates `_is_immutable_python_value`, 
which already treats `None`, `bool`, `int`, `float`, `Decimal` and the temporal 
values as immutable. When two places decide the same thing, they can disagree, 
which is how the gap in the comment on L625 arises. Keeping only the value 
check would make this shorter and independent of the pyarrow version.
   
   If you prefer to keep it, the `or` chain is the same as 
`types.is_primitive(arrow_type) or types.is_decimal(arrow_type) or 
types.is_null(arrow_type)`. I checked this with pyarrow 15.0.0.



##########
python/pyspark/eval_handlers/_arrow.py:
##########
@@ -591,13 +593,111 @@ def run(self, split_index: int, data: 
Iterator[GroupedBatch]) -> Iterator[pa.Rec
             yield ArrowBatchTransformer.enforce_schema(batch, 
self._return_schema)
 
 
+# Python scalar types whose values are immutable; see 
``_is_immutable_python_value``.

Review Comment:
   nit: Until now, this module has had only the eval type handler classes, and 
the shared helpers live in `pyspark/eval_handlers/utils.py` (e.g. 
`hashable_grouping_key` and `extract_key_value_indexes`). How about moving 
`_IMMUTABLE_PYTHON_SCALAR_TYPES`, `_python_values_are_immutable`, 
`_is_immutable_python_value` and `_WindowAggResults` there?



-- 
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