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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ arrow-buffer = "59.2"
arrow-cast = "59.2"
arrow-data = "59.2"
arrow-ipc = "59.2"
arrow-ord = "59.2"
arrow-row = "59.2"
arrow-schema = "59.2"
arrow-select = "59.2"
Expand Down
7 changes: 6 additions & 1 deletion vortex-arrow/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,19 @@ all-features = true
workspace = true

[features]
_test-harness = ["vortex-array/_test-harness", "dep:arrow-select"]
_test-harness = [
"vortex-array/_test-harness",
"dep:arrow-ord",
"dep:arrow-select",
]
_test-harness-hegel = ["_test-harness", "dep:hegeltest", "dep:half"]

[dependencies]
arrow-array = { workspace = true, features = ["ffi"] }
arrow-buffer = { workspace = true }
arrow-cast = { workspace = true }
arrow-data = { workspace = true }
arrow-ord = { workspace = true, optional = true }
arrow-schema = { workspace = true, features = ["canonical_extension_types"] }
arrow-select = { workspace = true, optional = true }
base64 = { workspace = true }
Expand Down
3 changes: 3 additions & 0 deletions vortex-arrow/src/extension/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@ pub trait ArrowExtVTable: ExtVTable {
/// The adapter checks the source extension type before calling this method. Return
/// [`ArrowExport::Unsupported`] when the target is unsupported. Child exports **must** receive
/// the same `options` through [`crate::ExecuteArrowExt::execute_arrow_with_options`].
///
/// The export **must** follow the
/// [null and comparison rules](crate::ArrowExportVTable::execute_arrow).
fn execute_arrow(
&self,
array: ArrayRef,
Expand Down
77 changes: 53 additions & 24 deletions vortex-arrow/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,24 @@ pub trait ArrowExportVTable: 'static + Send + Sync + Debug {
/// those exports, through [`ExecuteArrowExt::execute_arrow_with_options`]. The [`ArrowSession`]
/// of `ctx` is the session of the export, so a plugin that needs one must use it.
///
/// # Exported values
///
/// Every export **must** preserve the nulls of `array`.
///
/// If `array` has an extension dtype and the output type supports the Arrow comparison kernels,
/// the export **must** preserve equality and order. Two non-null exported values compare the
/// same way in Arrow as their storage values compare in Vortex. Nested Arrow types only have
/// the null requirement.
///
/// The comparison rule holds across batches in one Arrow representation. To push a comparison
/// down to Vortex storage, an engine also needs to know that both operands use compatible
/// representations. Two exporters can each preserve order and still encode equal storage
/// values differently. A round trip alone does not even ensure that one exporter preserves
/// order. An exporter can reverse the bytes of each value and undo that change on import.
///
/// A plugin that breaks these rules gives incorrect query results instead of an error. It does
/// not cause memory unsafety. `test_harness::check_arrow` checks both rules for one array.
///
/// [`ExecuteArrowExt::execute_arrow_with_options`]: crate::ExecuteArrowExt::execute_arrow_with_options
fn execute_arrow(
&self,
Expand Down Expand Up @@ -279,6 +297,9 @@ type ArrowImporterRegistry = ArcSwapMap<Id, Arc<[ArrowImportVTableRef]>>;
/// preserve its dtype and logical values. The owning dtype and Arrow plugins must be registered in
/// the importing session.
///
/// An Arrow reader observes exported values before any Vortex importer runs.
/// [`ArrowExportVTable::execute_arrow`] defines the null and comparison rules for those values.
///
/// The session checks inferred fields and successful plugin imports, including raw plugins.
/// Explicit export targets may request a different dtype. Unknown Vortex IDs import as storage.
///
Expand Down Expand Up @@ -567,8 +588,8 @@ impl ArrowSession {
/// produce any data for the same field, so a name with an exporter gives `false`.
///
/// The answer covers only the top level of `field`. Each storage child exports to its own
/// field, which can name another exporter, and [`Self::exports_without_plugins`] checks every
/// depth.
/// field, which can name another exporter. [`Self::exports_without_plugins`] checks for
/// exporters at every depth.
#[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
pub fn exports_extension_storage(&self, ext_dtype: &ExtDTypeRef, field: &Field) -> bool {
// A dictionary or run-end encoded field holds the storage values behind an encoding, so
Expand Down Expand Up @@ -608,21 +629,20 @@ impl ArrowSession {
.is_ok_and(|dtype| &dtype == ext_dtype.storage_dtype())
}

/// Returns whether an export to `field` calls no registered exporter at any depth.
/// Returns whether exporting to `field` uses only the built-in conversions at every depth.
///
/// Such an export uses only the conversions of this crate, so a caller planning reads without
/// the array knows which Arrow data it produces. A field that names an extension type without
/// an exporter still qualifies, because it exports through its Vortex ID or as plain storage.
#[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
/// A registered exporter can choose the Arrow representation even if the field also supports
/// a built-in conversion. The answer is conservative because the plugin can defer at runtime.
pub fn exports_without_plugins(&self, field: &Field) -> bool {
let names_exporter = field
.extension_type_name()
.is_some_and(|name| !self.exporters(&Id::new(name)).is_empty());
!field_uses_plugin(field, &|id| !self.exporters(id).is_empty())
}

!names_exporter
&& nested_fields(field.data_type())
.into_iter()
.all(|child| self.exports_without_plugins(child))
/// Returns whether importing from `field` uses only the built-in conversions at every depth.
///
/// A registered importer can transform values before Vortex sees them, even if the outer field
/// has no extension name.
pub fn imports_without_plugins(&self, field: &Field) -> bool {
!field_uses_plugin(field, &|id| !self.importers(id).is_empty())
}

/// Fails unless `field`, which names the Vortex ID of `ext_dtype`, describes `ext_dtype`.
Expand Down Expand Up @@ -1206,23 +1226,32 @@ pub(crate) fn ensure_ext_metadata(
Ok(())
}

/// Returns the fields nested directly in `data_type`.
///
/// A dictionary has no field for its values, so it returns the fields nested in the value type.
fn nested_fields(data_type: &DataType) -> Vec<&Field> {
#[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
fn field_uses_plugin(field: &Field, is_registered: &impl Fn(&Id) -> bool) -> bool {
field
.extension_type_name()
.is_some_and(|name| is_registered(&Id::new(name)))
|| child_uses_plugin(field.data_type(), is_registered)
}

fn child_uses_plugin(data_type: &DataType, is_registered: &impl Fn(&Id) -> bool) -> bool {
match data_type {
DataType::Struct(fields) => fields.iter().map(Arc::as_ref).collect(),
DataType::Union(fields, _) => fields.iter().map(|(_, field)| field.as_ref()).collect(),
DataType::Struct(fields) => fields
.iter()
.any(|field| field_uses_plugin(field, is_registered)),
DataType::Union(fields, _) => fields
.iter()
.any(|(_, field)| field_uses_plugin(field, is_registered)),
DataType::List(field)
| DataType::LargeList(field)
| DataType::ListView(field)
| DataType::LargeListView(field)
| DataType::FixedSizeList(field, _)
| DataType::Map(field, _)
| DataType::RunEndEncoded(_, field) => vec![field.as_ref()],
DataType::Dictionary(_, values) => nested_fields(values),
// Other Arrow types have no nested fields.
_ => Vec::new(),
| DataType::RunEndEncoded(_, field) => field_uses_plugin(field, is_registered),
// A dictionary carries its value field's metadata on the outer field, checked above.
DataType::Dictionary(_, values) => child_uses_plugin(values, is_registered),
_ => false,
}
}

Expand Down
115 changes: 109 additions & 6 deletions vortex-arrow/src/test_harness/round_trip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,30 @@
use std::sync::Arc;

use arrow_array::Array;
use arrow_ord::cmp;
use arrow_schema::DataType;
use arrow_schema::Field;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
use vortex_array::IntoArray;
use vortex_array::arrays::BoolArray;
use vortex_array::arrays::DictArray;
use vortex_array::arrays::ExtensionArray;
use vortex_array::arrays::FixedSizeListArray;
use vortex_array::arrays::ListArray;
use vortex_array::arrays::ListViewArray;
use vortex_array::arrays::MapArray;
use vortex_array::arrays::PrimitiveArray;
use vortex_array::arrays::RunEnd;
use vortex_array::arrays::StructArray;
use vortex_array::arrays::extension::ExtensionArrayExt;
use vortex_array::assert_arrays_eq;
use vortex_array::builtins::ArrayBuiltins;
use vortex_array::dtype::DType;
use vortex_array::dtype::FieldNames;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::PType;
use vortex_array::scalar_fn::builtin::operators::Operator;
use vortex_array::validity::Validity;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
Expand All @@ -39,14 +45,18 @@ use crate::ExecuteArrowExt;
/// The caller supplies both representations from source values. The expected field must not come
/// from the Vortex exporter. The Vortex array must have an extension dtype. Arrow data equality
/// ignores values masked by nulls.
///
/// Also check the export against the Vortex storage for nulls, equality, and order where the Arrow
/// comparison kernels support the output type.
#[track_caller]
pub fn check_arrow(
array: ArrayRef,
field: &Field,
expected: arrow_array::ArrayRef,
ctx: &mut ExecutionCtx,
) -> VortexResult<()> {
check_arrow_values(array.clone(), field, Arc::clone(&expected), ctx)?;
let exported = check_arrow_values(array.clone(), field, Arc::clone(&expected), ctx)?;
check_exported_values(array.clone(), exported.as_ref(), ctx)?;
check_nested_arrow(array.clone(), field, Arc::clone(&expected), ctx)?;
let len = array.len();
let indices: Vec<_> = (0..u32::try_from(len)?)
Expand Down Expand Up @@ -78,9 +88,7 @@ pub fn check_arrow(
];
for (operation, selected, expected) in selected {
assert_eq!(selected.dtype(), array.dtype(), "{operation} dtype");
let selected = selected
.execute::<vortex_array::arrays::ExtensionArray>(ctx)?
.into_array();
let selected = selected.execute::<ExtensionArray>(ctx)?.into_array();
let exported = selected.execute_arrow(Some(field), ctx)?;
assert_eq!(exported.to_data(), expected.to_data(), "{operation} values");
}
Expand All @@ -94,7 +102,7 @@ fn check_arrow_values(
field: &Field,
expected: arrow_array::ArrayRef,
ctx: &mut ExecutionCtx,
) -> VortexResult<()> {
) -> VortexResult<arrow_array::ArrayRef> {
let session = ctx.session().clone();
let arrow = session.arrow();
assert_eq!(expected.data_type(), field.data_type());
Expand All @@ -106,6 +114,71 @@ fn check_arrow_values(
exported.to_data().validate_full()?;
assert_eq!(exported.to_data(), expected.to_data());

Ok(exported)
}

/// Checks the nulls and comparable storage values against the exported array.
///
/// [`ArrowExportVTable::execute_arrow`] states the two rules. Check nulls across all rows, then
/// compare consecutive non-null rows. If the array contains distinct values, at least one pair
/// compares them. Nested exports only support the null check.
///
/// [`ArrowExportVTable::execute_arrow`]: crate::ArrowExportVTable::execute_arrow
#[track_caller]
fn check_exported_values(
array: ArrayRef,
exported: &dyn Array,
ctx: &mut ExecutionCtx,
) -> VortexResult<()> {
let len = array.len();
let nulls = exported.logical_nulls();
let exported_is_null = match &nulls {
Some(nulls) => BoolArray::from_iter(nulls.iter().map(|valid| !valid)),
None => BoolArray::from_iter(std::iter::repeat_n(false, len)),
};
assert_arrays_eq!(exported_is_null.into_array(), array.is_null()?, ctx);

if exported.data_type().is_nested() {
return Ok(());
}

let indices = match nulls {
Some(nulls) => nulls
.valid_indices()
.map(u32::try_from)
.collect::<Result<Vec<_>, _>>()?,
None => (0..u32::try_from(len)?).collect(),
};
if indices.len() < 2 {
return Ok(());
}

let left_indices = &indices[..indices.len() - 1];
let right_indices = &indices[1..];

let session = ctx.session().clone();
let extension = array.execute::<ExtensionArray>(ctx)?;
let storage = extension.storage_array();
let arrow_left = reference_take(exported, left_indices)?;
let arrow_right = reference_take(exported, right_indices)?;
let storage_left =
storage.take(PrimitiveArray::from_iter(left_indices.iter().copied()).into_array())?;
let storage_right =
storage.take(PrimitiveArray::from_iter(right_indices.iter().copied()).into_array())?;

let comparisons = [
(Operator::Eq, cmp::eq(&arrow_left, &arrow_right)?),
(Operator::Lt, cmp::lt(&arrow_left, &arrow_right)?),
];

for (operator, in_arrow) in comparisons {
let in_vortex = storage_left.binary(storage_right.clone(), operator)?;
let in_arrow = session
.arrow()
.from_arrow_array(Arc::new(in_arrow), in_vortex.dtype().is_nullable())?;
assert_arrays_eq!(in_arrow, in_vortex, ctx);
}

Ok(())
}

Expand Down Expand Up @@ -292,7 +365,9 @@ fn check_nested_arrow(
.data_type(run_field.data_type().clone())
.build()?,
);
check_arrow_values(runs, &run_field, expected_runs, ctx)
check_arrow_values(runs, &run_field, expected_runs, ctx)?;

Ok(())
}

/// Selects source rows while retaining the row count of zero-width lists.
Expand Down Expand Up @@ -484,3 +559,31 @@ pub fn check_containers(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult

check_field_round_trip(run_end, &field, Some(&field), ctx)
}

#[cfg(test)]
mod tests {
use std::sync::Arc;

use arrow_array::Date32Array;
use vortex_array::VortexSessionExecute as _;
use vortex_error::VortexExpect;
use vortex_session::VortexSession;

use super::check_exported_values;
use crate::ArrowSessionExt;

#[test]
#[should_panic(expected = "assertion failed: arrays do not match")]
fn test_export_order_check_pairs_non_null_rows() {
let session = VortexSession::empty();
let storage_order = Date32Array::from(vec![Some(1), Some(2), None, None]);
let reversed_order = Date32Array::from(vec![Some(2), Some(1), None, None]);
let array = session
.arrow()
.from_arrow_array(Arc::new(storage_order), true)
.vortex_expect("Date32 imports as a Vortex date array");

check_exported_values(array, &reversed_order, &mut session.create_execution_ctx())
.vortex_expect("Date32 comparisons are supported");
}
}
Loading
Loading