HyukjinKwon commented on code in PR #60543:
URL: https://github.com/apache/spark/pull/60543#discussion_r4583100918


##########
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:
   Thanks, reproduced: two such aggregators over one array column both got `[1, 
2, 2]` from `ArrowGroupedAggIncrementalPartialUDFHandler`.
   
   The window path calls `to_pylist()` per aggregator, so aggregators don't 
share inputs there. But it passes a row's objects to `reduce` again for each 
frame that is folded from `zero` and includes that row, so the same rule 
applies.
   
   Documented in 063f63d: `reduce` must not update `value` or keep a mutable 
object of it in `buffer`, with both reasons. `merge` needs no such rule, 
because each aggregator merges its own buffer column and each incoming buffer 
is used once.



##########
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:
   Fixed in 063f63d as suggested. The other comments this PR touched don't have 
that contradiction: they either say that each frame is folded, or spell out 
that the previous row's buffer is extended.



##########
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:
   Done in 063f63d: `is_immutable_python_value` and `WindowAggResults` now live 
in `pyspark/eval_handlers/utils.py`, public like the other helpers there, and 
`_arrow.py` imports `WindowAggResults`. `utils.py` still has no pyspark 
imports, and it imports pyarrow only lazily.



##########
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:
   Done in 063f63d. `WindowAggResultsTests` now checks only `to_array()`: that 
a later in-place update doesn't change a flushed result, many flushed results, 
and no results. `IsImmutablePythonValueTests` covers the value check.



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