You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "Spenserrrr (via GitHub)" <gi...@apache.org> on 2026/07/29 06:09:55 UTC
[PR] [SPARK-54945][PYTHON] Add tests for pa.Array.to_pandas with zero copy [spark]
Spenserrrr opened a new pull request, #57624:
URL: https://github.com/apache/spark/pull/57624
### What changes were proposed in this pull request?
This PR adds a golden-file test that monitors the zero-copy behavior of `pa.Array.to_pandas(zero_copy_only=True)`, under the SPARK-54936 umbrella for detecting upstream PyArrow/pandas behavior drift.
It adds `PyArrowArrayToPandasZeroCopyTests` as a new subclass in the existing `python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py` (reusing the shared `_PyArrowToPandasTestBase` and the centralized golden-matrix driver), plus a `_numpy_shares_arrow_buffer` helper on the base class.
The golden file records two things per source Arrow array:
- **`zero_copy_only=True`**: PyArrow's own verdict for whether the Arrow -> pandas conversion is zero-copy (`Series[dtype]`) or requires a copy (`ERR@ArrowInvalid`).
- **`numpy shares arrow buffer`**: an *independent* verification (via `np.shares_memory`) of whether the default `to_pandas()` result physically shares memory with a source Arrow buffer. This does not simply trust PyArrow's flag; it measures the actual buffer sharing.
The row set targets the layout properties that determine zero-copy -- no-null vs null primitives (across integer widths and float), bool, string/binary, temporal types across units, sliced (offset) arrays, and single- vs multi-chunk ChunkedArrays -- rather than re-enumerating every Arrow type (that is already covered by `test_pyarrow_arrow_to_pandas_default.py`).
**Scope note:** this PR intentionally covers the commonly-used NumPy-backed `zero_copy_only` path. Testing the Arrow-backed path (`types_mapper=pd.ArrowDtype`), and whether/how to verify zero-copy independently of PyArrow's flag across the pandas 2 -> 3 transition, are open design questions being discussed separately before finalizing. Opened as a draft to make the code diff visible for that discussion.
### Why are the changes needed?
PySpark relies on `pa.Array.to_pandas` throughout its conversion layer (`python/pyspark/sql/pandas/conversion.py`), and whether a given Arrow type converts to pandas without copying its buffers directly affects the memory and latency of `toPandas` and pandas UDFs. Pinning this behavior in a golden file lets CI fail loudly if it drifts across PyArrow/pandas/NumPy upgrades, instead of silently regressing performance.
### Does this PR introduce _any_ user-facing change?
No. This is a test-only change.
### How was this patch tested?
This is itself a test. It runs without a Spark session (it exercises PyArrow/pandas directly). Verified both with `SPARK_GENERATE_GOLDEN_FILES=1` (regenerating and eyeballing the golden file) and without the flag (comparing against the committed golden file), on pandas 2.3.3, pyarrow 24.0.0, numpy 2.4.1. ruff check + format pass.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Opus 4.8)
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-54945][PYTHON] Add tests for pa.Array.to_pandas with zero copy [spark]
Posted by "Yicong-Huang (via GitHub)" <gi...@apache.org>.
Yicong-Huang commented on code in PR #57624:
URL: https://github.com/apache/spark/pull/57624#discussion_r3708380224
##########
python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py:
##########
@@ -258,6 +309,182 @@ def compute_cell(row_name, col_name):
)
+@unittest.skipIf(
+ not have_pyarrow or not have_pandas or not have_numpy,
+ pyarrow_requirement_message or pandas_requirement_message or numpy_requirement_message,
+)
+class PyArrowArrayToPandasZeroCopyTests(_PyArrowToPandasTestBase):
+ """
+ Tests pa.Array.to_pandas(zero_copy_only=True) via golden file comparison.
+
+ PySpark converts Arrow data to (numpy-backed) pandas objects throughout its
+ conversion layer (``python/pyspark/sql/pandas/conversion.py``); whether a
+ given Arrow type can make that conversion WITHOUT copying its buffers
+ directly affects the memory and latency of ``toPandas`` and pandas UDFs.
+ ``zero_copy_only=True`` makes PyArrow raise ``ArrowInvalid`` instead of
+ silently copying, so it is the natural probe for "is this conversion
+ zero-copy?". These tests record, per Arrow type, whether the conversion is
+ zero-copy so CI fails loudly if that changes across pandas/PyArrow/NumPy
+ upgrades.
+
+ Two output columns are recorded for each source array:
+
+ - ``zero_copy_only=True``: PyArrow's own verdict -- ``Series[dtype]`` when the
+ conversion is zero-copy, or ``ERR@ArrowInvalid`` when a copy is required.
+ - ``numpy shares arrow buffer``: an INDEPENDENT verification (via
+ ``np.shares_memory``) of whether the default ``to_pandas()`` result
+ actually shares memory with the Arrow buffer. This does not simply trust
+ PyArrow's flag; it confirms the physical sharing. The two columns are
+ expected to agree except in vacuous or backend-specific cases (e.g. empty
+ arrays, or pandas 3 arrow-backed string where the flag reports zero-copy
+ but ``to_numpy()`` materializes) -- such differences are pinned as data.
+
+ The row set targets the layout properties that determine zero-copy, rather
+ than re-enumerating every Arrow type (that is covered by
+ ``test_pyarrow_arrow_to_pandas_default.py``): fixed-width numerics with and
+ without nulls, bool, string/binary, temporal types across units, sliced
+ (offset) arrays, and single- vs multi-chunk ChunkedArrays.
+ """
+
+ def _build_source_arrays(self):
+ """Build an ordered dict of named source PyArrow arrays for testing."""
+ sources = {}
+
+ # =====================================================================
+ # Fixed-width numerics WITHOUT nulls: the canonical zero-copy case --
+ # the Arrow value buffer already matches numpy's layout exactly.
+ # =====================================================================
+ for bits, pa_type in [
+ (8, pa.int8()),
+ (16, pa.int16()),
+ (32, pa.int32()),
+ (64, pa.int64()),
+ ]:
+ sources[f"int{bits}:no-null"] = pa.array([0, 1, -1], pa_type)
+ sources["uint32:no-null"] = pa.array([0, 1, 2], pa.uint32())
+ sources["float32:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float32())
+ sources["float64:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float64())
+
+ # =====================================================================
+ # Same numerics WITH a null: Arrow tracks nulls in a separate validity
+ # bitmap that numpy has no equivalent for, so pandas must promote/rebuild
+ # (e.g. int -> float64 with NaN) -- a copy.
+ # =====================================================================
+ sources["int32:with-null"] = pa.array([0, 1, None], pa.int32())
+ sources["int64:with-null"] = pa.array([0, 1, None], pa.int64())
+ sources["float64:with-null"] = pa.array([0.0, 1.5, None], pa.float64())
+
+ # =====================================================================
+ # Boolean: Arrow stores bits (1 bit/value); numpy uses 1 byte/value, so
+ # the buffer must be unpacked -- always a copy, even without nulls.
+ # =====================================================================
+ sources["bool:no-null"] = pa.array([True, False, True], pa.bool_())
+ sources["bool:with-null"] = pa.array([True, None, False], pa.bool_())
+
+ # =====================================================================
+ # String / binary: variable-length data materialized into an object
+ # array of Python str/bytes -- always a copy.
+ # =====================================================================
+ sources["string:no-null"] = pa.array(["hello", "world", ""], pa.string())
+ sources["binary:no-null"] = pa.array([b"hello", b"world"], pa.binary())
+
+ # =====================================================================
+ # Temporal types. Fixed-width timestamp/duration convert zero-copy
+ # without nulls (they map to numpy datetime64/timedelta64); date and
+ # time map to object dtype and therefore always copy. A nullable
+ # timestamp requires a copy (bitmap reconciliation, like the numerics).
+ # =====================================================================
+ dt = datetime.datetime(2024, 1, 1, 12, 0, 0)
+ for unit in ["s", "ms", "us", "ns"]:
+ sources[f"timestamp[{unit}]:no-null"] = pa.array([dt, dt], pa.timestamp(unit))
+ sources["timestamp[us]:with-null"] = pa.array([dt, None], pa.timestamp("us"))
+ td = datetime.timedelta(days=1)
+ sources["duration[us]:no-null"] = pa.array([td, td], pa.duration("us"))
+ sources["date32:no-null"] = pa.array(
+ [datetime.date(2024, 1, 1), datetime.date(2024, 6, 15)], pa.date32()
+ )
+ sources["time64[us]:no-null"] = pa.array(
+ [datetime.time(12, 30), datetime.time(18, 45)], pa.time64("us")
+ )
+
+ # =====================================================================
+ # Sliced (offset) arrays: still zero-copy when the slice views a
+ # contiguous no-null primitive region, but the numpy data starts partway
+ # into the parent buffer -- the case that defeats naive address equality.
+ # =====================================================================
+ sources["int64:sliced"] = pa.array(list(range(10)), pa.int64()).slice(2, 3)
+ sources["int64:sliced-with-null"] = pa.array([1, 2, None, 4, 5], pa.int64()).slice(1, 3)
+
+ # =====================================================================
+ # ChunkedArray: a single chunk is zero-copy, but multiple chunks must be
+ # concatenated into one contiguous numpy buffer -- a copy. This is the
+ # common shape in real PySpark, where each partition is its own chunk.
+ # =====================================================================
+ sources["int64:single-chunk"] = pa.chunked_array([pa.array([1, 2, 3], pa.int64())])
+ sources["int64:multi-chunk"] = pa.chunked_array(
+ [pa.array([1, 2], pa.int64()), pa.array([3, 4], pa.int64())]
+ )
+
+ # =====================================================================
+ # Empty and nested (controls). Empty reports zero-copy (nothing to copy)
+ # but shares no buffer; nested types materialize to object -- a copy.
+ # =====================================================================
+ sources["int64:empty"] = pa.array([], pa.int64())
+ sources["string:empty"] = pa.array([], pa.string())
+ sources["list<int64>:no-null"] = pa.array([[1, 2], [3]], pa.list_(pa.int64()))
+ sources["struct:no-null"] = pa.array([{"x": 1}, {"x": 2}], pa.struct([("x", pa.int64())]))
+
+ return sources
+
+ # Output column recording PyArrow's own zero-copy verdict.
+ COL_ZERO_COPY_ONLY = "zero_copy_only=True"
+
+ # Output column independently verifying physical memory sharing.
+ COL_SHARES_BUFFER = "numpy shares arrow buffer"
+
+ def test_to_pandas_zero_copy_only(self):
+ """Test pa.Array.to_pandas(zero_copy_only=True) against golden file."""
+ sources = self._build_source_arrays()
+ row_names = list(sources.keys())
+ col_names = [
+ "pyarrow array",
+ self.COL_ZERO_COPY_ONLY,
+ self.COL_SHARES_BUFFER,
+ ]
+
+ # Version-specific expected values go here, keyed by (row, col), when a
+ # newer pandas/PyArrow/NumPy legitimately changes a cell's output.
+ overrides: dict[tuple[str, str], str] = {}
Review Comment:
Confirmed -- I re-ran pyarrow 18-25 on pandas 2.3.3 and 3.0.5, zero mismatches, so the two-tier override matches the Arrow-backed boundary. Good catch on the tz-aware timestamp; recording both columns as data is the right call.
##########
python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py:
##########
@@ -258,6 +309,182 @@ def compute_cell(row_name, col_name):
)
+@unittest.skipIf(
+ not have_pyarrow or not have_pandas or not have_numpy,
+ pyarrow_requirement_message or pandas_requirement_message or numpy_requirement_message,
+)
+class PyArrowArrayToPandasZeroCopyTests(_PyArrowToPandasTestBase):
+ """
+ Tests pa.Array.to_pandas(zero_copy_only=True) via golden file comparison.
+
+ PySpark converts Arrow data to (numpy-backed) pandas objects throughout its
+ conversion layer (``python/pyspark/sql/pandas/conversion.py``); whether a
+ given Arrow type can make that conversion WITHOUT copying its buffers
+ directly affects the memory and latency of ``toPandas`` and pandas UDFs.
+ ``zero_copy_only=True`` makes PyArrow raise ``ArrowInvalid`` instead of
+ silently copying, so it is the natural probe for "is this conversion
+ zero-copy?". These tests record, per Arrow type, whether the conversion is
+ zero-copy so CI fails loudly if that changes across pandas/PyArrow/NumPy
+ upgrades.
+
+ Two output columns are recorded for each source array:
+
+ - ``zero_copy_only=True``: PyArrow's own verdict -- ``Series[dtype]`` when the
+ conversion is zero-copy, or ``ERR@ArrowInvalid`` when a copy is required.
+ - ``numpy shares arrow buffer``: an INDEPENDENT verification (via
+ ``np.shares_memory``) of whether the default ``to_pandas()`` result
+ actually shares memory with the Arrow buffer. This does not simply trust
+ PyArrow's flag; it confirms the physical sharing. The two columns are
+ expected to agree except in vacuous or backend-specific cases (e.g. empty
+ arrays, or pandas 3 arrow-backed string where the flag reports zero-copy
+ but ``to_numpy()`` materializes) -- such differences are pinned as data.
+
+ The row set targets the layout properties that determine zero-copy, rather
+ than re-enumerating every Arrow type (that is covered by
+ ``test_pyarrow_arrow_to_pandas_default.py``): fixed-width numerics with and
+ without nulls, bool, string/binary, temporal types across units, sliced
+ (offset) arrays, and single- vs multi-chunk ChunkedArrays.
+ """
+
+ def _build_source_arrays(self):
+ """Build an ordered dict of named source PyArrow arrays for testing."""
+ sources = {}
+
+ # =====================================================================
+ # Fixed-width numerics WITHOUT nulls: the canonical zero-copy case --
+ # the Arrow value buffer already matches numpy's layout exactly.
+ # =====================================================================
+ for bits, pa_type in [
+ (8, pa.int8()),
+ (16, pa.int16()),
+ (32, pa.int32()),
+ (64, pa.int64()),
+ ]:
+ sources[f"int{bits}:no-null"] = pa.array([0, 1, -1], pa_type)
+ sources["uint32:no-null"] = pa.array([0, 1, 2], pa.uint32())
+ sources["float32:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float32())
+ sources["float64:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float64())
+
+ # =====================================================================
+ # Same numerics WITH a null: Arrow tracks nulls in a separate validity
+ # bitmap that numpy has no equivalent for, so pandas must promote/rebuild
+ # (e.g. int -> float64 with NaN) -- a copy.
+ # =====================================================================
+ sources["int32:with-null"] = pa.array([0, 1, None], pa.int32())
+ sources["int64:with-null"] = pa.array([0, 1, None], pa.int64())
+ sources["float64:with-null"] = pa.array([0.0, 1.5, None], pa.float64())
+
+ # =====================================================================
+ # Boolean: Arrow stores bits (1 bit/value); numpy uses 1 byte/value, so
+ # the buffer must be unpacked -- always a copy, even without nulls.
+ # =====================================================================
+ sources["bool:no-null"] = pa.array([True, False, True], pa.bool_())
+ sources["bool:with-null"] = pa.array([True, None, False], pa.bool_())
+
+ # =====================================================================
+ # String / binary: variable-length data materialized into an object
+ # array of Python str/bytes -- always a copy.
+ # =====================================================================
+ sources["string:no-null"] = pa.array(["hello", "world", ""], pa.string())
+ sources["binary:no-null"] = pa.array([b"hello", b"world"], pa.binary())
+
+ # =====================================================================
+ # Temporal types. Fixed-width timestamp/duration convert zero-copy
+ # without nulls (they map to numpy datetime64/timedelta64); date and
+ # time map to object dtype and therefore always copy. A nullable
+ # timestamp requires a copy (bitmap reconciliation, like the numerics).
+ # =====================================================================
+ dt = datetime.datetime(2024, 1, 1, 12, 0, 0)
+ for unit in ["s", "ms", "us", "ns"]:
+ sources[f"timestamp[{unit}]:no-null"] = pa.array([dt, dt], pa.timestamp(unit))
+ sources["timestamp[us]:with-null"] = pa.array([dt, None], pa.timestamp("us"))
+ td = datetime.timedelta(days=1)
+ sources["duration[us]:no-null"] = pa.array([td, td], pa.duration("us"))
+ sources["date32:no-null"] = pa.array(
+ [datetime.date(2024, 1, 1), datetime.date(2024, 6, 15)], pa.date32()
+ )
+ sources["time64[us]:no-null"] = pa.array(
+ [datetime.time(12, 30), datetime.time(18, 45)], pa.time64("us")
+ )
+
+ # =====================================================================
+ # Sliced (offset) arrays: still zero-copy when the slice views a
+ # contiguous no-null primitive region, but the numpy data starts partway
+ # into the parent buffer -- the case that defeats naive address equality.
+ # =====================================================================
+ sources["int64:sliced"] = pa.array(list(range(10)), pa.int64()).slice(2, 3)
+ sources["int64:sliced-with-null"] = pa.array([1, 2, None, 4, 5], pa.int64()).slice(1, 3)
+
+ # =====================================================================
+ # ChunkedArray: a single chunk is zero-copy, but multiple chunks must be
+ # concatenated into one contiguous numpy buffer -- a copy. This is the
+ # common shape in real PySpark, where each partition is its own chunk.
+ # =====================================================================
+ sources["int64:single-chunk"] = pa.chunked_array([pa.array([1, 2, 3], pa.int64())])
+ sources["int64:multi-chunk"] = pa.chunked_array(
+ [pa.array([1, 2], pa.int64()), pa.array([3, 4], pa.int64())]
+ )
+
+ # =====================================================================
+ # Empty and nested (controls). Empty reports zero-copy (nothing to copy)
+ # but shares no buffer; nested types materialize to object -- a copy.
+ # =====================================================================
+ sources["int64:empty"] = pa.array([], pa.int64())
+ sources["string:empty"] = pa.array([], pa.string())
+ sources["list<int64>:no-null"] = pa.array([[1, 2], [3]], pa.list_(pa.int64()))
+ sources["struct:no-null"] = pa.array([{"x": 1}, {"x": 2}], pa.struct([("x", pa.int64())]))
Review Comment:
Reusing the default test's rows directly is better than what I suggested -- coverage stays in sync now. Thanks!
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-54945][PYTHON] Add tests for pa.Array.to_pandas with zero copy [spark]
Posted by "Spenserrrr (via GitHub)" <gi...@apache.org>.
Spenserrrr commented on code in PR #57624:
URL: https://github.com/apache/spark/pull/57624#discussion_r3708144842
##########
python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py:
##########
@@ -258,6 +309,182 @@ def compute_cell(row_name, col_name):
)
+@unittest.skipIf(
+ not have_pyarrow or not have_pandas or not have_numpy,
+ pyarrow_requirement_message or pandas_requirement_message or numpy_requirement_message,
+)
+class PyArrowArrayToPandasZeroCopyTests(_PyArrowToPandasTestBase):
+ """
+ Tests pa.Array.to_pandas(zero_copy_only=True) via golden file comparison.
+
+ PySpark converts Arrow data to (numpy-backed) pandas objects throughout its
+ conversion layer (``python/pyspark/sql/pandas/conversion.py``); whether a
+ given Arrow type can make that conversion WITHOUT copying its buffers
+ directly affects the memory and latency of ``toPandas`` and pandas UDFs.
+ ``zero_copy_only=True`` makes PyArrow raise ``ArrowInvalid`` instead of
+ silently copying, so it is the natural probe for "is this conversion
+ zero-copy?". These tests record, per Arrow type, whether the conversion is
+ zero-copy so CI fails loudly if that changes across pandas/PyArrow/NumPy
+ upgrades.
+
+ Two output columns are recorded for each source array:
+
+ - ``zero_copy_only=True``: PyArrow's own verdict -- ``Series[dtype]`` when the
+ conversion is zero-copy, or ``ERR@ArrowInvalid`` when a copy is required.
+ - ``numpy shares arrow buffer``: an INDEPENDENT verification (via
+ ``np.shares_memory``) of whether the default ``to_pandas()`` result
+ actually shares memory with the Arrow buffer. This does not simply trust
+ PyArrow's flag; it confirms the physical sharing. The two columns are
+ expected to agree except in vacuous or backend-specific cases (e.g. empty
+ arrays, or pandas 3 arrow-backed string where the flag reports zero-copy
+ but ``to_numpy()`` materializes) -- such differences are pinned as data.
+
+ The row set targets the layout properties that determine zero-copy, rather
+ than re-enumerating every Arrow type (that is covered by
+ ``test_pyarrow_arrow_to_pandas_default.py``): fixed-width numerics with and
+ without nulls, bool, string/binary, temporal types across units, sliced
+ (offset) arrays, and single- vs multi-chunk ChunkedArrays.
+ """
+
+ def _build_source_arrays(self):
+ """Build an ordered dict of named source PyArrow arrays for testing."""
+ sources = {}
+
+ # =====================================================================
+ # Fixed-width numerics WITHOUT nulls: the canonical zero-copy case --
+ # the Arrow value buffer already matches numpy's layout exactly.
+ # =====================================================================
+ for bits, pa_type in [
+ (8, pa.int8()),
+ (16, pa.int16()),
+ (32, pa.int32()),
+ (64, pa.int64()),
+ ]:
+ sources[f"int{bits}:no-null"] = pa.array([0, 1, -1], pa_type)
+ sources["uint32:no-null"] = pa.array([0, 1, 2], pa.uint32())
+ sources["float32:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float32())
+ sources["float64:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float64())
+
+ # =====================================================================
+ # Same numerics WITH a null: Arrow tracks nulls in a separate validity
+ # bitmap that numpy has no equivalent for, so pandas must promote/rebuild
+ # (e.g. int -> float64 with NaN) -- a copy.
+ # =====================================================================
+ sources["int32:with-null"] = pa.array([0, 1, None], pa.int32())
+ sources["int64:with-null"] = pa.array([0, 1, None], pa.int64())
+ sources["float64:with-null"] = pa.array([0.0, 1.5, None], pa.float64())
+
+ # =====================================================================
+ # Boolean: Arrow stores bits (1 bit/value); numpy uses 1 byte/value, so
+ # the buffer must be unpacked -- always a copy, even without nulls.
+ # =====================================================================
+ sources["bool:no-null"] = pa.array([True, False, True], pa.bool_())
+ sources["bool:with-null"] = pa.array([True, None, False], pa.bool_())
+
+ # =====================================================================
+ # String / binary: variable-length data materialized into an object
+ # array of Python str/bytes -- always a copy.
+ # =====================================================================
+ sources["string:no-null"] = pa.array(["hello", "world", ""], pa.string())
+ sources["binary:no-null"] = pa.array([b"hello", b"world"], pa.binary())
+
+ # =====================================================================
+ # Temporal types. Fixed-width timestamp/duration convert zero-copy
+ # without nulls (they map to numpy datetime64/timedelta64); date and
+ # time map to object dtype and therefore always copy. A nullable
+ # timestamp requires a copy (bitmap reconciliation, like the numerics).
+ # =====================================================================
+ dt = datetime.datetime(2024, 1, 1, 12, 0, 0)
+ for unit in ["s", "ms", "us", "ns"]:
+ sources[f"timestamp[{unit}]:no-null"] = pa.array([dt, dt], pa.timestamp(unit))
+ sources["timestamp[us]:with-null"] = pa.array([dt, None], pa.timestamp("us"))
+ td = datetime.timedelta(days=1)
+ sources["duration[us]:no-null"] = pa.array([td, td], pa.duration("us"))
+ sources["date32:no-null"] = pa.array(
+ [datetime.date(2024, 1, 1), datetime.date(2024, 6, 15)], pa.date32()
+ )
+ sources["time64[us]:no-null"] = pa.array(
+ [datetime.time(12, 30), datetime.time(18, 45)], pa.time64("us")
+ )
+
+ # =====================================================================
+ # Sliced (offset) arrays: still zero-copy when the slice views a
+ # contiguous no-null primitive region, but the numpy data starts partway
+ # into the parent buffer -- the case that defeats naive address equality.
+ # =====================================================================
+ sources["int64:sliced"] = pa.array(list(range(10)), pa.int64()).slice(2, 3)
+ sources["int64:sliced-with-null"] = pa.array([1, 2, None, 4, 5], pa.int64()).slice(1, 3)
+
+ # =====================================================================
+ # ChunkedArray: a single chunk is zero-copy, but multiple chunks must be
+ # concatenated into one contiguous numpy buffer -- a copy. This is the
+ # common shape in real PySpark, where each partition is its own chunk.
+ # =====================================================================
+ sources["int64:single-chunk"] = pa.chunked_array([pa.array([1, 2, 3], pa.int64())])
+ sources["int64:multi-chunk"] = pa.chunked_array(
+ [pa.array([1, 2], pa.int64()), pa.array([3, 4], pa.int64())]
+ )
+
+ # =====================================================================
+ # Empty and nested (controls). Empty reports zero-copy (nothing to copy)
+ # but shares no buffer; nested types materialize to object -- a copy.
+ # =====================================================================
+ sources["int64:empty"] = pa.array([], pa.int64())
+ sources["string:empty"] = pa.array([], pa.string())
+ sources["list<int64>:no-null"] = pa.array([[1, 2], [3]], pa.list_(pa.int64()))
+ sources["struct:no-null"] = pa.array([{"x": 1}, {"x": 2}], pa.struct([("x", pa.int64())]))
+
+ return sources
+
+ # Output column recording PyArrow's own zero-copy verdict.
+ COL_ZERO_COPY_ONLY = "zero_copy_only=True"
+
+ # Output column independently verifying physical memory sharing.
+ COL_SHARES_BUFFER = "numpy shares arrow buffer"
+
+ def test_to_pandas_zero_copy_only(self):
+ """Test pa.Array.to_pandas(zero_copy_only=True) against golden file."""
+ sources = self._build_source_arrays()
+ row_names = list(sources.keys())
+ col_names = [
+ "pyarrow array",
+ self.COL_ZERO_COPY_ONLY,
+ self.COL_SHARES_BUFFER,
+ ]
+
+ # Version-specific expected values go here, keyed by (row, col), when a
+ # newer pandas/PyArrow/NumPy legitimately changes a cell's output.
+ overrides: dict[tuple[str, str], str] = {}
Review Comment:
I re-ran against the expanded golden and added a pandas 3 axis: PyArrow 18 to 25 with pandas 2 and 3, 16/16 pass. No pa.__version__ override needed on pandas 2. Note that pandas 3 did need a two-tier override: pandas 3 alone only changes the dtype (object to str), while pandas 3 and pyarrow >= 24 is what makes the conversion Arrow-backed so zero_copy_only succeeds.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-54945][PYTHON] Add tests for pa.Array.to_pandas with zero copy [spark]
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on code in PR #57624:
URL: https://github.com/apache/spark/pull/57624#discussion_r3708585101
##########
python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py:
##########
@@ -99,6 +105,77 @@ def _to_pandas_cell(self, arr, **to_pandas_kwargs) -> str:
except Exception as e:
return f"ERR@{type(e).__name__}"
+ @staticmethod
+ def _arrow_buffers(arrow_obj):
+ """
+ Every non-null buffer backing ``arrow_obj``.
+
+ A ChunkedArray has no buffers of its own -- its data lives in its chunks --
+ so it is expanded first. ``None`` entries (e.g. an absent validity bitmap)
+ are skipped.
+ """
+ if isinstance(arrow_obj, pa.ChunkedArray):
+ chunks = [arrow_obj.chunk(i) for i in range(arrow_obj.num_chunks)]
+ else:
+ chunks = [arrow_obj]
+
+ buffers = []
+ for chunk in chunks:
+ for buffer in chunk.buffers():
+ if buffer is not None:
+ buffers.append(buffer)
+ return buffers
+
+ @classmethod
+ def _verify_zero_copy(cls, arr, **to_pandas_kwargs) -> str:
+ """
+ Independently verify whether ``to_pandas`` reused ``arr``'s buffers,
+ instead of trusting PyArrow's own ``zero_copy_only`` verdict.
+
+ The check inspects whatever storage pandas returned rather than assuming a
+ numpy-backed Series, so it stays correct as pandas moves more dtypes to
+ Arrow-backed storage.
+
+ Returns ``"zero-copy"``, ``"copied"``, or ``"ERR@<ExceptionClass>"``.
+ """
+ try:
+ series = arr.to_pandas(**to_pandas_kwargs)
+ except Exception as e:
+ return f"ERR@{type(e).__name__}"
+
+ backing_array = series.array
+
+ # Arrow-backed result: compare buffer addresses, reading the stored data
+ # back through the public __arrow_array__ protocol. to_numpy() would
+ # materialize a copy here and wrongly report no sharing. Keying on the
+ # protocol rather than on ArrowDtype also covers dtypes that are
+ # Arrow-backed without being ArrowDtype, such as pandas 3's string.
+ if hasattr(backing_array, "__arrow_array__"):
+ stored = pa.array(backing_array)
+ source_addresses = {buffer.address for buffer in cls._arrow_buffers(arr)}
+ for buffer in cls._arrow_buffers(stored):
+ if buffer.address in source_addresses:
+ return "zero-copy"
Review Comment:
Minor concern (forward-looking): _arrow_buffers includes validity, offset, and value buffers, and this loop returns `zero-copy` when *any* source buffer is present in pandas storage. A conversion could retain an offset or validity buffer while materializing the values, masking the data-copy regression this test is meant to detect. Could we compare the value buffer specifically (as described in the design doc), require all relevant buffers to match, or report a distinct partial-copy result?
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-54945][PYTHON] Add tests for pa.Array.to_pandas with zero copy [spark]
Posted by "Spenserrrr (via GitHub)" <gi...@apache.org>.
Spenserrrr commented on PR #57624:
URL: https://github.com/apache/spark/pull/57624#issuecomment-5114231900
Hi @Yicong-Huang @zhengruifeng! Could you take a look when you have a moment? Thank you!
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-54945][PYTHON] Add tests for pa.Array.to_pandas with zero copy [spark]
Posted by "Spenserrrr (via GitHub)" <gi...@apache.org>.
Spenserrrr commented on code in PR #57624:
URL: https://github.com/apache/spark/pull/57624#discussion_r3708134335
##########
python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py:
##########
@@ -258,6 +309,182 @@ def compute_cell(row_name, col_name):
)
+@unittest.skipIf(
+ not have_pyarrow or not have_pandas or not have_numpy,
+ pyarrow_requirement_message or pandas_requirement_message or numpy_requirement_message,
+)
+class PyArrowArrayToPandasZeroCopyTests(_PyArrowToPandasTestBase):
+ """
+ Tests pa.Array.to_pandas(zero_copy_only=True) via golden file comparison.
+
+ PySpark converts Arrow data to (numpy-backed) pandas objects throughout its
+ conversion layer (``python/pyspark/sql/pandas/conversion.py``); whether a
+ given Arrow type can make that conversion WITHOUT copying its buffers
+ directly affects the memory and latency of ``toPandas`` and pandas UDFs.
+ ``zero_copy_only=True`` makes PyArrow raise ``ArrowInvalid`` instead of
+ silently copying, so it is the natural probe for "is this conversion
+ zero-copy?". These tests record, per Arrow type, whether the conversion is
+ zero-copy so CI fails loudly if that changes across pandas/PyArrow/NumPy
+ upgrades.
+
+ Two output columns are recorded for each source array:
+
+ - ``zero_copy_only=True``: PyArrow's own verdict -- ``Series[dtype]`` when the
+ conversion is zero-copy, or ``ERR@ArrowInvalid`` when a copy is required.
+ - ``numpy shares arrow buffer``: an INDEPENDENT verification (via
+ ``np.shares_memory``) of whether the default ``to_pandas()`` result
+ actually shares memory with the Arrow buffer. This does not simply trust
+ PyArrow's flag; it confirms the physical sharing. The two columns are
+ expected to agree except in vacuous or backend-specific cases (e.g. empty
+ arrays, or pandas 3 arrow-backed string where the flag reports zero-copy
+ but ``to_numpy()`` materializes) -- such differences are pinned as data.
+
+ The row set targets the layout properties that determine zero-copy, rather
+ than re-enumerating every Arrow type (that is covered by
+ ``test_pyarrow_arrow_to_pandas_default.py``): fixed-width numerics with and
+ without nulls, bool, string/binary, temporal types across units, sliced
+ (offset) arrays, and single- vs multi-chunk ChunkedArrays.
+ """
+
+ def _build_source_arrays(self):
+ """Build an ordered dict of named source PyArrow arrays for testing."""
+ sources = {}
+
+ # =====================================================================
+ # Fixed-width numerics WITHOUT nulls: the canonical zero-copy case --
+ # the Arrow value buffer already matches numpy's layout exactly.
+ # =====================================================================
+ for bits, pa_type in [
+ (8, pa.int8()),
+ (16, pa.int16()),
+ (32, pa.int32()),
+ (64, pa.int64()),
+ ]:
+ sources[f"int{bits}:no-null"] = pa.array([0, 1, -1], pa_type)
+ sources["uint32:no-null"] = pa.array([0, 1, 2], pa.uint32())
+ sources["float32:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float32())
+ sources["float64:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float64())
+
+ # =====================================================================
+ # Same numerics WITH a null: Arrow tracks nulls in a separate validity
+ # bitmap that numpy has no equivalent for, so pandas must promote/rebuild
+ # (e.g. int -> float64 with NaN) -- a copy.
+ # =====================================================================
+ sources["int32:with-null"] = pa.array([0, 1, None], pa.int32())
+ sources["int64:with-null"] = pa.array([0, 1, None], pa.int64())
+ sources["float64:with-null"] = pa.array([0.0, 1.5, None], pa.float64())
+
+ # =====================================================================
+ # Boolean: Arrow stores bits (1 bit/value); numpy uses 1 byte/value, so
+ # the buffer must be unpacked -- always a copy, even without nulls.
+ # =====================================================================
+ sources["bool:no-null"] = pa.array([True, False, True], pa.bool_())
+ sources["bool:with-null"] = pa.array([True, None, False], pa.bool_())
+
+ # =====================================================================
+ # String / binary: variable-length data materialized into an object
+ # array of Python str/bytes -- always a copy.
+ # =====================================================================
+ sources["string:no-null"] = pa.array(["hello", "world", ""], pa.string())
+ sources["binary:no-null"] = pa.array([b"hello", b"world"], pa.binary())
+
+ # =====================================================================
+ # Temporal types. Fixed-width timestamp/duration convert zero-copy
+ # without nulls (they map to numpy datetime64/timedelta64); date and
+ # time map to object dtype and therefore always copy. A nullable
+ # timestamp requires a copy (bitmap reconciliation, like the numerics).
+ # =====================================================================
+ dt = datetime.datetime(2024, 1, 1, 12, 0, 0)
+ for unit in ["s", "ms", "us", "ns"]:
+ sources[f"timestamp[{unit}]:no-null"] = pa.array([dt, dt], pa.timestamp(unit))
+ sources["timestamp[us]:with-null"] = pa.array([dt, None], pa.timestamp("us"))
+ td = datetime.timedelta(days=1)
+ sources["duration[us]:no-null"] = pa.array([td, td], pa.duration("us"))
+ sources["date32:no-null"] = pa.array(
+ [datetime.date(2024, 1, 1), datetime.date(2024, 6, 15)], pa.date32()
+ )
+ sources["time64[us]:no-null"] = pa.array(
+ [datetime.time(12, 30), datetime.time(18, 45)], pa.time64("us")
+ )
+
+ # =====================================================================
+ # Sliced (offset) arrays: still zero-copy when the slice views a
+ # contiguous no-null primitive region, but the numpy data starts partway
+ # into the parent buffer -- the case that defeats naive address equality.
+ # =====================================================================
+ sources["int64:sliced"] = pa.array(list(range(10)), pa.int64()).slice(2, 3)
+ sources["int64:sliced-with-null"] = pa.array([1, 2, None, 4, 5], pa.int64()).slice(1, 3)
+
+ # =====================================================================
+ # ChunkedArray: a single chunk is zero-copy, but multiple chunks must be
+ # concatenated into one contiguous numpy buffer -- a copy. This is the
+ # common shape in real PySpark, where each partition is its own chunk.
+ # =====================================================================
+ sources["int64:single-chunk"] = pa.chunked_array([pa.array([1, 2, 3], pa.int64())])
+ sources["int64:multi-chunk"] = pa.chunked_array(
+ [pa.array([1, 2], pa.int64()), pa.array([3, 4], pa.int64())]
+ )
+
+ # =====================================================================
+ # Empty and nested (controls). Empty reports zero-copy (nothing to copy)
+ # but shares no buffer; nested types materialize to object -- a copy.
+ # =====================================================================
+ sources["int64:empty"] = pa.array([], pa.int64())
+ sources["string:empty"] = pa.array([], pa.string())
+ sources["list<int64>:no-null"] = pa.array([[1, 2], [3]], pa.list_(pa.int64()))
+ sources["struct:no-null"] = pa.array([{"x": 1}, {"x": 2}], pa.struct([("x", pa.int64())]))
+
+ return sources
+
+ # Output column recording PyArrow's own zero-copy verdict.
+ COL_ZERO_COPY_ONLY = "zero_copy_only=True"
+
+ # Output column independently verifying physical memory sharing.
+ COL_SHARES_BUFFER = "numpy shares arrow buffer"
+
+ def test_to_pandas_zero_copy_only(self):
+ """Test pa.Array.to_pandas(zero_copy_only=True) against golden file."""
+ sources = self._build_source_arrays()
+ row_names = list(sources.keys())
+ col_names = [
+ "pyarrow array",
+ self.COL_ZERO_COPY_ONLY,
+ self.COL_SHARES_BUFFER,
+ ]
+
+ # Version-specific expected values go here, keyed by (row, col), when a
+ # newer pandas/PyArrow/NumPy legitimately changes a cell's output.
+ overrides: dict[tuple[str, str], str] = {}
Review Comment:
Thanks for the advice @Yicong-Huang! I reuse the default test's rows directly and append a few more meaningful tests for this flag.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-54945][PYTHON] Add tests for pa.Array.to_pandas with zero copy [spark]
Posted by "Spenserrrr (via GitHub)" <gi...@apache.org>.
Spenserrrr commented on code in PR #57624:
URL: https://github.com/apache/spark/pull/57624#discussion_r3709002782
##########
python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py:
##########
@@ -99,6 +105,77 @@ def _to_pandas_cell(self, arr, **to_pandas_kwargs) -> str:
except Exception as e:
return f"ERR@{type(e).__name__}"
+ @staticmethod
+ def _arrow_buffers(arrow_obj):
+ """
+ Every non-null buffer backing ``arrow_obj``.
+
+ A ChunkedArray has no buffers of its own -- its data lives in its chunks --
+ so it is expanded first. ``None`` entries (e.g. an absent validity bitmap)
+ are skipped.
+ """
+ if isinstance(arrow_obj, pa.ChunkedArray):
+ chunks = [arrow_obj.chunk(i) for i in range(arrow_obj.num_chunks)]
+ else:
+ chunks = [arrow_obj]
+
+ buffers = []
+ for chunk in chunks:
+ for buffer in chunk.buffers():
+ if buffer is not None:
+ buffers.append(buffer)
+ return buffers
+
+ @classmethod
+ def _verify_zero_copy(cls, arr, **to_pandas_kwargs) -> str:
+ """
+ Independently verify whether ``to_pandas`` reused ``arr``'s buffers,
+ instead of trusting PyArrow's own ``zero_copy_only`` verdict.
+
+ The check inspects whatever storage pandas returned rather than assuming a
+ numpy-backed Series, so it stays correct as pandas moves more dtypes to
+ Arrow-backed storage.
+
+ Returns ``"zero-copy"``, ``"copied"``, or ``"ERR@<ExceptionClass>"``.
+ """
+ try:
+ series = arr.to_pandas(**to_pandas_kwargs)
+ except Exception as e:
+ return f"ERR@{type(e).__name__}"
+
+ backing_array = series.array
+
+ # Arrow-backed result: compare buffer addresses, reading the stored data
+ # back through the public __arrow_array__ protocol. to_numpy() would
+ # materialize a copy here and wrongly report no sharing. Keying on the
+ # protocol rather than on ArrowDtype also covers dtypes that are
+ # Arrow-backed without being ArrowDtype, such as pandas 3's string.
+ if hasattr(backing_array, "__arrow_array__"):
+ stored = pa.array(backing_array)
+ source_addresses = {buffer.address for buffer in cls._arrow_buffers(arr)}
+ for buffer in cls._arrow_buffers(stored):
+ if buffer.address in source_addresses:
+ return "zero-copy"
Review Comment:
Thanks for the advice @zhengruifeng! Actually, this problem already appears. On pandas 2 it's harmless. A numpy result is one dense block, so any/all are the same question. But on pandas 3 + pyarrow >= 24, strings become ArrowStringArray with 3 buffers of their own. string:standard borrows the values while pandas rebuilds the 32-bit offsets as 64-bit because it normalizes string to large_string. Thus, only 1 of the 2 buffers is shared. The old check can't tell this.
Thus, I count how many of the result's buffers were borrowed, then report zero-copy (all), partial-copy (some), copied (none). The edit is in the new commit. The golden file is identical, and in the override section, two rows are changed to partial-copy.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-54945][PYTHON][TEST] Add tests for pa.Array.to_pandas with zero copy [spark]
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on PR #57624:
URL: https://github.com/apache/spark/pull/57624#issuecomment-5175097828
**Merge Summary:**
- merged into master https://github.com/apache/spark/commit/15f12ebf1892ea503c69e3acfc62a4592ca81e91
- merged into branch-4.x https://github.com/apache/spark/commit/85266b32bfb43b8b4858db6a790f07dae9ecbe32
*Posted by `merge_spark_pr.py`*
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-54945][PYTHON][TEST] Add tests for pa.Array.to_pandas with zero copy [spark]
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng closed pull request #57624: [SPARK-54945][PYTHON][TEST] Add tests for pa.Array.to_pandas with zero copy
URL: https://github.com/apache/spark/pull/57624
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-54945][PYTHON] Add tests for pa.Array.to_pandas with zero copy [spark]
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on code in PR #57624:
URL: https://github.com/apache/spark/pull/57624#discussion_r3708585101
##########
python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py:
##########
@@ -99,6 +105,77 @@ def _to_pandas_cell(self, arr, **to_pandas_kwargs) -> str:
except Exception as e:
return f"ERR@{type(e).__name__}"
+ @staticmethod
+ def _arrow_buffers(arrow_obj):
+ """
+ Every non-null buffer backing ``arrow_obj``.
+
+ A ChunkedArray has no buffers of its own -- its data lives in its chunks --
+ so it is expanded first. ``None`` entries (e.g. an absent validity bitmap)
+ are skipped.
+ """
+ if isinstance(arrow_obj, pa.ChunkedArray):
+ chunks = [arrow_obj.chunk(i) for i in range(arrow_obj.num_chunks)]
+ else:
+ chunks = [arrow_obj]
+
+ buffers = []
+ for chunk in chunks:
+ for buffer in chunk.buffers():
+ if buffer is not None:
+ buffers.append(buffer)
+ return buffers
+
+ @classmethod
+ def _verify_zero_copy(cls, arr, **to_pandas_kwargs) -> str:
+ """
+ Independently verify whether ``to_pandas`` reused ``arr``'s buffers,
+ instead of trusting PyArrow's own ``zero_copy_only`` verdict.
+
+ The check inspects whatever storage pandas returned rather than assuming a
+ numpy-backed Series, so it stays correct as pandas moves more dtypes to
+ Arrow-backed storage.
+
+ Returns ``"zero-copy"``, ``"copied"``, or ``"ERR@<ExceptionClass>"``.
+ """
+ try:
+ series = arr.to_pandas(**to_pandas_kwargs)
+ except Exception as e:
+ return f"ERR@{type(e).__name__}"
+
+ backing_array = series.array
+
+ # Arrow-backed result: compare buffer addresses, reading the stored data
+ # back through the public __arrow_array__ protocol. to_numpy() would
+ # materialize a copy here and wrongly report no sharing. Keying on the
+ # protocol rather than on ArrowDtype also covers dtypes that are
+ # Arrow-backed without being ArrowDtype, such as pandas 3's string.
+ if hasattr(backing_array, "__arrow_array__"):
+ stored = pa.array(backing_array)
+ source_addresses = {buffer.address for buffer in cls._arrow_buffers(arr)}
+ for buffer in cls._arrow_buffers(stored):
+ if buffer.address in source_addresses:
+ return "zero-copy"
Review Comment:
_arrow_buffers includes validity, offset, and value buffers, and this loop returns `zero-copy` when *any* source buffer is present in pandas storage. A conversion could retain an offset or validity buffer while materializing the values, masking the data-copy regression this test is meant to detect. Could we compare the value buffer specifically (as described in the design doc), require all relevant buffers to match, or report a distinct partial-copy result?
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-54945][PYTHON] Add tests for pa.Array.to_pandas with zero copy [spark]
Posted by "Yicong-Huang (via GitHub)" <gi...@apache.org>.
Yicong-Huang commented on code in PR #57624:
URL: https://github.com/apache/spark/pull/57624#discussion_r3707424545
##########
python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py:
##########
@@ -258,6 +309,182 @@ def compute_cell(row_name, col_name):
)
+@unittest.skipIf(
+ not have_pyarrow or not have_pandas or not have_numpy,
+ pyarrow_requirement_message or pandas_requirement_message or numpy_requirement_message,
+)
+class PyArrowArrayToPandasZeroCopyTests(_PyArrowToPandasTestBase):
+ """
+ Tests pa.Array.to_pandas(zero_copy_only=True) via golden file comparison.
+
+ PySpark converts Arrow data to (numpy-backed) pandas objects throughout its
+ conversion layer (``python/pyspark/sql/pandas/conversion.py``); whether a
+ given Arrow type can make that conversion WITHOUT copying its buffers
+ directly affects the memory and latency of ``toPandas`` and pandas UDFs.
+ ``zero_copy_only=True`` makes PyArrow raise ``ArrowInvalid`` instead of
+ silently copying, so it is the natural probe for "is this conversion
+ zero-copy?". These tests record, per Arrow type, whether the conversion is
+ zero-copy so CI fails loudly if that changes across pandas/PyArrow/NumPy
+ upgrades.
+
+ Two output columns are recorded for each source array:
+
+ - ``zero_copy_only=True``: PyArrow's own verdict -- ``Series[dtype]`` when the
+ conversion is zero-copy, or ``ERR@ArrowInvalid`` when a copy is required.
+ - ``numpy shares arrow buffer``: an INDEPENDENT verification (via
+ ``np.shares_memory``) of whether the default ``to_pandas()`` result
+ actually shares memory with the Arrow buffer. This does not simply trust
+ PyArrow's flag; it confirms the physical sharing. The two columns are
+ expected to agree except in vacuous or backend-specific cases (e.g. empty
+ arrays, or pandas 3 arrow-backed string where the flag reports zero-copy
+ but ``to_numpy()`` materializes) -- such differences are pinned as data.
+
+ The row set targets the layout properties that determine zero-copy, rather
+ than re-enumerating every Arrow type (that is covered by
+ ``test_pyarrow_arrow_to_pandas_default.py``): fixed-width numerics with and
+ without nulls, bool, string/binary, temporal types across units, sliced
+ (offset) arrays, and single- vs multi-chunk ChunkedArrays.
+ """
+
+ def _build_source_arrays(self):
+ """Build an ordered dict of named source PyArrow arrays for testing."""
+ sources = {}
+
+ # =====================================================================
+ # Fixed-width numerics WITHOUT nulls: the canonical zero-copy case --
+ # the Arrow value buffer already matches numpy's layout exactly.
+ # =====================================================================
+ for bits, pa_type in [
+ (8, pa.int8()),
+ (16, pa.int16()),
+ (32, pa.int32()),
+ (64, pa.int64()),
+ ]:
+ sources[f"int{bits}:no-null"] = pa.array([0, 1, -1], pa_type)
+ sources["uint32:no-null"] = pa.array([0, 1, 2], pa.uint32())
+ sources["float32:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float32())
+ sources["float64:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float64())
+
+ # =====================================================================
+ # Same numerics WITH a null: Arrow tracks nulls in a separate validity
+ # bitmap that numpy has no equivalent for, so pandas must promote/rebuild
+ # (e.g. int -> float64 with NaN) -- a copy.
+ # =====================================================================
+ sources["int32:with-null"] = pa.array([0, 1, None], pa.int32())
+ sources["int64:with-null"] = pa.array([0, 1, None], pa.int64())
+ sources["float64:with-null"] = pa.array([0.0, 1.5, None], pa.float64())
+
+ # =====================================================================
+ # Boolean: Arrow stores bits (1 bit/value); numpy uses 1 byte/value, so
+ # the buffer must be unpacked -- always a copy, even without nulls.
+ # =====================================================================
+ sources["bool:no-null"] = pa.array([True, False, True], pa.bool_())
+ sources["bool:with-null"] = pa.array([True, None, False], pa.bool_())
+
+ # =====================================================================
+ # String / binary: variable-length data materialized into an object
+ # array of Python str/bytes -- always a copy.
+ # =====================================================================
+ sources["string:no-null"] = pa.array(["hello", "world", ""], pa.string())
+ sources["binary:no-null"] = pa.array([b"hello", b"world"], pa.binary())
+
+ # =====================================================================
+ # Temporal types. Fixed-width timestamp/duration convert zero-copy
+ # without nulls (they map to numpy datetime64/timedelta64); date and
+ # time map to object dtype and therefore always copy. A nullable
+ # timestamp requires a copy (bitmap reconciliation, like the numerics).
+ # =====================================================================
+ dt = datetime.datetime(2024, 1, 1, 12, 0, 0)
+ for unit in ["s", "ms", "us", "ns"]:
+ sources[f"timestamp[{unit}]:no-null"] = pa.array([dt, dt], pa.timestamp(unit))
+ sources["timestamp[us]:with-null"] = pa.array([dt, None], pa.timestamp("us"))
+ td = datetime.timedelta(days=1)
+ sources["duration[us]:no-null"] = pa.array([td, td], pa.duration("us"))
+ sources["date32:no-null"] = pa.array(
+ [datetime.date(2024, 1, 1), datetime.date(2024, 6, 15)], pa.date32()
+ )
+ sources["time64[us]:no-null"] = pa.array(
+ [datetime.time(12, 30), datetime.time(18, 45)], pa.time64("us")
+ )
+
+ # =====================================================================
+ # Sliced (offset) arrays: still zero-copy when the slice views a
+ # contiguous no-null primitive region, but the numpy data starts partway
+ # into the parent buffer -- the case that defeats naive address equality.
+ # =====================================================================
+ sources["int64:sliced"] = pa.array(list(range(10)), pa.int64()).slice(2, 3)
+ sources["int64:sliced-with-null"] = pa.array([1, 2, None, 4, 5], pa.int64()).slice(1, 3)
+
+ # =====================================================================
+ # ChunkedArray: a single chunk is zero-copy, but multiple chunks must be
+ # concatenated into one contiguous numpy buffer -- a copy. This is the
+ # common shape in real PySpark, where each partition is its own chunk.
+ # =====================================================================
+ sources["int64:single-chunk"] = pa.chunked_array([pa.array([1, 2, 3], pa.int64())])
+ sources["int64:multi-chunk"] = pa.chunked_array(
+ [pa.array([1, 2], pa.int64()), pa.array([3, 4], pa.int64())]
+ )
+
+ # =====================================================================
+ # Empty and nested (controls). Empty reports zero-copy (nothing to copy)
+ # but shares no buffer; nested types materialize to object -- a copy.
+ # =====================================================================
+ sources["int64:empty"] = pa.array([], pa.int64())
+ sources["string:empty"] = pa.array([], pa.string())
+ sources["list<int64>:no-null"] = pa.array([[1, 2], [3]], pa.list_(pa.int64()))
+ sources["struct:no-null"] = pa.array([{"x": 1}, {"x": 2}], pa.struct([("x", pa.int64())]))
Review Comment:
The nested-type coverage looks a bit incomplete here -- just `list<int64>:no-null` and `struct<x:int64>:no-null`. The sibling `default` test covers the full nested set: `map`, `dictionary`, `large_list`, `fixed_size_list`, nullable/empty variants, and deep nesting (`list<list>`, `list<struct>`, `list<map>`, `struct<struct>`, `struct<list>`, `struct<map>`, `map<string,list>`, `map<string,struct>`, `map<string,map>`).
Could you bring the nested rows here in line with that set? Mirroring the `default` test's nested coverage keeps the two golden files consistent and pins the same shapes' `zero_copy_only` verdict.
##########
python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py:
##########
@@ -258,6 +309,182 @@ def compute_cell(row_name, col_name):
)
+@unittest.skipIf(
+ not have_pyarrow or not have_pandas or not have_numpy,
+ pyarrow_requirement_message or pandas_requirement_message or numpy_requirement_message,
+)
+class PyArrowArrayToPandasZeroCopyTests(_PyArrowToPandasTestBase):
+ """
+ Tests pa.Array.to_pandas(zero_copy_only=True) via golden file comparison.
+
+ PySpark converts Arrow data to (numpy-backed) pandas objects throughout its
+ conversion layer (``python/pyspark/sql/pandas/conversion.py``); whether a
+ given Arrow type can make that conversion WITHOUT copying its buffers
+ directly affects the memory and latency of ``toPandas`` and pandas UDFs.
+ ``zero_copy_only=True`` makes PyArrow raise ``ArrowInvalid`` instead of
+ silently copying, so it is the natural probe for "is this conversion
+ zero-copy?". These tests record, per Arrow type, whether the conversion is
+ zero-copy so CI fails loudly if that changes across pandas/PyArrow/NumPy
+ upgrades.
+
+ Two output columns are recorded for each source array:
+
+ - ``zero_copy_only=True``: PyArrow's own verdict -- ``Series[dtype]`` when the
+ conversion is zero-copy, or ``ERR@ArrowInvalid`` when a copy is required.
+ - ``numpy shares arrow buffer``: an INDEPENDENT verification (via
+ ``np.shares_memory``) of whether the default ``to_pandas()`` result
+ actually shares memory with the Arrow buffer. This does not simply trust
+ PyArrow's flag; it confirms the physical sharing. The two columns are
+ expected to agree except in vacuous or backend-specific cases (e.g. empty
+ arrays, or pandas 3 arrow-backed string where the flag reports zero-copy
+ but ``to_numpy()`` materializes) -- such differences are pinned as data.
+
+ The row set targets the layout properties that determine zero-copy, rather
+ than re-enumerating every Arrow type (that is covered by
+ ``test_pyarrow_arrow_to_pandas_default.py``): fixed-width numerics with and
+ without nulls, bool, string/binary, temporal types across units, sliced
+ (offset) arrays, and single- vs multi-chunk ChunkedArrays.
+ """
+
+ def _build_source_arrays(self):
+ """Build an ordered dict of named source PyArrow arrays for testing."""
+ sources = {}
+
+ # =====================================================================
+ # Fixed-width numerics WITHOUT nulls: the canonical zero-copy case --
+ # the Arrow value buffer already matches numpy's layout exactly.
+ # =====================================================================
+ for bits, pa_type in [
+ (8, pa.int8()),
+ (16, pa.int16()),
+ (32, pa.int32()),
+ (64, pa.int64()),
+ ]:
+ sources[f"int{bits}:no-null"] = pa.array([0, 1, -1], pa_type)
+ sources["uint32:no-null"] = pa.array([0, 1, 2], pa.uint32())
+ sources["float32:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float32())
+ sources["float64:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float64())
+
+ # =====================================================================
+ # Same numerics WITH a null: Arrow tracks nulls in a separate validity
+ # bitmap that numpy has no equivalent for, so pandas must promote/rebuild
+ # (e.g. int -> float64 with NaN) -- a copy.
+ # =====================================================================
+ sources["int32:with-null"] = pa.array([0, 1, None], pa.int32())
+ sources["int64:with-null"] = pa.array([0, 1, None], pa.int64())
+ sources["float64:with-null"] = pa.array([0.0, 1.5, None], pa.float64())
+
+ # =====================================================================
+ # Boolean: Arrow stores bits (1 bit/value); numpy uses 1 byte/value, so
+ # the buffer must be unpacked -- always a copy, even without nulls.
+ # =====================================================================
+ sources["bool:no-null"] = pa.array([True, False, True], pa.bool_())
+ sources["bool:with-null"] = pa.array([True, None, False], pa.bool_())
+
+ # =====================================================================
+ # String / binary: variable-length data materialized into an object
+ # array of Python str/bytes -- always a copy.
+ # =====================================================================
+ sources["string:no-null"] = pa.array(["hello", "world", ""], pa.string())
+ sources["binary:no-null"] = pa.array([b"hello", b"world"], pa.binary())
+
+ # =====================================================================
+ # Temporal types. Fixed-width timestamp/duration convert zero-copy
+ # without nulls (they map to numpy datetime64/timedelta64); date and
+ # time map to object dtype and therefore always copy. A nullable
+ # timestamp requires a copy (bitmap reconciliation, like the numerics).
+ # =====================================================================
+ dt = datetime.datetime(2024, 1, 1, 12, 0, 0)
+ for unit in ["s", "ms", "us", "ns"]:
+ sources[f"timestamp[{unit}]:no-null"] = pa.array([dt, dt], pa.timestamp(unit))
+ sources["timestamp[us]:with-null"] = pa.array([dt, None], pa.timestamp("us"))
+ td = datetime.timedelta(days=1)
+ sources["duration[us]:no-null"] = pa.array([td, td], pa.duration("us"))
+ sources["date32:no-null"] = pa.array(
+ [datetime.date(2024, 1, 1), datetime.date(2024, 6, 15)], pa.date32()
+ )
+ sources["time64[us]:no-null"] = pa.array(
+ [datetime.time(12, 30), datetime.time(18, 45)], pa.time64("us")
+ )
+
+ # =====================================================================
+ # Sliced (offset) arrays: still zero-copy when the slice views a
+ # contiguous no-null primitive region, but the numpy data starts partway
+ # into the parent buffer -- the case that defeats naive address equality.
+ # =====================================================================
+ sources["int64:sliced"] = pa.array(list(range(10)), pa.int64()).slice(2, 3)
+ sources["int64:sliced-with-null"] = pa.array([1, 2, None, 4, 5], pa.int64()).slice(1, 3)
+
+ # =====================================================================
+ # ChunkedArray: a single chunk is zero-copy, but multiple chunks must be
+ # concatenated into one contiguous numpy buffer -- a copy. This is the
+ # common shape in real PySpark, where each partition is its own chunk.
+ # =====================================================================
+ sources["int64:single-chunk"] = pa.chunked_array([pa.array([1, 2, 3], pa.int64())])
+ sources["int64:multi-chunk"] = pa.chunked_array(
+ [pa.array([1, 2], pa.int64()), pa.array([3, 4], pa.int64())]
+ )
+
+ # =====================================================================
+ # Empty and nested (controls). Empty reports zero-copy (nothing to copy)
+ # but shares no buffer; nested types materialize to object -- a copy.
+ # =====================================================================
+ sources["int64:empty"] = pa.array([], pa.int64())
+ sources["string:empty"] = pa.array([], pa.string())
+ sources["list<int64>:no-null"] = pa.array([[1, 2], [3]], pa.list_(pa.int64()))
+ sources["struct:no-null"] = pa.array([{"x": 1}, {"x": 2}], pa.struct([("x", pa.int64())]))
+
+ return sources
+
+ # Output column recording PyArrow's own zero-copy verdict.
+ COL_ZERO_COPY_ONLY = "zero_copy_only=True"
+
+ # Output column independently verifying physical memory sharing.
+ COL_SHARES_BUFFER = "numpy shares arrow buffer"
+
+ def test_to_pandas_zero_copy_only(self):
+ """Test pa.Array.to_pandas(zero_copy_only=True) against golden file."""
+ sources = self._build_source_arrays()
+ row_names = list(sources.keys())
+ col_names = [
+ "pyarrow array",
+ self.COL_ZERO_COPY_ONLY,
+ self.COL_SHARES_BUFFER,
+ ]
+
+ # Version-specific expected values go here, keyed by (row, col), when a
+ # newer pandas/PyArrow/NumPy legitimately changes a cell's output.
+ overrides: dict[tuple[str, str], str] = {}
Review Comment:
This golden is generated on pyarrow 24.0.0 and there's no `pa.__version__` override (only the pandas>=3 one). Did you check the `string:*` / `binary` rows across the supported pyarrow range (`>=18`), or just on 24.0.0?
Asking because the sibling `test_pyarrow_arrow_to_pandas_default.py` needed a `pyarrow>=24.0.0` override for a pandas-3 / pyarrow-24 string-dtype change -- if this test is ever run under pandas 3 or a newer pyarrow, the string rows here might need the same `pa.__version__` guard.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-54945][PYTHON] Add tests for pa.Array.to_pandas with zero copy [spark]
Posted by "Spenserrrr (via GitHub)" <gi...@apache.org>.
Spenserrrr commented on code in PR #57624:
URL: https://github.com/apache/spark/pull/57624#discussion_r3708134335
##########
python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py:
##########
@@ -258,6 +309,182 @@ def compute_cell(row_name, col_name):
)
+@unittest.skipIf(
+ not have_pyarrow or not have_pandas or not have_numpy,
+ pyarrow_requirement_message or pandas_requirement_message or numpy_requirement_message,
+)
+class PyArrowArrayToPandasZeroCopyTests(_PyArrowToPandasTestBase):
+ """
+ Tests pa.Array.to_pandas(zero_copy_only=True) via golden file comparison.
+
+ PySpark converts Arrow data to (numpy-backed) pandas objects throughout its
+ conversion layer (``python/pyspark/sql/pandas/conversion.py``); whether a
+ given Arrow type can make that conversion WITHOUT copying its buffers
+ directly affects the memory and latency of ``toPandas`` and pandas UDFs.
+ ``zero_copy_only=True`` makes PyArrow raise ``ArrowInvalid`` instead of
+ silently copying, so it is the natural probe for "is this conversion
+ zero-copy?". These tests record, per Arrow type, whether the conversion is
+ zero-copy so CI fails loudly if that changes across pandas/PyArrow/NumPy
+ upgrades.
+
+ Two output columns are recorded for each source array:
+
+ - ``zero_copy_only=True``: PyArrow's own verdict -- ``Series[dtype]`` when the
+ conversion is zero-copy, or ``ERR@ArrowInvalid`` when a copy is required.
+ - ``numpy shares arrow buffer``: an INDEPENDENT verification (via
+ ``np.shares_memory``) of whether the default ``to_pandas()`` result
+ actually shares memory with the Arrow buffer. This does not simply trust
+ PyArrow's flag; it confirms the physical sharing. The two columns are
+ expected to agree except in vacuous or backend-specific cases (e.g. empty
+ arrays, or pandas 3 arrow-backed string where the flag reports zero-copy
+ but ``to_numpy()`` materializes) -- such differences are pinned as data.
+
+ The row set targets the layout properties that determine zero-copy, rather
+ than re-enumerating every Arrow type (that is covered by
+ ``test_pyarrow_arrow_to_pandas_default.py``): fixed-width numerics with and
+ without nulls, bool, string/binary, temporal types across units, sliced
+ (offset) arrays, and single- vs multi-chunk ChunkedArrays.
+ """
+
+ def _build_source_arrays(self):
+ """Build an ordered dict of named source PyArrow arrays for testing."""
+ sources = {}
+
+ # =====================================================================
+ # Fixed-width numerics WITHOUT nulls: the canonical zero-copy case --
+ # the Arrow value buffer already matches numpy's layout exactly.
+ # =====================================================================
+ for bits, pa_type in [
+ (8, pa.int8()),
+ (16, pa.int16()),
+ (32, pa.int32()),
+ (64, pa.int64()),
+ ]:
+ sources[f"int{bits}:no-null"] = pa.array([0, 1, -1], pa_type)
+ sources["uint32:no-null"] = pa.array([0, 1, 2], pa.uint32())
+ sources["float32:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float32())
+ sources["float64:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float64())
+
+ # =====================================================================
+ # Same numerics WITH a null: Arrow tracks nulls in a separate validity
+ # bitmap that numpy has no equivalent for, so pandas must promote/rebuild
+ # (e.g. int -> float64 with NaN) -- a copy.
+ # =====================================================================
+ sources["int32:with-null"] = pa.array([0, 1, None], pa.int32())
+ sources["int64:with-null"] = pa.array([0, 1, None], pa.int64())
+ sources["float64:with-null"] = pa.array([0.0, 1.5, None], pa.float64())
+
+ # =====================================================================
+ # Boolean: Arrow stores bits (1 bit/value); numpy uses 1 byte/value, so
+ # the buffer must be unpacked -- always a copy, even without nulls.
+ # =====================================================================
+ sources["bool:no-null"] = pa.array([True, False, True], pa.bool_())
+ sources["bool:with-null"] = pa.array([True, None, False], pa.bool_())
+
+ # =====================================================================
+ # String / binary: variable-length data materialized into an object
+ # array of Python str/bytes -- always a copy.
+ # =====================================================================
+ sources["string:no-null"] = pa.array(["hello", "world", ""], pa.string())
+ sources["binary:no-null"] = pa.array([b"hello", b"world"], pa.binary())
+
+ # =====================================================================
+ # Temporal types. Fixed-width timestamp/duration convert zero-copy
+ # without nulls (they map to numpy datetime64/timedelta64); date and
+ # time map to object dtype and therefore always copy. A nullable
+ # timestamp requires a copy (bitmap reconciliation, like the numerics).
+ # =====================================================================
+ dt = datetime.datetime(2024, 1, 1, 12, 0, 0)
+ for unit in ["s", "ms", "us", "ns"]:
+ sources[f"timestamp[{unit}]:no-null"] = pa.array([dt, dt], pa.timestamp(unit))
+ sources["timestamp[us]:with-null"] = pa.array([dt, None], pa.timestamp("us"))
+ td = datetime.timedelta(days=1)
+ sources["duration[us]:no-null"] = pa.array([td, td], pa.duration("us"))
+ sources["date32:no-null"] = pa.array(
+ [datetime.date(2024, 1, 1), datetime.date(2024, 6, 15)], pa.date32()
+ )
+ sources["time64[us]:no-null"] = pa.array(
+ [datetime.time(12, 30), datetime.time(18, 45)], pa.time64("us")
+ )
+
+ # =====================================================================
+ # Sliced (offset) arrays: still zero-copy when the slice views a
+ # contiguous no-null primitive region, but the numpy data starts partway
+ # into the parent buffer -- the case that defeats naive address equality.
+ # =====================================================================
+ sources["int64:sliced"] = pa.array(list(range(10)), pa.int64()).slice(2, 3)
+ sources["int64:sliced-with-null"] = pa.array([1, 2, None, 4, 5], pa.int64()).slice(1, 3)
+
+ # =====================================================================
+ # ChunkedArray: a single chunk is zero-copy, but multiple chunks must be
+ # concatenated into one contiguous numpy buffer -- a copy. This is the
+ # common shape in real PySpark, where each partition is its own chunk.
+ # =====================================================================
+ sources["int64:single-chunk"] = pa.chunked_array([pa.array([1, 2, 3], pa.int64())])
+ sources["int64:multi-chunk"] = pa.chunked_array(
+ [pa.array([1, 2], pa.int64()), pa.array([3, 4], pa.int64())]
+ )
+
+ # =====================================================================
+ # Empty and nested (controls). Empty reports zero-copy (nothing to copy)
+ # but shares no buffer; nested types materialize to object -- a copy.
+ # =====================================================================
+ sources["int64:empty"] = pa.array([], pa.int64())
+ sources["string:empty"] = pa.array([], pa.string())
+ sources["list<int64>:no-null"] = pa.array([[1, 2], [3]], pa.list_(pa.int64()))
+ sources["struct:no-null"] = pa.array([{"x": 1}, {"x": 2}], pa.struct([("x", pa.int64())]))
+
+ return sources
+
+ # Output column recording PyArrow's own zero-copy verdict.
+ COL_ZERO_COPY_ONLY = "zero_copy_only=True"
+
+ # Output column independently verifying physical memory sharing.
+ COL_SHARES_BUFFER = "numpy shares arrow buffer"
+
+ def test_to_pandas_zero_copy_only(self):
+ """Test pa.Array.to_pandas(zero_copy_only=True) against golden file."""
+ sources = self._build_source_arrays()
+ row_names = list(sources.keys())
+ col_names = [
+ "pyarrow array",
+ self.COL_ZERO_COPY_ONLY,
+ self.COL_SHARES_BUFFER,
+ ]
+
+ # Version-specific expected values go here, keyed by (row, col), when a
+ # newer pandas/PyArrow/NumPy legitimately changes a cell's output.
+ overrides: dict[tuple[str, str], str] = {}
Review Comment:
Thanks for the advice @Yicong-Huang! I reuse the default test's rows directly and append a few more meaningful tests for this flag.
##########
python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py:
##########
@@ -258,6 +309,182 @@ def compute_cell(row_name, col_name):
)
+@unittest.skipIf(
+ not have_pyarrow or not have_pandas or not have_numpy,
+ pyarrow_requirement_message or pandas_requirement_message or numpy_requirement_message,
+)
+class PyArrowArrayToPandasZeroCopyTests(_PyArrowToPandasTestBase):
+ """
+ Tests pa.Array.to_pandas(zero_copy_only=True) via golden file comparison.
+
+ PySpark converts Arrow data to (numpy-backed) pandas objects throughout its
+ conversion layer (``python/pyspark/sql/pandas/conversion.py``); whether a
+ given Arrow type can make that conversion WITHOUT copying its buffers
+ directly affects the memory and latency of ``toPandas`` and pandas UDFs.
+ ``zero_copy_only=True`` makes PyArrow raise ``ArrowInvalid`` instead of
+ silently copying, so it is the natural probe for "is this conversion
+ zero-copy?". These tests record, per Arrow type, whether the conversion is
+ zero-copy so CI fails loudly if that changes across pandas/PyArrow/NumPy
+ upgrades.
+
+ Two output columns are recorded for each source array:
+
+ - ``zero_copy_only=True``: PyArrow's own verdict -- ``Series[dtype]`` when the
+ conversion is zero-copy, or ``ERR@ArrowInvalid`` when a copy is required.
+ - ``numpy shares arrow buffer``: an INDEPENDENT verification (via
+ ``np.shares_memory``) of whether the default ``to_pandas()`` result
+ actually shares memory with the Arrow buffer. This does not simply trust
+ PyArrow's flag; it confirms the physical sharing. The two columns are
+ expected to agree except in vacuous or backend-specific cases (e.g. empty
+ arrays, or pandas 3 arrow-backed string where the flag reports zero-copy
+ but ``to_numpy()`` materializes) -- such differences are pinned as data.
+
+ The row set targets the layout properties that determine zero-copy, rather
+ than re-enumerating every Arrow type (that is covered by
+ ``test_pyarrow_arrow_to_pandas_default.py``): fixed-width numerics with and
+ without nulls, bool, string/binary, temporal types across units, sliced
+ (offset) arrays, and single- vs multi-chunk ChunkedArrays.
+ """
+
+ def _build_source_arrays(self):
+ """Build an ordered dict of named source PyArrow arrays for testing."""
+ sources = {}
+
+ # =====================================================================
+ # Fixed-width numerics WITHOUT nulls: the canonical zero-copy case --
+ # the Arrow value buffer already matches numpy's layout exactly.
+ # =====================================================================
+ for bits, pa_type in [
+ (8, pa.int8()),
+ (16, pa.int16()),
+ (32, pa.int32()),
+ (64, pa.int64()),
+ ]:
+ sources[f"int{bits}:no-null"] = pa.array([0, 1, -1], pa_type)
+ sources["uint32:no-null"] = pa.array([0, 1, 2], pa.uint32())
+ sources["float32:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float32())
+ sources["float64:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float64())
+
+ # =====================================================================
+ # Same numerics WITH a null: Arrow tracks nulls in a separate validity
+ # bitmap that numpy has no equivalent for, so pandas must promote/rebuild
+ # (e.g. int -> float64 with NaN) -- a copy.
+ # =====================================================================
+ sources["int32:with-null"] = pa.array([0, 1, None], pa.int32())
+ sources["int64:with-null"] = pa.array([0, 1, None], pa.int64())
+ sources["float64:with-null"] = pa.array([0.0, 1.5, None], pa.float64())
+
+ # =====================================================================
+ # Boolean: Arrow stores bits (1 bit/value); numpy uses 1 byte/value, so
+ # the buffer must be unpacked -- always a copy, even without nulls.
+ # =====================================================================
+ sources["bool:no-null"] = pa.array([True, False, True], pa.bool_())
+ sources["bool:with-null"] = pa.array([True, None, False], pa.bool_())
+
+ # =====================================================================
+ # String / binary: variable-length data materialized into an object
+ # array of Python str/bytes -- always a copy.
+ # =====================================================================
+ sources["string:no-null"] = pa.array(["hello", "world", ""], pa.string())
+ sources["binary:no-null"] = pa.array([b"hello", b"world"], pa.binary())
+
+ # =====================================================================
+ # Temporal types. Fixed-width timestamp/duration convert zero-copy
+ # without nulls (they map to numpy datetime64/timedelta64); date and
+ # time map to object dtype and therefore always copy. A nullable
+ # timestamp requires a copy (bitmap reconciliation, like the numerics).
+ # =====================================================================
+ dt = datetime.datetime(2024, 1, 1, 12, 0, 0)
+ for unit in ["s", "ms", "us", "ns"]:
+ sources[f"timestamp[{unit}]:no-null"] = pa.array([dt, dt], pa.timestamp(unit))
+ sources["timestamp[us]:with-null"] = pa.array([dt, None], pa.timestamp("us"))
+ td = datetime.timedelta(days=1)
+ sources["duration[us]:no-null"] = pa.array([td, td], pa.duration("us"))
+ sources["date32:no-null"] = pa.array(
+ [datetime.date(2024, 1, 1), datetime.date(2024, 6, 15)], pa.date32()
+ )
+ sources["time64[us]:no-null"] = pa.array(
+ [datetime.time(12, 30), datetime.time(18, 45)], pa.time64("us")
+ )
+
+ # =====================================================================
+ # Sliced (offset) arrays: still zero-copy when the slice views a
+ # contiguous no-null primitive region, but the numpy data starts partway
+ # into the parent buffer -- the case that defeats naive address equality.
+ # =====================================================================
+ sources["int64:sliced"] = pa.array(list(range(10)), pa.int64()).slice(2, 3)
+ sources["int64:sliced-with-null"] = pa.array([1, 2, None, 4, 5], pa.int64()).slice(1, 3)
+
+ # =====================================================================
+ # ChunkedArray: a single chunk is zero-copy, but multiple chunks must be
+ # concatenated into one contiguous numpy buffer -- a copy. This is the
+ # common shape in real PySpark, where each partition is its own chunk.
+ # =====================================================================
+ sources["int64:single-chunk"] = pa.chunked_array([pa.array([1, 2, 3], pa.int64())])
+ sources["int64:multi-chunk"] = pa.chunked_array(
+ [pa.array([1, 2], pa.int64()), pa.array([3, 4], pa.int64())]
+ )
+
+ # =====================================================================
+ # Empty and nested (controls). Empty reports zero-copy (nothing to copy)
+ # but shares no buffer; nested types materialize to object -- a copy.
+ # =====================================================================
+ sources["int64:empty"] = pa.array([], pa.int64())
+ sources["string:empty"] = pa.array([], pa.string())
+ sources["list<int64>:no-null"] = pa.array([[1, 2], [3]], pa.list_(pa.int64()))
+ sources["struct:no-null"] = pa.array([{"x": 1}, {"x": 2}], pa.struct([("x", pa.int64())]))
Review Comment:
Thanks for the advice @Yicong-Huang! I reuse the default test's rows directly and append a few more meaningful tests for this flag.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-54945][PYTHON] Add tests for pa.Array.to_pandas with zero copy [spark]
Posted by "Spenserrrr (via GitHub)" <gi...@apache.org>.
Spenserrrr commented on code in PR #57624:
URL: https://github.com/apache/spark/pull/57624#discussion_r3708150313
##########
python/pyspark/tests/upstream/pyarrow/test_pyarrow_arrow_to_pandas_non_default.py:
##########
@@ -258,6 +309,182 @@ def compute_cell(row_name, col_name):
)
+@unittest.skipIf(
+ not have_pyarrow or not have_pandas or not have_numpy,
+ pyarrow_requirement_message or pandas_requirement_message or numpy_requirement_message,
+)
+class PyArrowArrayToPandasZeroCopyTests(_PyArrowToPandasTestBase):
+ """
+ Tests pa.Array.to_pandas(zero_copy_only=True) via golden file comparison.
+
+ PySpark converts Arrow data to (numpy-backed) pandas objects throughout its
+ conversion layer (``python/pyspark/sql/pandas/conversion.py``); whether a
+ given Arrow type can make that conversion WITHOUT copying its buffers
+ directly affects the memory and latency of ``toPandas`` and pandas UDFs.
+ ``zero_copy_only=True`` makes PyArrow raise ``ArrowInvalid`` instead of
+ silently copying, so it is the natural probe for "is this conversion
+ zero-copy?". These tests record, per Arrow type, whether the conversion is
+ zero-copy so CI fails loudly if that changes across pandas/PyArrow/NumPy
+ upgrades.
+
+ Two output columns are recorded for each source array:
+
+ - ``zero_copy_only=True``: PyArrow's own verdict -- ``Series[dtype]`` when the
+ conversion is zero-copy, or ``ERR@ArrowInvalid`` when a copy is required.
+ - ``numpy shares arrow buffer``: an INDEPENDENT verification (via
+ ``np.shares_memory``) of whether the default ``to_pandas()`` result
+ actually shares memory with the Arrow buffer. This does not simply trust
+ PyArrow's flag; it confirms the physical sharing. The two columns are
+ expected to agree except in vacuous or backend-specific cases (e.g. empty
+ arrays, or pandas 3 arrow-backed string where the flag reports zero-copy
+ but ``to_numpy()`` materializes) -- such differences are pinned as data.
+
+ The row set targets the layout properties that determine zero-copy, rather
+ than re-enumerating every Arrow type (that is covered by
+ ``test_pyarrow_arrow_to_pandas_default.py``): fixed-width numerics with and
+ without nulls, bool, string/binary, temporal types across units, sliced
+ (offset) arrays, and single- vs multi-chunk ChunkedArrays.
+ """
+
+ def _build_source_arrays(self):
+ """Build an ordered dict of named source PyArrow arrays for testing."""
+ sources = {}
+
+ # =====================================================================
+ # Fixed-width numerics WITHOUT nulls: the canonical zero-copy case --
+ # the Arrow value buffer already matches numpy's layout exactly.
+ # =====================================================================
+ for bits, pa_type in [
+ (8, pa.int8()),
+ (16, pa.int16()),
+ (32, pa.int32()),
+ (64, pa.int64()),
+ ]:
+ sources[f"int{bits}:no-null"] = pa.array([0, 1, -1], pa_type)
+ sources["uint32:no-null"] = pa.array([0, 1, 2], pa.uint32())
+ sources["float32:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float32())
+ sources["float64:no-null"] = pa.array([0.0, 1.5, -1.5], pa.float64())
+
+ # =====================================================================
+ # Same numerics WITH a null: Arrow tracks nulls in a separate validity
+ # bitmap that numpy has no equivalent for, so pandas must promote/rebuild
+ # (e.g. int -> float64 with NaN) -- a copy.
+ # =====================================================================
+ sources["int32:with-null"] = pa.array([0, 1, None], pa.int32())
+ sources["int64:with-null"] = pa.array([0, 1, None], pa.int64())
+ sources["float64:with-null"] = pa.array([0.0, 1.5, None], pa.float64())
+
+ # =====================================================================
+ # Boolean: Arrow stores bits (1 bit/value); numpy uses 1 byte/value, so
+ # the buffer must be unpacked -- always a copy, even without nulls.
+ # =====================================================================
+ sources["bool:no-null"] = pa.array([True, False, True], pa.bool_())
+ sources["bool:with-null"] = pa.array([True, None, False], pa.bool_())
+
+ # =====================================================================
+ # String / binary: variable-length data materialized into an object
+ # array of Python str/bytes -- always a copy.
+ # =====================================================================
+ sources["string:no-null"] = pa.array(["hello", "world", ""], pa.string())
+ sources["binary:no-null"] = pa.array([b"hello", b"world"], pa.binary())
+
+ # =====================================================================
+ # Temporal types. Fixed-width timestamp/duration convert zero-copy
+ # without nulls (they map to numpy datetime64/timedelta64); date and
+ # time map to object dtype and therefore always copy. A nullable
+ # timestamp requires a copy (bitmap reconciliation, like the numerics).
+ # =====================================================================
+ dt = datetime.datetime(2024, 1, 1, 12, 0, 0)
+ for unit in ["s", "ms", "us", "ns"]:
+ sources[f"timestamp[{unit}]:no-null"] = pa.array([dt, dt], pa.timestamp(unit))
+ sources["timestamp[us]:with-null"] = pa.array([dt, None], pa.timestamp("us"))
+ td = datetime.timedelta(days=1)
+ sources["duration[us]:no-null"] = pa.array([td, td], pa.duration("us"))
+ sources["date32:no-null"] = pa.array(
+ [datetime.date(2024, 1, 1), datetime.date(2024, 6, 15)], pa.date32()
+ )
+ sources["time64[us]:no-null"] = pa.array(
+ [datetime.time(12, 30), datetime.time(18, 45)], pa.time64("us")
+ )
+
+ # =====================================================================
+ # Sliced (offset) arrays: still zero-copy when the slice views a
+ # contiguous no-null primitive region, but the numpy data starts partway
+ # into the parent buffer -- the case that defeats naive address equality.
+ # =====================================================================
+ sources["int64:sliced"] = pa.array(list(range(10)), pa.int64()).slice(2, 3)
+ sources["int64:sliced-with-null"] = pa.array([1, 2, None, 4, 5], pa.int64()).slice(1, 3)
+
+ # =====================================================================
+ # ChunkedArray: a single chunk is zero-copy, but multiple chunks must be
+ # concatenated into one contiguous numpy buffer -- a copy. This is the
+ # common shape in real PySpark, where each partition is its own chunk.
+ # =====================================================================
+ sources["int64:single-chunk"] = pa.chunked_array([pa.array([1, 2, 3], pa.int64())])
+ sources["int64:multi-chunk"] = pa.chunked_array(
+ [pa.array([1, 2], pa.int64()), pa.array([3, 4], pa.int64())]
+ )
+
+ # =====================================================================
+ # Empty and nested (controls). Empty reports zero-copy (nothing to copy)
+ # but shares no buffer; nested types materialize to object -- a copy.
+ # =====================================================================
+ sources["int64:empty"] = pa.array([], pa.int64())
+ sources["string:empty"] = pa.array([], pa.string())
+ sources["list<int64>:no-null"] = pa.array([[1, 2], [3]], pa.list_(pa.int64()))
+ sources["struct:no-null"] = pa.array([{"x": 1}, {"x": 2}], pa.struct([("x", pa.int64())]))
+
+ return sources
+
+ # Output column recording PyArrow's own zero-copy verdict.
+ COL_ZERO_COPY_ONLY = "zero_copy_only=True"
+
+ # Output column independently verifying physical memory sharing.
+ COL_SHARES_BUFFER = "numpy shares arrow buffer"
+
+ def test_to_pandas_zero_copy_only(self):
+ """Test pa.Array.to_pandas(zero_copy_only=True) against golden file."""
+ sources = self._build_source_arrays()
+ row_names = list(sources.keys())
+ col_names = [
+ "pyarrow array",
+ self.COL_ZERO_COPY_ONLY,
+ self.COL_SHARES_BUFFER,
+ ]
+
+ # Version-specific expected values go here, keyed by (row, col), when a
+ # newer pandas/PyArrow/NumPy legitimately changes a cell's output.
+ overrides: dict[tuple[str, str], str] = {}
Review Comment:
Also, there is one thing worth flagging. zero_copy_only=True isn't always accurate. timestamp[us,tz=UTC] reports success but is genuinely copied, which is the only mismatch in 125 rows. to_pandas is two stages: Arrow to numpy is zero-copy, but numpy toSeries copies because DatetimeTZDtype is an extension dtype whose constructor allocates. The flag only describes the first stage. Hence, both columns are recorded as data rather than asserted equal.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org