Skip to content
Draft
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
4 changes: 3 additions & 1 deletion docs/developer-guide/benchmarking.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,9 @@ factors are configurable per suite (e.g. `--opt scale-factor=10.0` for TPC-H SF=
Benchmark sessions enable the newest `preview` edition and the `unstable` edition, so every
benchmark measures Vortex files whose compressor may also choose their encodings. `preview`
currently holds `fastlanes.delta`, and `unstable` holds `vortex.decimal_byte_parts.v2` and
`vortex.widen`. `vortex_bench::enable_unstable_encodings` enables both on a session.
`vortex.widen`. `unstable` also holds the `vortex.extension` layout, which benchmarks do not use
because they opt no extension type into it. `vortex_bench::enable_unstable_encodings` enables
both editions on a session.

### Running SQL Benchmarks

Expand Down
5 changes: 5 additions & 0 deletions vortex-array/src/dtype/extension/foreign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,15 @@ pub struct ForeignExtDType {
}

impl ForeignExtDType {
/// Creates the placeholder vtable for the extension ID `id`.
pub fn new(id: ExtId) -> Self {
Self { id }
}

/// Builds an extension dtype for `id` from its serialized metadata and storage dtype.
///
/// No registered vtable checks the metadata, so any metadata bytes and storage dtype are
/// accepted.
pub fn from_parts(
id: ExtId,
metadata: Vec<u8>,
Expand Down
5 changes: 5 additions & 0 deletions vortex-array/src/dtype/extension/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ mod plugin;
pub use plugin::*;

mod foreign;
// Tests in other crates use it to build extension dtypes over arbitrary storage without
// defining a vtable for each storage shape.
#[cfg(feature = "_test-harness")]
pub use foreign::ForeignExtDType;
#[cfg(not(feature = "_test-harness"))]
pub(crate) use foreign::*;

mod typed;
Expand Down
17 changes: 2 additions & 15 deletions vortex-arrow/src/executor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,7 @@ use crate::executor::struct_::to_arrow_struct;
use crate::executor::temporal::to_arrow_date;
use crate::executor::temporal::to_arrow_time;
use crate::executor::temporal::to_arrow_timestamp;
use crate::ext_metadata::decode_arrow_ext_metadata;
use crate::session::ArrowSessionExt;
use crate::session::ensure_ext_metadata;

/// Execution of a Vortex array into an Arrow array, for every type that implements [`IntoArray`].
///
Expand Down Expand Up @@ -326,20 +324,9 @@ fn execute_arrow_ext_storage(
options: &ArrowExportOptions,
ctx: &mut ExecutionCtx,
) -> VortexResult<ArrowArrayRef> {
if let Some(importer_dtype) = ctx
.session()
ctx.session()
.arrow()
.infer_field_dtype_with_importers(target)?
{
vortex_ensure_eq!(
importer_dtype.as_nullable(),
array.dtype().as_nullable(),
"Arrow field {:?} must describe the source extension type",
target.name()
);
} else {
ensure_ext_metadata(target, &decode_arrow_ext_metadata(target)?, ext_dtype)?;
}
.ensure_ext_storage_metadata(target, ext_dtype)?;

let target_dtype = ctx
.session()
Expand Down
45 changes: 45 additions & 0 deletions vortex-arrow/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,51 @@ impl ArrowSession {
Ok(field)
}

/// Checks whether `field` routes the registered `ext_dtype` through storage export.
///
/// A plugin registered for the target's extension name can transform values even when its
/// Arrow type matches the storage. Encoded targets use separate export routes.
#[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
pub fn is_extension_storage_field(&self, field: &Field, ext_dtype: &ExtDTypeRef) -> bool {
let Some(name) = field.extension_type_name() else {
return false;
};

let id = Id::new(name);
if self.known_vortex_id(&id) != Some(ext_dtype.id())
|| !self.exporters(&id).is_empty()
|| matches!(
field.data_type(),
DataType::Dictionary(..) | DataType::RunEndEncoded(..)
)
{
return false;
}

self.from_arrow_datatype(field.data_type(), ext_dtype.nullability())
.is_ok_and(|dtype| &dtype == ext_dtype.storage_dtype())
&& self.ensure_ext_storage_metadata(field, ext_dtype).is_ok()
}

/// Checks that a Vortex-ID export target describes the source extension type.
pub(crate) fn ensure_ext_storage_metadata(
&self,
field: &Field,
ext_dtype: &ExtDTypeRef,
) -> VortexResult<()> {
if let Some(importer_dtype) = self.infer_field_dtype_with_importers(field)? {
vortex_ensure_eq!(
importer_dtype.as_nullable(),
DType::Extension(ext_dtype.with_nullability(Nullability::Nullable)),
"Arrow field {:?} must describe the source extension type",
field.name()
);
Ok(())
} else {
ensure_ext_metadata(field, &decode_arrow_ext_metadata(field)?, ext_dtype)
}
}

/// Returns the Vortex ID that the extension name `id` resolves to, or `None` if the session does
/// not know it. The registry can hold an alias, so the result can differ from `id`.
pub(crate) fn known_vortex_id(&self, id: &Id) -> Option<ExtId> {
Expand Down
107 changes: 73 additions & 34 deletions vortex-datafusion/src/convert/exprs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//! extension metadata, or inherit missing metadata from the operand they are compared with. This
//! supplies the logical dtype that Vortex requires without adding implicit casts.

mod projection_fields;
use std::sync::Arc;

use arrow_schema::DataType;
Expand Down Expand Up @@ -40,6 +41,7 @@ use datafusion_physical_expr::projection::ProjectionExprs;
use datafusion_physical_expr::utils::collect_columns;
use datafusion_physical_plan::expressions as df_expr;
use itertools::Itertools;
pub(crate) use projection_fields::push_down_projection_fields;
use vortex::VortexSessionDefault;
use vortex::aggregate_fn::NumericalAggregateOpts;
use vortex::array::VortexSessionExecute;
Expand All @@ -51,6 +53,7 @@ use vortex::expr::Expression;
use vortex::expr::Lambda;
use vortex::expr::byte_length;
use vortex::expr::cast;
use vortex::expr::ext_storage;
use vortex::expr::get_item;
use vortex::expr::in_list_of;
use vortex::expr::is_not_null;
Expand Down Expand Up @@ -173,6 +176,14 @@ pub trait ExpressionConverter: Send + Sync {
})
}

/// Allow scans to refine the raw fallback returned by [`Self::split_projection`].
///
/// Defaults to `false`. Opt in if scans may replace whole struct inputs with the plain fields
/// the remaining DataFusion projection needs.
fn allows_projection_field_pushdown(&self) -> bool {
false
}

/// Create a projection that reads only the required columns without pushing down
/// any expressions. All projection logic is applied after the scan.
fn no_pushdown_projection(
Expand Down Expand Up @@ -266,6 +277,7 @@ type Conversion<T> = Result<T, Unconverted>;
/// Nested struct field access also uses Vortex semantics: a null parent produces a null child,
/// whereas DataFusion extracts the child without applying parent validity. These differences
/// are accepted for both filters and projections.
/// Field access through an extension can run natively when Arrow exposes its Vortex storage.
/// Searched `CASE WHEN` expressions preserve short-circuit evaluation: conditions and
/// branch values only execute on the rows that reach them, including fallible branches.
/// Other expressions require compatible SQL semantics or remain in DataFusion.
Expand Down Expand Up @@ -746,40 +758,7 @@ impl DefaultExpressionConverter {
}

if ScalarFunctionExpr::try_downcast_func::<GetFieldFunc>(scalar_fn).is_some() {
// DataFusion's GetFieldFunc flattens nested field access into a single call
// with multiple field name arguments, e.g. `outer.inner.leaf` becomes
// get_field(Column("outer"), "inner", "leaf").
let [source, paths @ ..] = scalar_fn.args() else {
return Err(
exec_datafusion_err!("get_field requires a source and field path").into(),
);
};
if paths.is_empty() {
return Err(exec_datafusion_err!("get_field requires a field path").into());
}
let mut source_type = source.data_type(schema)?;
let mut names = Vec::with_capacity(paths.len());
for path in paths {
let name = path
.downcast_ref::<df_expr::Literal>()
.and_then(|literal| literal.value().try_as_str().flatten())
.ok_or_else(|| {
exec_datafusion_err!("get_field path must be a non-null string literal")
})?;
let DataType::Struct(fields) = &source_type else {
return Err(Unconverted::Unsupported);
};
let (_, field) = fields.find(name).ok_or_else(|| {
exec_datafusion_err!("get_field references missing field {name}")
})?;
source_type = field.data_type().clone();
names.push(name);
}
let mut result = self.convert_expr(source, schema, input_dtype)?;
for name in names {
result = get_item(name, result);
}
return Ok(result);
return self.convert_get_field(scalar_fn, schema, input_dtype);
}

if ScalarFunctionExpr::try_downcast_func::<ArraySum>(scalar_fn).is_some() {
Expand Down Expand Up @@ -823,6 +802,62 @@ impl DefaultExpressionConverter {
Ok(cast(length(input), return_dtype))
}

fn convert_get_field(
&self,
scalar_fn: &ScalarFunctionExpr,
schema: &Schema,
input_dtype: &DType,
) -> Conversion<Expression> {
let [source, paths @ ..] = scalar_fn.args() else {
return Err(exec_datafusion_err!("get_field requires a source and field path").into());
};
if paths.is_empty() {
return Err(exec_datafusion_err!("get_field requires a field path").into());
}

// DataFusion can flatten nested accesses into one call, so each step needs its own
// Arrow field metadata to identify the representation that DataFusion sees.
let source_field = source.return_field(schema)?;
let mut parent_field = source_field.as_ref();
let mut steps = Vec::with_capacity(paths.len());
for path in paths {
let name = path
.downcast_ref::<df_expr::Literal>()
.and_then(|literal| literal.value().try_as_str().flatten())
.ok_or_else(|| {
exec_datafusion_err!("get_field path must be a non-null string literal")
})?;
let DataType::Struct(fields) = parent_field.data_type() else {
return Err(Unconverted::Unsupported);
};
let (_, child_field) = fields
.find(name)
.ok_or_else(|| exec_datafusion_err!("get_field references missing field {name}"))?;
steps.push((parent_field, name));
parent_field = child_field.as_ref();
}

let mut result = self.convert_expr(source, schema, input_dtype)?;
for (parent_field, name) in steps {
if parent_field.extension_type_name().is_some() {
let DType::Extension(ext_dtype) = converted_dtype(&result, input_dtype)? else {
return Err(Unconverted::Unsupported);
};
if !self
.session
.arrow()
.is_extension_storage_field(parent_field, &ext_dtype)
{
return Err(Unconverted::Unsupported);
}
result = ext_storage(result);
}
result = get_item(name, result);
}

Ok(result)
}

/// Converts `array_sum` to `list_sum`.
///
/// DataFusion casts the list to `List<Float64>`, then adds each list's valid elements in
Expand Down Expand Up @@ -926,6 +961,10 @@ impl ExpressionConverter for DefaultExpressionConverter {
Err(Unconverted::Failed(error)) => Err(error),
}
}

fn allows_projection_field_pushdown(&self) -> bool {
true
}
}

/// Whether evaluating `expr` cannot fail, so Vortex may evaluate it on rows DataFusion skips.
Expand Down
Loading