Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 69 additions & 4 deletions vortex-layout/src/scan/arrow.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use std::error::Error;
use std::sync::Arc;

use arrow_array::Array;
use arrow_array::RecordBatch;
use arrow_array::RecordBatchOptions;
use arrow_array::RecordBatchReader;
use arrow_array::cast::AsArray;
use arrow_schema::ArrowError;
use arrow_schema::Field;
use arrow_schema::Schema;
use arrow_schema::SchemaRef;
use futures::Stream;
use futures::TryStreamExt;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
use vortex_array::VortexSessionExecute;
use vortex_arrow::ExecuteArrowExt;
use vortex_error::VortexError;
use vortex_error::VortexResult;
use vortex_io::runtime::BlockingRuntime;

Expand All @@ -40,7 +45,7 @@ impl ScanBuilder<ArrayRef> {
to_record_batch(chunk, &struct_field, &mut ctx)
})
.into_iter(runtime)?
.map(|result| result.map_err(|e| ArrowError::ExternalError(Box::new(e))));
.map(|result| result.map_err(vortex_err_to_arrow));

Ok(RecordBatchIteratorAdapter { iter, schema })
}
Expand All @@ -58,19 +63,46 @@ impl ScanBuilder<ArrayRef> {
to_record_batch(chunk, &struct_field, &mut ctx)
})
.into_stream()?
.map_err(|e| ArrowError::ExternalError(Box::new(e)));
.map_err(vortex_err_to_arrow);

Ok(stream)
}
}

pub(crate) fn to_record_batch(
/// Convert a Vortex struct chunk into an Arrow [`RecordBatch`] without panicking on top-level
/// struct nulls.
pub fn to_record_batch(
chunk: ArrayRef,
data_type: &Field,
ctx: &mut ExecutionCtx,
) -> VortexResult<RecordBatch> {
let arrow = chunk.execute_arrow(Some(data_type), ctx)?;
Ok(RecordBatch::from(arrow.as_struct().clone()))
let struct_array = arrow.as_struct();
let row_count = struct_array.len();
let (fields, columns, nulls) = struct_array.clone().into_parts();
if nulls.is_some_and(|n| n.null_count() > 0) {
return Err(ArrowError::InvalidArgumentError(
"Cannot convert nullable StructArray to RecordBatch, see StructArray documentation"
.to_string(),
)
.into());
}
let schema = Arc::new(Schema::new(fields));
let options = RecordBatchOptions::default().with_row_count(Some(row_count));
Ok(RecordBatch::try_new_with_options(
schema, columns, &options,
)?)
}

/// Convert a [`VortexError`] to an [`ArrowError`], preserving [`ArrowError::InvalidArgumentError`]
/// so Arrow C stream consumers see `EINVAL` rather than a generic I/O error.
pub fn vortex_err_to_arrow(err: VortexError) -> ArrowError {
if let Some(ArrowError::InvalidArgumentError(msg)) =
err.source().and_then(|e| e.downcast_ref::<ArrowError>())
{
return ArrowError::InvalidArgumentError(msg.clone());
}
ArrowError::ExternalError(Box::new(err))
}

/// We create an adapter for record batch iterators that supports clone.
Expand Down Expand Up @@ -196,6 +228,39 @@ mod tests {
Ok(())
}

#[test]
fn test_record_batch_rejects_nullable_struct_with_nulls() -> VortexResult<()> {
let schema = create_arrow_schema();
let mut nulls = arrow_array::builder::NullBufferBuilder::new(2);
nulls.append_non_null();
nulls.append_null();
let struct_array = StructArray::new(
schema.fields().clone(),
vec![
Arc::new(Int32Array::from(vec![Some(1), Some(2)])) as ArrowArrayRef,
Arc::new(StringArray::from(vec![Some("Alice"), Some("Bob")])) as ArrowArrayRef,
],
nulls.finish(),
);
let vortex_array = SCAN_SESSION
.arrow()
.from_arrow_array(Arc::new(struct_array), true)?;
let struct_field = Field::new_struct("", schema.fields().clone(), false);
let mut ctx = SCAN_SESSION.create_execution_ctx();

let err = to_record_batch(vortex_array, &struct_field, &mut ctx).unwrap_err();
let arrow_err = vortex_err_to_arrow(err);
assert!(
matches!(
&arrow_err,
ArrowError::InvalidArgumentError(msg)
if msg.contains("Cannot convert nullable StructArray to RecordBatch")
),
"unexpected error: {arrow_err:?}"
);
Ok(())
}

#[test]
fn test_record_batch_iterator_adapter() -> VortexResult<()> {
let schema = create_arrow_schema();
Expand Down
47 changes: 36 additions & 11 deletions vortex-python/src/arrays/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use std::ptr::NonNull;

use arrow_array::Array as ArrowArray;
use arrow_array::ArrayRef as ArrowArrayRef;
use arrow_schema::DataType;
use arrow_schema::Field;
use pyo3::IntoPyObjectExt;
use pyo3::exceptions::PyIndexError;
Expand Down Expand Up @@ -70,6 +69,7 @@ use crate::arrays::py::PythonArray;
use crate::arrays::py::PythonVTable;
use crate::arrow::FromPyArrow;
use crate::arrow::ToPyArrow;
use crate::arrow::array_data_with_field_to_pyarrow;
use crate::classes::chunked_array_fn;
use crate::dtype::PyDType;
use crate::error::PyVortexError;
Expand Down Expand Up @@ -198,9 +198,9 @@ pub(crate) fn arrow_target_field(
dtype: &DType,
) -> PyResult<Option<Field>> {
Ok(arrow_type
.map(|arrow_type| DataType::from_pyarrow(&arrow_type.as_borrowed()))
.map(|arrow_type| Field::from_pyarrow(&arrow_type.as_borrowed()))
.transpose()?
.map(|data_type| Field::new("", data_type, dtype.is_nullable())))
.map(|field| field.with_name("").with_nullable(dtype.is_nullable())))
}

/// An array executed into Arrow, but not yet given to pyarrow.
Expand All @@ -211,7 +211,9 @@ pub(crate) fn arrow_target_field(
pub(crate) enum ArrowExport {
/// One Arrow array per chunk, all converted to the type of the field.
Chunked(Vec<ArrowArrayRef>, Field),
Single(ArrowArrayRef),
/// A single Arrow array, plus its export field when field metadata (e.g. extension type)
/// must be preserved across the C Data Interface.
Single(ArrowArrayRef, Option<Field>),
}

impl ArrowExport {
Expand Down Expand Up @@ -247,29 +249,52 @@ impl ArrowExport {
return Ok(Self::Chunked(chunks, arrow_field));
}

let export_field = match target_field {
Some(field) => Some(field),
None => {
let default_field = session()
.arrow()
.default_arrow_export_field(array.dtype())?;
default_field
.extension_type_name()
.is_some()
.then_some(default_field)
}
};
let arrow_array =
array.execute_arrow(target_field.as_ref(), &mut session().create_execution_ctx())?;
Ok(Self::Single(arrow_array))
array.execute_arrow(export_field.as_ref(), &mut session().create_execution_ctx())?;
Ok(Self::Single(arrow_array, export_field))
}

/// Give the Arrow data to pyarrow, as a ``pyarrow.ChunkedArray`` for chunks.
pub(crate) fn into_pyarrow(self, py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
match self {
Self::Chunked(chunks, arrow_field) => {
// NOTE(aduffy): pyarrow.chunked_array() constructor only takes DataType and not
// Field, which probably loses the extension information?
let pa_data_type = arrow_field.data_type().clone().to_pyarrow(py)?;
// Export through `Field` so pyarrow preserves `ARROW:extension:name` and
// `ARROW:extension:metadata` on both the chunked array type and each chunk.
let pa_field = arrow_field.to_pyarrow(py)?;
let pa_data_type = pa_field.getattr(py, intern!(py, "type"))?;
let chunks = chunks
.iter()
.map(|arrow_array| arrow_array.into_data().to_pyarrow(py))
.map(|arrow_array| {
array_data_with_field_to_pyarrow(&arrow_array.into_data(), &arrow_field, py)
})
.collect::<Result<Vec<_>, _>>()?;

let kwargs = [(intern!(py, "type"), pa_data_type)].into_py_dict(py)?;

// Combine into a chunked array
chunked_array_fn(py)?.call((PyList::new(py, chunks)?,), Some(&kwargs))
}
Self::Single(arrow_array) => Ok(arrow_array.into_data().to_pyarrow(py)?.into_bound(py)),
Self::Single(arrow_array, Some(arrow_field)) => {
Ok(
array_data_with_field_to_pyarrow(&arrow_array.into_data(), &arrow_field, py)?
.into_bound(py),
)
}
Self::Single(arrow_array, None) => {
Ok(arrow_array.into_data().to_pyarrow(py)?.into_bound(py))
}
}
}
}
Expand Down
30 changes: 25 additions & 5 deletions vortex-python/src/arrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,26 @@ impl ToPyArrow for ArrayData {
}
}

/// Export an Arrow [`ArrayData`] to pyarrow using an explicit [`Field`] schema so field-level
/// metadata such as `ARROW:extension:name` and `ARROW:extension:metadata` is preserved.
pub(crate) fn array_data_with_field_to_pyarrow(
data: &ArrayData,
field: &Field,
py: Python,
) -> PyResult<Py<PyAny>> {
let array = FFI_ArrowArray::new(data);
let schema = FFI_ArrowSchema::try_from(field).map_err(to_py_err)?;

let array = array_class(py)?.call_method1(
intern!(py, "_import_from_c"),
(
addr_of!(array) as Py_uintptr_t,
addr_of!(schema) as Py_uintptr_t,
),
)?;
Ok(array.unbind())
}

impl<'py> FromPyArrow<'_, 'py> for RecordBatch {
fn from_pyarrow(value: &Borrowed<'_, 'py, PyAny>) -> PyResult<Self> {
let py = value.py();
Expand Down Expand Up @@ -282,11 +302,11 @@ impl<'py> FromPyArrow<'_, 'py> for RecordBatch {
// the output schema with the schema from the capsule.
let schema = Arc::new(Schema::try_from(schema_ptr).map_err(to_py_err)?);
let (_fields, columns, nulls) = array.into_parts();
assert_eq!(
nulls.map(|n| n.null_count()).unwrap_or_default(),
0,
"Cannot convert nullable StructArray to RecordBatch, see StructArray documentation"
);
if nulls.is_some_and(|n| n.null_count() > 0) {
return Err(PyValueError::new_err(
"Cannot convert nullable StructArray to RecordBatch, see StructArray documentation",
));
}

RecordBatch::try_new_with_options(schema, columns, &options).map_err(to_py_err)
}
Expand Down
14 changes: 4 additions & 10 deletions vortex-python/src/dataset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ use std::task::Poll;

use arrow_array::RecordBatch;
use arrow_array::RecordBatchReader;
use arrow_array::cast::AsArray;
use arrow_schema::ArrowError;
use arrow_schema::Field;
use arrow_schema::SchemaRef;
use futures::StreamExt;
Expand Down Expand Up @@ -50,12 +48,13 @@ use vortex::io::runtime::BlockingRuntime;
use vortex::io::session::RuntimeSessionExt;
use vortex::io::std_file::StdFileSystem;
use vortex::layout::scan::arrow::RecordBatchIteratorAdapter;
use vortex::layout::scan::arrow::to_record_batch;
use vortex::layout::scan::arrow::vortex_err_to_arrow;
use vortex::layout::scan::scan_builder::ScanBuilder;
use vortex::layout::scan::split_by::SplitBy;
use vortex::scan::strict_sorted_buffer::StrictSortedBuffer;
use vortex::utils::parallelism::get_available_parallelism;
use vortex_arrow::ArrowSessionExt;
use vortex_arrow::ExecuteArrowExt;

use crate::arrays::PyArrayRef;
use crate::arrow::IntoPyArrow;
Expand Down Expand Up @@ -541,11 +540,6 @@ fn take_rows(
.boxed()
}

fn to_record_batch(chunk: ArrayRef, target: &Field) -> VortexResult<RecordBatch> {
let arrow = chunk.execute_arrow(Some(target), &mut session().create_execution_ctx())?;
Ok(RecordBatch::from(arrow.as_struct().clone()))
}

#[pymethods]
impl PyVortexDataset {
fn schema(self_: PyRef<Self>) -> PyResult<Py<PyAny>> {
Expand Down Expand Up @@ -619,15 +613,15 @@ impl PyVortexDataset {
row_range,
split_by,
concurrency,
move |chunk| to_record_batch(chunk, &target),
move |chunk| to_record_batch(chunk, &target, &mut session().create_execution_ctx()),
)?;
if let Some(limit) = limit {
batches = take_rows(batches, limit);
}

let batches = current_runtime()
.block_on_stream(batches)
.map(|batch| batch.map_err(|e| ArrowError::ExternalError(Box::new(e))));
.map(|batch| batch.map_err(vortex_err_to_arrow));

let reader: Box<dyn RecordBatchReader + Send> =
Box::new(RecordBatchIteratorAdapter::new(batches, schema));
Expand Down
15 changes: 6 additions & 9 deletions vortex-python/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use std::error::Error;
use pyo3::CastError;
use pyo3::PyErr;
use pyo3::Python;
use pyo3::exceptions::PyIndexError;
use pyo3::exceptions::PyRuntimeError;
use vortex::error::VortexError;

Expand Down Expand Up @@ -42,14 +41,12 @@ impl From<PyVortexError> for PyErr {
match value {
PyVortexError::Py(py) => py,
PyVortexError::Vortex(vx) => {
if let Some(py_err) = vx.source().and_then(|err| err.downcast_ref::<PyErr>()) {
return Python::attach(|py| {
if py_err.is_instance_of::<PyIndexError>(py) {
py_err.clone_ref(py)
} else {
PyRuntimeError::new_err(vx.to_string())
}
});
let mut source = vx.source();
while let Some(err) = source {
if let Some(py_err) = err.downcast_ref::<PyErr>() {
return Python::attach(|py| py_err.clone_ref(py));
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
}
source = err.source();
}
PyRuntimeError::new_err(vx.to_string())
}
Expand Down
Loading
Loading