Repository navigation
[SPARK-60586][CONNECT] Export Arrow tables through the Arrow C Stream Interface #108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
d7cebc3
Export Arrow tables through the C Stream interface
dbtsai afb69bc
Use arrow-rs reader conversion for the C Stream handoff
dbtsai d89c01b
Simplify Arrow handoff tests and add live-server smoke cases
dbtsai fe79d54
Skip Arrow handoff tests when protoc is unavailable
dbtsai e60aa53
[SPARK-60586][CONNECT] Strengthen Arrow handoff regression coverage
dbtsai e0eb002
[SPARK-60586][CONNECT] Run native Arrow smoke tests in CI
dbtsai 0234d2f
[SPARK-60586][CONNECT] Clarify RSS reproduction Python paths
dbtsai f23423e
[SPARK-60586][CONNECT] Move Arrow handoff review notes to maintainer …
dbtsai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| //! Export decoded Spark results using arrow-rs's PyArrow reader conversion. | ||
|
|
||
| use std::sync::Arc; | ||
|
|
||
| use arrow::datatypes::{DataType, Field, Schema}; | ||
| use arrow::ipc::writer::FileWriter; | ||
| use arrow::pyarrow::IntoPyArrow; | ||
| use arrow::record_batch::{RecordBatch, RecordBatchIterator, RecordBatchReader}; | ||
| use pyo3::exceptions::{PyRuntimeError, PyValueError}; | ||
| use pyo3::prelude::*; | ||
| use pyo3::types::PyBytes; | ||
|
|
||
| /// Share compatible value and offset buffers with PyArrow in one reader import. | ||
| /// | ||
| /// Batches have already been collected; this does not stream the network response. | ||
| /// Spark result maps are unsorted and result fields are not dictionary-encoded. | ||
| /// An empty vector retains the existing empty-schema behavior. | ||
| pub(crate) fn record_batches_to_pyarrow( | ||
| py: Python<'_>, | ||
| batches: Vec<RecordBatch>, | ||
| ) -> PyResult<Py<PyAny>> { | ||
| let schema = batches | ||
| .first() | ||
| .map(|batch| batch.schema()) | ||
| .unwrap_or_else(|| Arc::new(Schema::empty())); | ||
| // RecordBatchIterator does not validate schemas. Check before either path, | ||
| // including metadata, so later batches are not relabeled with the first schema. | ||
| if batches.iter().any(|batch| batch.schema_ref() != &schema) { | ||
| return Err(PyValueError::new_err( | ||
| "Arrow record batches have inconsistent schemas", | ||
| )); | ||
| } | ||
| if schema.fields().iter().any(|field| field_needs_ipc(field)) { | ||
| // Arrow 58.3 panics on NUL-containing C strings inside the C stream | ||
| // `get_schema` callback. Unwinding across that extern "C" boundary | ||
| // aborts Python instead of raising an exception. Check before export, | ||
| // then reuse the collected batches for IPC without another request. | ||
| // CString::new(...).unwrap() in FFI_ArrowSchema::try_new / with_name: | ||
| // https://github.com/apache/arrow-rs/blob/58.3.0/arrow-schema/src/ffi.rs#L148 | ||
| // https://github.com/apache/arrow-rs/blob/58.3.0/arrow-schema/src/ffi.rs#L174 | ||
| let bytes = py | ||
| .detach(|| -> arrow::error::Result<Vec<u8>> { | ||
| let mut bytes = Vec::new(); | ||
| let mut writer = FileWriter::try_new(&mut bytes, &schema)?; | ||
| for batch in &batches { | ||
| writer.write(batch)?; | ||
| } | ||
| writer.finish()?; | ||
| drop(writer); | ||
| Ok(bytes) | ||
| }) | ||
| .map_err(|error| PyRuntimeError::new_err(error.to_string()))?; | ||
| return Ok(py | ||
| .import("pyarrow")? | ||
| .getattr("ipc")? | ||
| .call_method1("open_file", (PyBytes::new(py, &bytes),))? | ||
| .call_method0("read_all")? | ||
| .unbind()); | ||
| } | ||
|
|
||
| let reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new( | ||
| batches.into_iter().map(Ok), | ||
| schema, | ||
| )); | ||
| Ok(reader.into_pyarrow(py)?.call_method0("read_all")?.unbind()) | ||
| } | ||
|
|
||
| fn field_needs_ipc(field: &Field) -> bool { | ||
| field.name().contains('\0') || data_type_needs_ipc(field.data_type()) | ||
| } | ||
|
|
||
| fn data_type_needs_ipc(data_type: &DataType) -> bool { | ||
| match data_type { | ||
| DataType::Timestamp(_, Some(timezone)) => timezone.contains('\0'), | ||
| DataType::List(field) | ||
| | DataType::LargeList(field) | ||
| | DataType::ListView(field) | ||
| | DataType::LargeListView(field) | ||
| | DataType::FixedSizeList(field, _) | ||
| | DataType::Map(field, _) => field_needs_ipc(field), | ||
| DataType::Struct(fields) => fields.iter().any(|field| field_needs_ipc(field)), | ||
| DataType::Union(fields, _) => fields.iter().any(|(_, field)| field_needs_ipc(field)), | ||
| DataType::RunEndEncoded(run_ends, values) => { | ||
| field_needs_ipc(run_ends) || field_needs_ipc(values) | ||
| } | ||
| DataType::Dictionary(keys, values) => { | ||
| data_type_needs_ipc(keys) || data_type_needs_ipc(values) | ||
| } | ||
| _ => false, | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| # | ||
| # Licensed to the Apache Software Foundation (ASF) under one or more | ||
| # contributor license agreements. See the NOTICE file distributed with | ||
| # this work for additional information regarding copyright ownership. | ||
| # The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| # (the "License"); you may not use this file except in compliance with | ||
| # the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
| """Native toArrow smoke tests against a live Spark Connect server.""" | ||
|
|
||
| import os | ||
| from datetime import date, datetime, timezone | ||
|
|
||
| import pyarrow as pa | ||
| import pytest | ||
| from pyspark.sql import SparkSession | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def session(): | ||
| remote = os.environ.get("SPARK_REMOTE") | ||
| if not remote: | ||
| pytest.skip("SPARK_REMOTE is required for live-server tests") | ||
| session = SparkSession.builder.remote(remote).getOrCreate() | ||
| try: | ||
| yield session | ||
| finally: | ||
| session.stop() | ||
|
|
||
|
|
||
| def test_to_arrow_nested_null_binary_and_temporal_values(session): | ||
| table = session.sql(""" | ||
| SELECT array(1, CAST(NULL AS INT), 3) AS items, | ||
| named_struct('name', 'spark', 'value', CAST(NULL AS BIGINT)) AS nested, | ||
| X'00FF' AS binary_value, DATE '2020-01-02' AS day, | ||
| TIMESTAMP '2020-01-02 03:04:05+00:00' AS instant | ||
| """).toArrow() | ||
| assert isinstance(table, pa.Table) | ||
| values = table.to_pylist() | ||
| assert len(values) == 1 | ||
| assert values[0] == { | ||
| "items": [1, None, 3], | ||
| "nested": {"name": "spark", "value": None}, | ||
| "binary_value": b"\x00\xff", | ||
| "day": date(2020, 1, 2), | ||
| "instant": datetime(2020, 1, 2, 3, 4, 5, tzinfo=timezone.utc), | ||
| } | ||
|
|
||
|
|
||
| def test_to_arrow_numeric_range(session): | ||
| table = session.range(10000).toArrow() | ||
| assert table.num_rows == 10000 | ||
| assert table.column("id").to_pylist() == list(range(10000)) | ||
|
|
||
|
|
||
| def test_to_arrow_empty_result(session): | ||
| table = session.range(0).toArrow() | ||
| assert isinstance(table, pa.Table) | ||
| assert table.num_rows == 0 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Carrying over from #103:
pyproject.tomlstill declarespyarrow>=10.0.0(L30), but this step is the only CI run of the handoff tests, and it gets the latest PyArrow from L93 (26.0.0 in this head's run). The preflight for older PyArrow is gone, andtoArrow()now goes through PyArrow's privateRecordBatchReader._import_from_c(arrow-pyarrow lib.rs#L460-L466) instead of the publicpa.ipc.open_file, so the local PyArrow 10 run is the only evidence for the floor. Could CI add a leg pinned topyarrow==10.0.0? If that isn't practical, could the docs state which PyArrow versions are tested?