HyukjinKwon commented on code in PR #60543:
URL: https://github.com/apache/spark/pull/60543#discussion_r4584330002
##########
python/pyspark/eval_handlers/utils.py:
##########
@@ -115,3 +121,90 @@ def func(*args: Any) -> Any:
return func, args_offsets + [kwargs_offsets[key] for key in keys]
else:
return f, args_offsets
+
+
+# Python scalar types whose values are immutable; see
``is_immutable_python_value``.
+_IMMUTABLE_PYTHON_SCALAR_TYPES = (
+ type(None),
+ bool,
+ int,
+ float,
+ str,
+ bytes,
+ decimal.Decimal,
+ datetime.date,
+ datetime.time,
+ datetime.timedelta,
+)
+_IMMUTABLE_PYTHON_SCALAR_TYPE_SET = frozenset(_IMMUTABLE_PYTHON_SCALAR_TYPES +
(datetime.datetime,))
+
+
+def is_immutable_python_value(value: Any) -> bool:
+ """
+ Whether nothing can update ``value`` in place: ``None``, a ``bool``,
``int``, ``float``,
+ ``str``, ``bytes``, ``Decimal``, date, time or timedelta, or a subclass of
one (such as a
+ numpy ``float64``), another numpy scalar, or a tuple of such values,
including a ``Row`` or a
+ namedtuple, whose items are all that Arrow reads of it. A ``bytearray``,
``list``, ``dict``,
+ set or numpy array, even a 0-d one, can be updated in place.
+ """
+ if type(value) in _IMMUTABLE_PYTHON_SCALAR_TYPE_SET:
+ return True
+ if isinstance(value, tuple):
+ return all(is_immutable_python_value(v) for v in value)
+ if isinstance(value, _IMMUTABLE_PYTHON_SCALAR_TYPES):
+ return True
+ # A numpy scalar, but not a structured one (``numpy.void``), which can be
a view of an array.
+ numpy = sys.modules.get("numpy")
+ return (
+ numpy is not None and isinstance(value, numpy.generic) and not
isinstance(value, numpy.void)
+ )
+
+
+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
+ one of them may be updated in place (see ``is_immutable_python_value``).
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") -> None:
+ self._arrow_type = arrow_type
+ 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 not self._pending_may_share_state and not
is_immutable_python_value(result):
Review Comment:
Done in 07d3990, as you suggested. The loop tells `append` when a row was
refolded from `zero`. `append` then records only that row's result as
unchecked: the earlier results' buffers are no longer updated, so it also
clears the pending flag. `flush` checks that result first. Rows that extend or
repeat the running buffer's frame keep the check at `append`, so growing frames
cost what they did.
On a sliding frame over 20k `struct<mn, mx>` tuples, the collector's own
time drops from 8.9 ms to 2.2 ms. Two new tests cover it:
- `test_refolded_frame_result_does_not_share_the_extended_buffer` covers
your `rangeBetween(-1, currentRow)` case over 1, 3, 5 and 6, which gives `[1],
[3], [5], [5, 6]`.
- `test_refolded_result_checked_at_flush` covers the collector directly.
Both fail if `flush` skips that check.
##########
python/pyspark/eval_handlers/utils.py:
##########
@@ -115,3 +121,90 @@ def func(*args: Any) -> Any:
return func, args_offsets + [kwargs_offsets[key] for key in keys]
else:
return f, args_offsets
+
+
+# Python scalar types whose values are immutable; see
``is_immutable_python_value``.
+_IMMUTABLE_PYTHON_SCALAR_TYPES = (
+ type(None),
+ bool,
+ int,
+ float,
+ str,
+ bytes,
+ decimal.Decimal,
+ datetime.date,
+ datetime.time,
+ datetime.timedelta,
+)
+_IMMUTABLE_PYTHON_SCALAR_TYPE_SET = frozenset(_IMMUTABLE_PYTHON_SCALAR_TYPES +
(datetime.datetime,))
+
+
+def is_immutable_python_value(value: Any) -> bool:
+ """
+ Whether nothing can update ``value`` in place: ``None``, a ``bool``,
``int``, ``float``,
+ ``str``, ``bytes``, ``Decimal``, date, time or timedelta, or a subclass of
one (such as a
+ numpy ``float64``), another numpy scalar, or a tuple of such values,
including a ``Row`` or a
+ namedtuple, whose items are all that Arrow reads of it. A ``bytearray``,
``list``, ``dict``,
+ set or numpy array, even a 0-d one, can be updated in place.
Review Comment:
Fixed in 07d3990 with your wording. I also updated the PR description to say
numpy scalars other than `numpy.void`.
--
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]