spark-test commented on code in PR #58405:
URL: https://github.com/apache/spark/pull/58405#discussion_r4552038163


##########
python/pyspark/pandas/typedef/typehints.py:
##########
@@ -335,14 +353,30 @@ def spark_type_to_pandas_dtype(
 def is_str_dtype(tpe: Dtype) -> bool:
     if LooseVersion(pd.__version__) < "3.0.0":
         return False
+    if extension_arrow_dtypes_available and isinstance(tpe, ArrowDtype):
+        pyarrow_type = tpe.pyarrow_dtype
+        if pa.types.is_string(pyarrow_type) or 
pa.types.is_large_string(pyarrow_type):
+            return True
     if extension_object_dtypes_available:
         return isinstance(tpe, StringDtype) and tpe.na_value is np.nan
     return False
 
 
+def is_pyarrow_backed_dtype(tpe: Dtype) -> bool:
+    """Return whether the given dtype is a PyArrow-backed dtype."""
+    if extension_arrow_dtypes_available and isinstance(tpe, ArrowDtype):
+        return True
+    if extension_object_dtypes_available and isinstance(tpe, StringDtype):
+        storage = getattr(tpe, "storage", None)
+        return isinstance(storage, str) and storage.startswith("pyarrow")
+    return False
+
+
 def handle_dtype_as_extension_dtype(tpe: Dtype) -> bool:
     if is_str_dtype(tpe):
         return False
+    elif extension_arrow_dtypes_available and isinstance(tpe, ArrowDtype):

Review Comment:
   **Blocking (P1):** Treating `ArrowDtype` as an extension dtype here makes 
`BooleanOps.__and__`, `__or__` and `xor` (data_type_ops/boolean_ops.py) hand 
the operation to the right operand, with the operands swapped, whenever that 
operand is `bool[pyarrow]`. `DataTypeOps` still gives an 
`ArrowDtype(pa.bool_())` Series `BooleanOps` rather than `BooleanExtensionOps`, 
so with two `bool[pyarrow]` operands each side swaps back to the other. By the 
review's reading of the dispatch, the call never reaches `column_op` and ends 
in `RecursionError`. Because `column_op` now returns `bool[pyarrow]` for 
comparisons over PyArrow-backed operands, the usual multi-condition filter 
`psdf[(psdf.a == 'x') & (psdf.b == 'y')]` fails this way. It fails on 
`string[pyarrow]` columns, including on pandas 2.3.3, and on pandas 3's default 
string columns, where the base branch returns the element-wise result. 
`BooleanOps.add` and `mul` with a boolean Series delegate to `|` and `&`, and 
fail the same way.
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/pandas/typedef/typehints.py:
##########
@@ -253,17 +261,27 @@ def as_spark_type(
             elif isinstance(tpe, Float64Dtype) or (isinstance(tpe, str) and 
tpe == "Float64"):
                 return types.DoubleType()
 
+        # PyArrow-backed ArrowDtype
+        if extension_arrow_dtypes_available and isinstance(tpe, ArrowDtype):

Review Comment:
   **Blocking (P1):** Columns this branch admits reach 
`_should_return_all_false` in `DataTypeOps.eq` and `ne` 
(data_type_ops/base.py). It short-circuits to all False (all True for `!=`) 
whenever the two dtypes differ and are not both numeric. An `ArrowDtype` never 
equals the dtype pandas infers for an ordinary value, such as object or `str` 
for `'a'`, and `is_numeric_dtype` is False for every non-numeric `ArrowDtype`, 
including `bool[pyarrow]`. By the review's reading, `ps.Series(['a', 'b', 'c'], 
dtype=pd.ArrowDtype(pa.string())) == 'a'` therefore returns `[False, False, 
False]` where pandas returns `[True, False, False]`. The same happens for 
`bool[pyarrow]` against `True` or `1`, and for Arrow timestamp, date, binary 
and duration columns against matching scalars, lists or Series, so filters such 
as `psdf[psdf.city == 'Paris']` silently return no rows. The PR's test compares 
two Series of the same `ArrowDtype`, which skips this path.
   
   **Verification:**
   - **Regression:** == and != between ArrowDtype string, boolean, timestamp, 
date, binary and duration columns and same-kind scalars, lists and Series match 
pandas on pandas 2 and 3, including filters such as psdf[psdf.s == 'a'] and 
psdf[psdf.ts == pd.Timestamp('2024-01-01')] returning the matching rows.
   - **Regression:** An object or str string Series compared with an ArrowDtype 
string Series compares values in both operand orders instead of returning all 
False.
   - **Regression:** bool[pyarrow] == 1 and != 1 give the same result as the 
same comparison on a NumPy bool column, and an ArrowDtype string column 
compared with a number still returns all False, as pandas does.



##########
python/pyspark/pandas/typedef/typehints.py:
##########
@@ -253,17 +261,27 @@ def as_spark_type(
             elif isinstance(tpe, Float64Dtype) or (isinstance(tpe, str) and 
tpe == "Float64"):
                 return types.DoubleType()
 
+        # PyArrow-backed ArrowDtype
+        if extension_arrow_dtypes_available and isinstance(tpe, ArrowDtype):
+            return from_arrow_type(tpe.pyarrow_dtype, prefer_timestamp_ntz)

Review Comment:
   **Blocking (P1):** Mapping `ArrowDtype` timestamps to `TimestampType` here 
routes them through conversions that only handle NumPy datetime64. On the way 
in, `_check_series_convert_timestamps_internal` (sql/pandas/types.py) localizes 
only datetime64 values to the session time zone and passes an `ArrowDtype` 
series through unchanged, so `pa.Array.from_pandas` stores a naive value as if 
it were UTC. On the way out, collected values are naive session-local times, 
and on pandas 3 `DatetimeOps.restore` casts them to the field's `ArrowDtype`, 
which reads them as UTC for a zoned dtype. By the review's reading, with 
`spark.sql.session.timeZone` set to America/Los_Angeles, a naive 
`timestamp[us][pyarrow]` value of 2024-01-01 10:00 is stored as 10:00 UTC and 
comes back from `to_pandas()` as 02:00, and `psdf.ts.dt.hour` returns 2 where 
pandas returns 10. A zoned value of 10:00+00:00 comes back on pandas 3 as 
02:00+00:00. NumPy datetime64 columns are unaffected, and so are naive values 
under `
 spark.sql.timestampType=TIMESTAMP_NTZ`.
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/pandas/tests/data_type_ops/test_string_ops.py:
##########
@@ -237,6 +240,19 @@ def test_ge(self):
         self.assert_eq(pser >= other_pser, psser >= other_psser)
         self.assert_eq(pser >= pser, psser >= psser)
 
+    @unittest.skipIf(
+        not extension_arrow_dtypes_available, "PyArrow-backed dtypes are not 
available"
+    )
+    def test_pyarrow_backed_string_ops(self):

Review Comment:
   **Non-blocking (P2):** This is the only test that runs an operation, and it 
compares two null-free `ArrowDtype(pa.string())` Series from the same frame. By 
the review's reading, it still passes if the loc assignment or `combine_frames` 
flags are reverted, if the `ArrowDtype` branch of 
`handle_dtype_as_extension_dtype` is removed, or if `column_op` looks only at 
`self`. `tolist()` passes too, even though `to_pandas()` drops the 
`bool[pyarrow]` dtype. Nothing tests missing values, scalar or mixed operands, 
`&` or `|` on masks, loc assignment, operations across DataFrames, timestamp, 
large, dictionary or nested Arrow types, `string[pyarrow]` operands, or pandas 
3's default string columns, so regressions in the changed paths would ship 
without a failing test.
   
   **Verification:**
   - **Behavior:** An ArrowDtype comparison over operands with missing values 
returns <NA> where pandas does, and a filter on it keeps the same rows as 
pandas.
   - **Behavior:** Loc assignment into, and an operation across DataFrames on, 
ArrowDtype(pa.int64()) and ArrowDtype(pa.string()) data columns and index 
levels keeps their ArrowDtype.
   - **Behavior:** Comparing an ArrowDtype Series with a NumPy-dtype Series of 
the same kind returns an ArrowDtype result in either operand order.



##########
python/pyspark/pandas/typedef/typehints.py:
##########
@@ -335,14 +353,30 @@ def spark_type_to_pandas_dtype(
 def is_str_dtype(tpe: Dtype) -> bool:
     if LooseVersion(pd.__version__) < "3.0.0":
         return False
+    if extension_arrow_dtypes_available and isinstance(tpe, ArrowDtype):
+        pyarrow_type = tpe.pyarrow_dtype
+        if pa.types.is_string(pyarrow_type) or 
pa.types.is_large_string(pyarrow_type):
+            return True
     if extension_object_dtypes_available:
         return isinstance(tpe, StringDtype) and tpe.na_value is np.nan
     return False
 
 
+def is_pyarrow_backed_dtype(tpe: Dtype) -> bool:
+    """Return whether the given dtype is a PyArrow-backed dtype."""
+    if extension_arrow_dtypes_available and isinstance(tpe, ArrowDtype):
+        return True
+    if extension_object_dtypes_available and isinstance(tpe, StringDtype):

Review Comment:
   **Blocking (P1):** This also matches pandas 3's default `str` dtype: 
`StringDtype(na_value=np.nan)` has pyarrow storage whenever pyarrow is 
installed, and pandas-on-Spark gives that dtype to every string column. So on 
pandas 3, every operation on a default string column now takes the Arrow result 
path. For `psdf = ps.DataFrame({'n': [1, 2, 3], 's': ['a', None, 'c']})`, by 
the review's reading `psdf.s != 'a'` becomes `bool[pyarrow]` with the missing 
value kept, because `column_op` skips `booleanize_null` for an extension-dtype 
result. `psdf[psdf.s != 'a']` then drops the row whose `s` is missing, while 
pandas and the base branch keep it, and `(psdf.s + psdf.s).dtype` becomes 
`string[pyarrow]` instead of `str`. After `psdf.loc[psdf.n > 1, 's'] = 'z'` the 
column itself is retyped, so later scalar comparisons on it return all False. 
This applies on pandas 3 (3.0.x today), which PR CI does not run; on pandas 2 
the default string dtype is object, so default string columns there are unaf
 fected.
   
   **Recommended change:** Narrow the switch to ArrowDtype results. column_op 
fires it when an operand is a pandas ArrowDtype, or when the operation is a 
comparison (==, !=, <, <=, >, >=) and an operand is string[pyarrow], the 
StringDtype with pyarrow storage and pd.NA as its missing value. combine_frames 
and loc assignment fire it only for ArrowDtype fields. pandas' str dtype, the 
StringDtype with NaN as its missing value that pandas 3 uses by default and 
pandas 2 uses under future.infer_string, never fires it. Those columns, 
string[pyarrow] string results, and carried-through string[pyarrow] columns 
then keep the derivation they have on the base branch. Add pandas 3 str and 
string[pyarrow] cases to the string-ops tests, and update the typedef 
classifier test if is_pyarrow_backed_dtype itself is narrowed.
   
   **Why this works:** With the narrowed switch, column_op computes 
use_arrow_dtypes as False for str operands, so their comparisons go back to 
NumPy bool with booleanize_null and their string results keep str. 
string[pyarrow] comparisons keep the bool[pyarrow] that pandas returns for 
them, while string[pyarrow] string results go back to StringDtype. 
combine_frames and loc assignment rebuild every StringDtype field through 
use_extension_dtypes and the pandas 3 str rule, as on the base branch.
   
   **Scope:** Limit the switch to ArrowDtype results to ArrowDtype sources and 
string[pyarrow] comparisons, so pandas' str dtype and other string[pyarrow] 
results keep their base-branch dtypes.
   
   **Compatibility:** ArrowDtype operands and fields keep deriving ArrowDtype 
results at column_op, combine_frames and loc assignment, and string[pyarrow] 
comparisons keep the bool[pyarrow] results the PR gives them.
   
   **Risks:** column_op has to tell comparisons apart from other operations, 
for example with the comparison-function list booleanize_null already uses; an 
operation missing from that list gives string[pyarrow] operands the base-branch 
dtype instead of bool[pyarrow]. If is_pyarrow_backed_dtype keeps its current 
meaning, the result switch stops using it directly; if the predicate is 
narrowed instead, the typedef test that asserts StringDtype(storage='pyarrow') 
is PyArrow-backed changes with it.
   
   **Constraints:** On pandas 3, the str dtype must keep NumPy bool comparison 
results with booleanize_null, and str string results. ArrowDtype operands must 
keep producing ArrowDtype results, as the PR's ArrowDtype string comparison 
test requires. string[pyarrow] comparison masks stay bool[pyarrow], so this 
repair must land with, or after, the DataTypeOps repair that makes &, | and ^ 
on two bool[pyarrow] masks compute instead of recursing.
   
   **Exclusions:**
   - pandas 2's NaN-variant StringDtype under future.infer_string keeps the 
BooleanDtype comparisons it gets on the base branch, where pandas returns NumPy 
bool; that existing mismatch is left unchanged.
   
   **Success:** On pandas 3, comparisons on default string columns return NumPy 
bool with missing values compared as False (True for !=), and psdf[psdf.s != 
'a'] keeps the rows whose s is missing. On pandas 3, Series concatenation of 
default string columns keeps the str dtype, and loc assignment and operations 
across DataFrames leave str and string[pyarrow] columns with their StringDtype. 
string[pyarrow] comparisons return bool[pyarrow] with <NA> for missing values, 
as pandas does on pandas 2 and 3, while string[pyarrow] string results keep 
StringDtype. Comparing two ArrowDtype(pa.string()) Series still returns 
bool[pyarrow].
   
   **Verification:**
   - **Regression:** On pandas 3, with a default string column holding a 
missing value, ==, != and < match pandas in dtype and values, a != filter keeps 
the missing row, Series concatenation keeps str, and the column keeps str after 
loc assignment and after an operation across DataFrames.
   - **Regression:** For string[pyarrow] columns on pandas 2 and 3, comparisons 
return bool[pyarrow] with <NA> for missing values as pandas does, while Series 
concatenation and carried-through columns keep StringDtype.
   - **Behavior:** Comparing two ArrowDtype(pa.string()) Series still returns 
bool[pyarrow] with the expected values.



##########
python/pyspark/pandas/typedef/typehints.py:
##########
@@ -253,17 +261,27 @@ def as_spark_type(
             elif isinstance(tpe, Float64Dtype) or (isinstance(tpe, str) and 
tpe == "Float64"):
                 return types.DoubleType()
 
+        # PyArrow-backed ArrowDtype
+        if extension_arrow_dtypes_available and isinstance(tpe, ArrowDtype):

Review Comment:
   **Non-blocking (P2):** Accepting `ArrowDtype` here gives these columns the 
ops class their Spark type selects (`IntegralOps`, `FractionalOps`, 
`BooleanOps` or `StringOps`), because `DataTypeOps.__new__` picks the extension 
ops classes only for pandas extension dtype classes. Those classes' `restore` 
returns Spark's `toPandas` output unchanged, while the extension-dtype siblings 
cast to the field dtype, so `psdf.dtypes` and `psdf.to_pandas().dtypes` 
disagree. For `ps.from_pandas(pd.DataFrame({'a': pd.array([1, None], 
dtype='int64[pyarrow]'), 'b': pd.array([True, None], 
dtype='bool[pyarrow]')}))`, the reported dtypes are `int64[pyarrow]` and 
`bool[pyarrow]`, but by the review's reading `to_pandas()` returns float64 
`[1.0, NaN]` and object `[True, None]`. On pandas 2, an 
`ArrowDtype(pa.string())` column also comes back as object, and a zoned 
`ArrowDtype` timestamp as naive datetime64. The PR's dtype-preservation goal 
stops exactly where users read results back.
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/pandas/base.py:
##########
@@ -247,6 +250,7 @@ def wrapper(self: SeriesOrIndex, *args: Any) -> 
SeriesOrIndex:
                 use_extension_dtypes=any(
                     handle_dtype_as_extension_dtype(col.dtype) for col in 
[self] + cols
                 ),
+                use_arrow_dtypes=any(is_pyarrow_backed_dtype(col.dtype) for 
col in [self] + cols),

Review Comment:
   **Nit (P3):** This second `any(...)` reads `col.dtype` again for every 
operand. For a Series, each read goes through `Series._internal`, which builds 
a new `InternalFrame` via `select_column`, and in classic mode that constructor 
makes a py4j `isStreaming` call. Under Spark Connect, `isStreaming` and the 
schema are cached on the reused DataFrame, so the extra cost there is 
Python-side only. Every arithmetic or comparison operator on any dtype now pays 
this extra per-operand work, including NumPy-dtype operations whose results are 
unchanged. Reading the operand dtypes once, for example with `dtypes = 
[col.dtype for col in [self] + cols]`, and deriving both flags from that list 
gives the same flags.
   
   **Verification:**
   - **Inspection:** column_op reads each operand's dtype once per call and 
derives both use_extension_dtypes and use_arrow_dtypes from those values.



##########
python/pyspark/pandas/typedef/typehints.py:
##########
@@ -253,17 +261,27 @@ def as_spark_type(
             elif isinstance(tpe, Float64Dtype) or (isinstance(tpe, str) and 
tpe == "Float64"):
                 return types.DoubleType()
 
+        # PyArrow-backed ArrowDtype
+        if extension_arrow_dtypes_available and isinstance(tpe, ArrowDtype):
+            return from_arrow_type(tpe.pyarrow_dtype, prefer_timestamp_ntz)
+
     if raise_error:
         raise TypeError("Type %s was not understood." % tpe)
     else:
         return None
 
 
 def spark_type_to_pandas_dtype(
-    spark_type: types.DataType, *, use_extension_dtypes: bool = False
+    spark_type: types.DataType,
+    *,
+    use_extension_dtypes: bool = False,
+    use_arrow_dtypes: bool = False,
 ) -> Dtype:
     """Return the given Spark DataType to pandas dtype."""
 
+    if use_arrow_dtypes and extension_arrow_dtypes_available:
+        return ArrowDtype(to_arrow_type(spark_type))

Review Comment:
   **Non-blocking (P2):** This rebuilds the result dtype from the Spark type 
alone. `to_arrow_type` asserts a time zone for `TimestampType` 
(sql/pandas/types.py), and this call never passes one. A column that 
`astype('timestamp[us][pyarrow]')` leaves with an `ArrowDtype` on a 
`TimestampType` field then, by the review's reading, fails with a bare 
`AssertionError` on `psdf.loc[psdf.n > 0, 'ts'] = value` or on an operation 
across DataFrames that touches it; nested timestamps in arrays, maps and 
structs fail the same way. For other types, the rebuild cannot recover the 
source Arrow type, because several Arrow types share one Spark type. 
`large_string` and dictionary-encoded strings come back as `string[pyarrow]`, 
`large_list` comes back as `list`, and 
`spark.sql.execution.arrow.useLargeVarTypes` is ignored, so carried-through 
columns silently change dtype.
   
   **Recommended change:** In combine_frames and loc assignment, keep the 
source field's ArrowDtype when the rebuilt field's Spark type equals the source 
field's, instead of rebuilding it from the Spark type. For fields that 
column_op derives with a new Spark type, build the ArrowDtype with the 
arguments the NumPy branch passes: the session's 
spark.sql.execution.arrow.useLargeVarTypes setting, and for TimestampType a 
timestamp representation that matches how pandas-on-Spark represents 
TimestampType values (naive microseconds), so the rebuild neither asserts nor 
adds a zone the source did not have. Add mapping, loc assignment and 
ops-on-different-frames tests for timestamp, large, dictionary and nested Arrow 
types.
   
   **Why this works:** Carrying the source ArrowDtype means a carried-through 
column keeps exactly the Arrow type it had, whether that is large_string, a 
dictionary or list variant, or a timestamp unit or zone, so no rebuild can 
narrow it or reach to_arrow_type's TimestampType assertion. The remaining 
rebuild passes the arguments to_arrow_type needs, so it returns an ArrowDtype 
for every Spark type pandas-on-Spark produces.
   
   **Scope:** Carry the source ArrowDtype through fields whose Spark type is 
unchanged, and build new ArrowDtypes with the arguments to_arrow_type needs.
   
   **Risks:** Carrying the source dtype applies only to ArrowDtype source 
fields; other dtypes keep the base-branch rebuild, so categorical and pandas 
extension dtype handling is unchanged. Index levels merged from two frames 
whose ArrowDtypes differ need a rule for which dtype wins, falling back to the 
rebuild with full arguments.
   
   **Constraints:** The rebuild must not assert or raise for any Spark type 
pandas-on-Spark produces, including timestamps nested in arrays, maps and 
structs. It must stay consistent with the ArrowDtype timestamp conversions that 
the DataTypeOps repair adds, so restored timestamps keep the field's 
representation.
   
   **Success:** Loc assignment and operations across DataFrames on an 
ArrowDtype timestamp column succeed and keep the column's ArrowDtype. 
ArrowDtype large_string, dictionary and large_list columns keep their exact 
dtype after loc assignment and operations across DataFrames. 
spark_type_to_pandas_dtype with use_arrow_dtypes returns an ArrowDtype for 
TimestampType and nested timestamp types without an AssertionError, and honors 
spark.sql.execution.arrow.useLargeVarTypes.
   
   **Verification:**
   - **Regression:** Loc assignment into, and an operation across DataFrames 
on, naive and zoned ArrowDtype timestamp columns succeeds and keeps each 
column's dtype.
   - **Regression:** ArrowDtype large_string, dictionary-encoded string and 
large_list columns keep their exact dtype through loc assignment and operations 
across DataFrames, for data columns and index levels.
   - **Behavior:** The Arrow rebuild returns an ArrowDtype for TimestampType, 
for arrays and structs of timestamps, and for string types with 
useLargeVarTypes on and off.



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