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


##########
python/pyspark/eval_handlers/_arrow.py:
##########
@@ -591,13 +591,27 @@ def run(self, split_index: int, data: 
Iterator[GroupedBatch]) -> Iterator[pa.Rec
             yield ArrowBatchTransformer.enforce_schema(batch, 
self._return_schema)
 
 
+def _may_be_mutable_python_value(arrow_type: pa.DataType) -> bool:
+    """Whether a Python value of ``arrow_type`` can be a mutable object -- a 
list, a dict, a
+    tuple holding one, or a bytearray -- rather than an immutable scalar."""
+    import pyarrow as pa
+
+    return (
+        pa.types.is_nested(arrow_type)

Review Comment:
   `is_nested`/`is_binary` misses `string`/`large_string`. pyarrow accepts a 
`bytearray` as a `StringType` value (`pa.array([bytearray(b"ab")], 
type=pa.string())` gives `["ab"]`), so the aliasing that this PR fixes still 
happens there.
   
   For example, with `zero()` returning `(bytearray(),)`, `reduce` doing 
`buffer[0].extend(v.encode())`, and `finish` returning `buffer[0]`, the batched 
conversion over the default ordered frame gives `['abc', 'abc', 'abc']` instead 
of `['a', 'ab', 'abc']`. I reproduced this by running the loop of this handler 
with pyarrow 15.0.0.
   
   Could you add `pa.types.is_string` and `pa.types.is_large_string`? Another 
option is to turn this into an allowlist of types whose Python values are 
always immutable (numeric, boolean, decimal, temporal, null). Then any type not 
on the list takes the safe path.



##########
python/pyspark/eval_handlers/_arrow.py:
##########
@@ -670,8 +691,17 @@ def fold(agg: Any, buffer: Any, value_cols: list, start: 
int, end: int) -> Any:
                             running = fold(agg, agg.zero(), value_cols, begin, 
end)
                         have_running = True
                         prev_begin, prev_end = begin, end
-                        results.append(agg.finish(running))
-                    result_arrays.append(pa.array(results, type=result_type))
+                        result = agg.finish(running)
+                        if convert_per_row:
+                            results.append(pa.array([result], 
type=result_type))

Review Comment:
   This keeps one single-row Arrow array per row until the loop ends, which is 
expensive. I measured it locally with pyarrow 15.0.0:
   - Building 20k `struct<mn: double, mx: double>` results this way took about 
250x longer than a single `pa.array(results, type=result_type)` call (0.12s vs 
0.0005s). It was about 240x for `binary`.
   - Each single-row array takes about 2KB of RSS. A 1M-row partition over the 
default ordered frame would hold about 2GB of them in the Python worker.
   
   The cost is paid even when the value cannot share state with the buffer, 
e.g. immutable `bytes` for `BinaryType`, or a struct of scalars. Could we at 
least combine the single-row arrays periodically, so that their per-array 
overhead does not add up over the partition?



##########
python/pyspark/eval_handlers/_arrow.py:
##########
@@ -656,7 +670,14 @@ def fold(agg: Any, buffer: Any, value_cols: list, start: 
int, end: int) -> Any:
                     # ``zero`` -- O(n) overall rather than O(n^2). Otherwise 
-- the lower bound
                     # advanced (a row left the window, which ``reduce`` cannot 
subtract) or the
                     # frame shrank -- refold the frame from ``zero``.
-                    results = []
+                    #
+                    # Later rows keep reducing into the running buffer, which 
``reduce`` may
+                    # update in place, so a row's ``finish`` result can share 
state with it,
+                    # e.g. a list that ``reduce`` appends to. Convert such a 
result to Arrow at
+                    # its own row, before the next ``reduce`` changes it; a 
result whose Python
+                    # value is immutable is converted with the others after 
the loop.
+                    convert_per_row = _may_be_mutable_python_value(result_type)

Review Comment:
   `convert_per_row` is decided by the type alone, but only the extend branch 
(L688-689) keeps reducing into `running`. When the lower bound advances, e.g. 
`rowsBetween(-10, Window.currentRow)`, every row after the first few is 
refolded from a fresh `zero()`. The previous result can then no longer change, 
and converting it per row only adds the cost mentioned above.
   
   How about keeping the results as Python values and converting the pending 
ones only right before the extend branch reduces into `running` again? For 
example:
   
   ```python
   if have_running and begin == prev_begin and end >= prev_end:
       if convert_per_row:
           # The pending results may share state with ``running``, which 
``reduce`` may
           # update in place, so convert them before extending it.
           chunks.append(pa.array(pending, type=result_type))
           pending = []
       running = fold(agg, running, value_cols, prev_end, end)
   else:
       running = fold(agg, agg.zero(), value_cols, begin, end)
   ...
   pending.append(agg.finish(running))
   ```
   
   After the loop, `chunks` plus `pa.array(pending, type=result_type)` can be 
combined into one array. A sliding frame then stays batched, except for its 
first rows.



##########
python/pyspark/sql/tests/arrow/test_arrow_python_aggregator.py:
##########
@@ -401,6 +439,34 @@ def test_window_bounded_preceding_frame(self):
         for r, e in zip(result, expected):
             self.assertAlmostEqual(r["m"], e["m"], places=6)
 
+    def test_window_growing_frame_with_in_place_buffer(self):
+        # ``reduce`` may update its buffer in place, and over a frame whose 
lower bound stays fixed
+        # later rows keep reducing into the buffer that earlier rows were 
finished from. Each row
+        # must still get its own frame's value, also when ``finish`` returns 
the buffer's list
+        # itself or nests it in a struct.
+        df = self._data()
+        ordered = Window.partitionBy("k").orderBy("v")
+        frames = {

Review Comment:
   With `_data()` (`v` = 0..99, all distinct and non-null), these three frames 
give every row the same bounds:
   - The default frame of an ordered window is `RANGE BETWEEN UNBOUNDED 
PRECEDING AND CURRENT ROW`, so `"default"` and `"range"` are the same frame.
   - Without ties, `ROWS` gives the same bounds as `RANGE`.
   
   So the test runs one scenario three times and misses the paths around this 
change:
   - ties in `v` under `RANGE`: the `end == prev_end` case, where `finish` runs 
twice on the same buffer;
   - null inputs: the skip branch in `CollectList.reduce`;
   - a sliding frame such as `rowsBetween(-2, Window.currentRow)`;
   - a non-nested mutable output, such as `BinaryType` from a `bytearray`, or 
`StringType` (see the comment on `_may_be_mutable_python_value`).
   
   Could you use data with duplicates and nulls in `v` and add these cases?



##########
python/pyspark/eval_handlers/_arrow.py:
##########
@@ -670,8 +691,17 @@ def fold(agg: Any, buffer: Any, value_cols: list, start: 
int, end: int) -> Any:
                             running = fold(agg, agg.zero(), value_cols, begin, 
end)
                         have_running = True
                         prev_begin, prev_end = begin, end
-                        results.append(agg.finish(running))
-                    result_arrays.append(pa.array(results, type=result_type))
+                        result = agg.finish(running)
+                        if convert_per_row:
+                            results.append(pa.array([result], 
type=result_type))
+                        else:
+                            results.append(result)
+                    if not convert_per_row:

Review Comment:
   nit: These three branches can be one line, `pa.chunked_array(results, 
type=result_type).combine_chunks()`, which also covers an empty `results`. 
Also, `convert_per_row` depends only on `result_type`, so it could be computed 
once per UDF in `__init__` instead of for every partition.



##########
python/pyspark/sql/aggregator.py:
##########
@@ -126,7 +136,11 @@ def merge(self, buffer1: Tuple[Any, ...], buffer2: 
Tuple[Any, ...]) -> Tuple[Any
 
     @abstractmethod
     def finish(self, buffer: Tuple[Any, ...]) -> Any:
-        """Produce the output value from the final merged buffer."""
+        """Produce the output value from the final merged buffer.
+
+        It must not modify ``buffer``: over a window, it is called once per 
row on a buffer that

Review Comment:
   nit: Over an unbounded frame (e.g. `Window.partitionBy("k")` without 
`orderBy`), `finish` is called once per partition, and its value is repeated 
for every row (`_arrow.py` L653-659). So "called once per row" holds only for 
bounded frames.
   
   The same applies to the new comment in `PythonRunner.scala` ("streams each 
partition with per-row frame bounds"), because no bounds are sent for an 
unbounded frame. Also, the first line of this docstring ("from the final merged 
buffer") now contradicts the window path, which does not use `merge`.



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