Yicong-Huang commented on code in PR #60233:
URL: https://github.com/apache/spark/pull/60233#discussion_r4544788915
##########
python/pyspark/sql/tests/arrow/test_arrow_udtf.py:
##########
@@ -1332,6 +1332,36 @@ def terminate(self) -> Iterator["pa.Table"]:
)
assertDataFrameEqual(result_df, expected_df)
+ def test_arrow_udtf_with_partition_by_nan_values(self):
+ @arrow_udtf(returnType="n int")
+ class CountRows:
+ def __init__(self):
+ self._n = 0
+
+ def eval(self, table_data: "pa.RecordBatch") ->
Iterator["pa.Table"]:
+ self._n += table_data.num_rows
+ return iter(())
+
+ def terminate(self) -> Iterator["pa.Table"]:
+ yield pa.table({"n": pa.array([self._n], type=pa.int32())})
+
+ self.spark.udtf.register("count_rows_arrow", CountRows)
+ nan = float("nan")
+ # NaN keys must form one partition, also when nested in an array or a
struct.
+ df = self.spark.createDataFrame(
+ [(nan, 1), (nan, 2), (1.0, 3), (1.0, 4)], "k double, v int"
Review Comment:
**Non-blocking (P2):** With four rows and the default
`spark.sql.execution.arrow.maxRecordsPerBatch`, both NaN rows land in the same
Arrow batch, so only the within-batch comparison in
`_detect_partition_boundaries` decides their boundary. The cross-batch
comparison in `_process_arrow_batch_by_partitions` (the one against
`self._last_partition_key`) only meets a NaN-to-NaN continuation when a NaN
partition spans two batches, which never happens here. If that comparison went
back to `!=`, this test would still pass while a multi-batch NaN partition got
terminated and restarted at every batch boundary.
Running the same subtests under
`self.sql_conf({"spark.sql.execution.arrow.maxRecordsPerBatch": "1"})`, as
another test in this file already does with a small batch size, makes each NaN
partition span batches and covers that site.
**Verification:**
- **Regression:** With an Arrow batch size of one row, partitioning by a NaN
double, an array containing NaN and a struct containing NaN still yields one
row count per distinct key ([2, 2]), and the same case fails when the
cross-batch key comparison uses plain inequality.
##########
python/pyspark/eval_handlers/_udtf.py:
##########
@@ -71,6 +72,25 @@
from pyspark.worker_util import EvalConf, RunnerConf
+def _partition_values_equal(left: Any, right: Any) -> bool:
+ """
+ Compare two partition key values the way Spark groups them, treating NaN
as equal to NaN
+ (also when nested inside rows, structs, arrays or maps). Python's ``!=``
is not enough,
+ since ``float("nan") != float("nan")`` is True.
+ """
+ if isinstance(left, float) and isinstance(right, float):
Review Comment:
**Non-blocking (P2):** Every boundary check now pays for the isinstance
chain and, for array, struct and multi-column keys, a per-element recursive
`all()` in Python, even when consecutive keys are plainly equal, which is the
common case within a partition. On the base branch this was one C-level `!=`.
That adds per-row CPU to every `TABLE ... PARTITION BY` UDTF over keys without
NaN, which were already correct, and it grows with the size of nested keys.
When `left == right` is True, this helper already returns True for every
value Spark can produce here, so an early return at the top costs nothing in
correctness and makes the common case cheaper than before:
```python
if left == right:
return True
```
The NaN-aware branches then only run when the keys differ under `==`.
**Verification:**
- **Behavior:** The helper returns the same result before and after the
change for equal scalar keys, equal array and struct keys, NaN at top level and
nested in arrays, Row-style tuples and dicts, null versus NaN, and differing
keys, and the existing PARTITION BY UDTF tests keep their results.
- **Inspection:** For keys that compare equal with `==`, the helper returns
without evaluating its isinstance branches or recursing into elements.
##########
python/pyspark/eval_handlers/_udtf.py:
##########
@@ -71,6 +72,25 @@
from pyspark.worker_util import EvalConf, RunnerConf
+def _partition_values_equal(left: Any, right: Any) -> bool:
+ """
+ Compare two partition key values the way Spark groups them, treating NaN
as equal to NaN
+ (also when nested inside rows, structs, arrays or maps). Python's ``!=``
is not enough,
+ since ``float("nan") != float("nan")`` is True.
+ """
+ if isinstance(left, float) and isinstance(right, float):
Review Comment:
**Non-blocking (P2):** This check only recognizes NaN when both values are
Python `float`. On the Arrow-optimized UDTF with
`spark.sql.legacy.execution.pythonUDTF.pandas.conversion.enabled=true`, the
table argument goes through `ArrowToPandasConversion.to_pandas(...,
struct_in_pandas="row", ndarray_as_list=True)`, and `list(ndarray)` turns the
elements of an `array<float>` field into `numpy.float32`, which is not a
`float` subclass (`numpy.float64` is, so `array<double>` works). Two such NaN
elements then fall through to `left == right` and compare unequal.
So `PARTITION BY array(CAST(k AS FLOAT))` over `NaN, NaN, 1.0, 1.0` still
gives one partition per NaN row on that variant, by the review's reading of the
code: `[1, 1, 2]` instead of `[2, 2]`. The legacy conversion is off by default
but users can turn it on, and the PR description says both Arrow-optimized
variants are fixed.
Treating any NaN leaf as equal closes the gap, for example `return left ==
right or (left != left and right != right)` as the scalar fallback, or
including `numpy.floating` in the float check. It would also help to add an
`array<float>` key to the shared `BaseUDTFTestsMixin` NaN test so the legacy
pandas variant exercises it.
**Verification:**
- **Regression:** Partitioning a TABLE argument by an array of FLOAT values
that contain NaN, with the Arrow-optimized Python UDTF and the legacy pandas
conversion enabled, yields one partition per distinct key with NaN rows grouped
together, and fails on the current head.
- **Compatibility:** The same FLOAT-array NaN case and the existing double,
array and struct NaN cases give identical partition counts on the row-based
UDTF, both Arrow-optimized conversion variants and Spark Connect, and null keys
still form a partition separate from NaN keys.
##########
python/pyspark/eval_handlers/_udtf.py:
##########
@@ -71,6 +72,25 @@
from pyspark.worker_util import EvalConf, RunnerConf
+def _partition_values_equal(left: Any, right: Any) -> bool:
+ """
+ Compare two partition key values the way Spark groups them, treating NaN
as equal to NaN
Review Comment:
**Nit (P3):** This says the helper compares keys "the way Spark groups
them", but strings fall through to plain `==`, so collation-equal keys such as
`'a'` and `'A'` under `UTF8_LCASE` still compare as different. The PR
description explains that collated keys are left for a follow-up, but nothing
in the code records that, so the gap is easy to lose. Consider narrowing the
docstring to the NaN rule it implements and adding a TODO here that names
collated string partition keys as not yet handled, because the worker does not
know each key's collation.
**Verification:**
- **Inspection:** The helper's docstring describes only NaN-aware equality
over nested values, and a TODO beside it names collated string partition keys
as not yet handled.
--
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]