spark-test commented on code in PR #60543:
URL: https://github.com/apache/spark/pull/60543#discussion_r4584264092
##########
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:
**Nit (P3):** `append` runs `is_immutable_python_value` on each result until
a possibly mutable one is pending, but only `flush` reads that check, and the
handler calls `flush` only before it extends the running buffer (`end >
prev_end`). Once a frame's lower bound advances, as in `rowsBetween(-2,
currentRow)`, every later row refolds from `zero` and no `flush` follows, so
each immutable result (a tuple, `Row` or scalar) is walked for nothing. Outputs
are unaffected; the cost is per-row CPU in the Python worker on sliding and
narrow range frames, and the PR's own table shows that frame at 0.067s against
0.058s before this PR.
One way to drop it without slowing growing frames: let the loop tell
`append` when a row was folded from `zero`, record only that row's result as
the one left to check (a later refold replaces it, since `zero` gives each
refold a new buffer), and check it first in `flush`. Rows that extend or repeat
the running buffer's frame keep the check at `append`, so growing frames pay
what they pay now. Moving every check into `flush` would instead add
bookkeeping to every row of a growing frame.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60543#discussion_r4581744735).
**Verification:**
- **Behavior:** Over bounds where consecutive rows refold and a later row
extends the last refolded row's buffer, as rangeBetween(-1, currentRow) gives
over the order values 1, 3, 5 and 6, an aggregator whose reduce appends to its
buffer list and whose finish returns that list gives each row its own frame's
values, [1], [3], [5] and [5, 6].
- **Regression:** With immutable struct tuple results over about 20,000
rows, the handler returns the same arrays as before the change. Over
rowsBetween(-2, currentRow) bounds its time matches a collector that keeps
every result and converts them once at the end, and over
rowsBetween(unboundedPreceding, currentRow) bounds it is no slower than before
the change, both within measurement noise.
##########
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:
**Nit (P3):** The docstring counts "another numpy scalar" among the values
nothing can update in place, but line 159 returns `False` for `numpy.void`, as
the comment on line 156 and `test_numpy_values` intend: a structured scalar
such as `np.zeros(1, dtype="i8,f8")[0]` is a view of its array. A maintainer
who trusts the docstring could drop that exclusion as redundant. Suggested
wording:
```suggestion
numpy ``float64``), a numpy scalar other than ``numpy.void``, or a tuple
of such values,
including a ``Row`` or a namedtuple, whose items are all that Arrow
reads of it. A ``list``,
``dict``, set, ``bytearray``, ``numpy.void`` or numpy array (even 0-d)
can be updated in place.
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/60543#discussion_r4582996567).
**Verification:**
- **Inspection:** The value check's docstring no longer calls every numpy
scalar immutable: it names the structured numpy.void scalar among the values
that can be updated in place, which agrees with the code that returns False for
it.
--
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]