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


##########
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:
   Thanks, reproduced. With pyarrow 26, your `ZeroDimSum` over 
`rowsBetween(unboundedPreceding, currentRow)` gave `[6, 6, 6]` at d6f5cee.
   
   Fixed in 063f63d by relying on the value check alone. It treats a numpy 
array as mutable even when it's 0-d, and the case now gives `[1, 3, 6]`. 
`test_bounded_frame_results_do_not_share_a_numpy_buffer` covers it.



##########
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:
   Done in 063f63d: the type-based check and the `may_be_mutable` plumbing are 
removed, so the decision no longer depends on the pyarrow version.



##########
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:
   Done in 063f63d. `is_immutable_python_value` now accepts:
   - any tuple of immutable values, including a `Row` or a namedtuple;
   - numpy scalars, except `numpy.void`, which can be a view of a structured 
array;
   - subclasses of the immutable scalar types, such as `np.float64` or a pandas 
`Timestamp`.
   
   A numpy array is still mutable, including a 0-d one. On your benchmark, with 
pyarrow 26 and 20k rows, a `Row` result now takes 0.056s, against 0.224s at 
d6f5cee. A plain tuple takes 0.041s.



##########
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:
   Done in 063f63d: when nothing was flushed, `to_array` returns the converted 
pending results directly. Otherwise it concatenates the chunks once.



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