mod bool;
mod chunked;
mod decimal;
mod extension;
mod fixed_size_list;
mod fixed_width;
mod kernel;
mod listview;
mod map;
mod null;
mod paired_chunks;
mod primitive;
mod struct_;
mod varbinview;
mod widen;
use std::fmt::Display;
use std::fmt::Formatter;
use std::sync::Arc;
pub use kernel::*;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
use vortex_array::IntoArray;
use vortex_array::arrays::Bool;
use vortex_array::arrays::BoolArray;
use vortex_array::arrays::Chunked;
use vortex_array::arrays::Decimal;
use vortex_array::arrays::Extension;
use vortex_array::arrays::FixedSizeList;
use vortex_array::arrays::ListView;
use vortex_array::arrays::Map;
use vortex_array::arrays::Null;
use vortex_array::arrays::Primitive;
use vortex_array::arrays::ScalarFnArray;
use vortex_array::arrays::Struct;
use vortex_array::arrays::VarBinView;
use vortex_array::arrays::Widen;
use vortex_array::arrays::bool::BoolArrayExt;
use vortex_array::builders::ArrayBuilder;
use vortex_array::builders::builder_with_capacity_in;
use vortex_array::builtins::ArrayBuiltins;
use vortex_array::dtype::DType;
use vortex_array::dtype::StructFields;
use vortex_array::optimizer::ArrayOptimizer;
use vortex_array::optimizer::kernels::ArrayKernelsExt;
use vortex_array::scalar_fn::Arity;
use vortex_array::scalar_fn::ChildName;
use vortex_array::scalar_fn::EmptyOptions;
use vortex_array::scalar_fn::ExecutionArgs;
use vortex_array::scalar_fn::ReduceNode;
use vortex_array::scalar_fn::ScalarFnId;
use vortex_array::scalar_fn::ScalarFnVTable;
use vortex_array::scalar_fn::ScalarFnVTableExt;
use vortex_array::scalar_fn::builtin::cast::Cast;
use vortex_array::scalar_fn::display::ExprDisplay;
use vortex_array::scalar_fn::session::ScalarFnSessionExt;
use vortex_array::validity::Validity;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure;
use vortex_error::vortex_err;
use vortex_mask::Mask;
use vortex_mask::MaskValues;
use vortex_session::VortexSession;
use vortex_session::registry::CachedId;
use crate::builtins::ArrayFunctions;
pub(crate) fn initialize(session: &VortexSession) {
session.scalar_fns().register(Zip);
let kernels = session.kernels();
kernels.register_execute_parent_kernel(Zip.id(), Bool, ZipExecuteAdaptor(Bool));
kernels.register_execute_parent_kernel(Zip.id(), Chunked, ZipExecuteAdaptor(Chunked));
kernels.register_execute_parent_kernel(Zip.id(), Decimal, ZipExecuteAdaptor(Decimal));
kernels.register_execute_parent_kernel(
Zip.id(),
FixedSizeList,
ZipExecuteAdaptor(FixedSizeList),
);
kernels.register_execute_parent_kernel(Zip.id(), ListView, ZipExecuteAdaptor(ListView));
kernels.register_execute_parent_kernel(Zip.id(), Map, ZipExecuteAdaptor(Map));
kernels.register_execute_parent_kernel(Zip.id(), Primitive, ZipExecuteAdaptor(Primitive));
kernels.register_execute_parent_kernel(Zip.id(), Struct, ZipExecuteAdaptor(Struct));
kernels.register_execute_parent_kernel(Zip.id(), VarBinView, ZipExecuteAdaptor(VarBinView));
kernels.register_execute_parent_kernel(Zip.id(), Widen, ZipExecuteAdaptor(Widen));
kernels.register_reduce_parent_rule(Zip, Extension, const { &ZipReduceAdaptor(Extension) });
kernels.register_reduce_parent_rule(Zip, Null, const { &ZipReduceAdaptor(Null) });
}
#[derive(Clone)]
pub struct Zip;
impl Zip {
pub fn try_new(
if_true: ArrayRef,
if_false: ArrayRef,
mask: ArrayRef,
) -> VortexResult<ScalarFnArray> {
ScalarFnArray::try_new(Zip.bind(EmptyOptions), [if_true, if_false, mask])
}
}
impl ScalarFnVTable for Zip {
type Options = EmptyOptions;
fn id(&self) -> ScalarFnId {
static ID: CachedId = CachedId::new("vortex.zip");
*ID
}
fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
Ok(Some(vec![]))
}
fn deserialize(
&self,
_metadata: &[u8],
_session: &VortexSession,
) -> VortexResult<Self::Options> {
Ok(EmptyOptions)
}
fn arity(&self, _options: &Self::Options) -> Arity {
Arity::Exact(3)
}
fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
match child_idx {
0 => ChildName::from("if_true"),
1 => ChildName::from("if_false"),
2 => ChildName::from("mask"),
_ => unreachable!("Invalid child index {} for Zip expression", child_idx),
}
}
fn fmt_sql(
&self,
_options: &Self::Options,
expr: &dyn ExprDisplay,
f: &mut Formatter<'_>,
) -> std::fmt::Result {
write!(f, "zip(")?;
Display::fmt(expr.display_child(0), f)?;
write!(f, ", ")?;
Display::fmt(expr.display_child(1), f)?;
write!(f, ", ")?;
Display::fmt(expr.display_child(2), f)?;
write!(f, ")")
}
fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
vortex_ensure!(
matches!(arg_dtypes[2], DType::Bool(_)),
"zip requires mask to be a boolean type, got {}",
arg_dtypes[2]
);
zip_return_dtype(&arg_dtypes[0], &arg_dtypes[1])
}
fn execute(
&self,
_options: &Self::Options,
args: &dyn ExecutionArgs,
ctx: &mut ExecutionCtx,
) -> VortexResult<ArrayRef> {
let if_true = args.get(0)?;
let if_false = args.get(1)?;
let mask_array = args.get(2)?;
let mask = mask_array
.execute::<BoolArray>(ctx)?
.to_mask_fill_null_false(ctx);
let return_dtype = zip_return_dtype(if_true.dtype(), if_false.dtype())?;
if mask.all_true() {
return if_true.cast(return_dtype);
}
if mask.all_false() {
return if_false.cast(return_dtype);
}
if !if_true.is_canonical() || !if_false.is_canonical() {
let if_true = if_true.execute::<ArrayRef>(ctx)?;
let if_false = if_false.execute::<ArrayRef>(ctx)?;
return mask.into_array().zip(if_true, if_false);
}
let Mask::Values(mask) = mask else {
unreachable!("trivial masks returned above");
};
zip_impl(&if_true, &if_false, &mask, ctx)
}
fn simplify<T: ReduceNode>(
&self,
_options: &Self::Options,
node: &T,
) -> VortexResult<Option<T>> {
let mask = node.child(2);
let Some(mask_constant) = mask.as_constant() else {
return Ok(None);
};
if let Some(mask_value) = mask_constant.as_bool().value() {
let selected = if mask_value {
node.child(0)
} else {
node.child(1)
};
let dtype = node.node_dtype()?;
return Ok(Some(if selected.node_dtype()? == dtype {
selected
} else {
selected.new_node(Cast.bind(dtype), std::slice::from_ref(&selected))?
}));
}
Ok(None)
}
fn is_strict(&self, _options: &Self::Options) -> bool {
false
}
fn is_infallible(&self, _options: &Self::Options) -> bool {
true
}
}
fn zip_impl(
if_true: &ArrayRef,
if_false: &ArrayRef,
mask: &MaskValues,
ctx: &mut ExecutionCtx,
) -> VortexResult<ArrayRef> {
assert_eq!(
if_true.len(),
if_false.len(),
"zip requires arrays to have the same size"
);
let return_type = zip_return_dtype(if_true.dtype(), if_false.dtype())?;
if !has_builder(&return_type) {
vortex_bail!(
"zip of {return_type} arrays with a mixed mask is not supported: the dtype has no \
zip kernel and no array builder"
);
}
let if_true = if_true.cast(return_type.clone())?.optimize_ctx(ctx)?;
let if_false = if_false.cast(return_type.clone())?.optimize_ctx(ctx)?;
zip_impl_with_builder(
&if_true,
&if_false,
mask,
builder_with_capacity_in(&return_type, if_true.len(), ctx.allocator()),
ctx,
)
}
fn has_builder(dtype: &DType) -> bool {
match dtype {
DType::Union(..) => false,
DType::List(element, _) | DType::FixedSizeList(element, ..) => has_builder(element),
DType::Map(map, _) => has_builder(&map.key_dtype()) && has_builder(&map.value_dtype()),
DType::Struct(fields, _) => fields.fields().all(|field| has_builder(&field)),
DType::Extension(ext) => has_builder(ext.storage_dtype()),
DType::Null
| DType::Bool(_)
| DType::Primitive(..)
| DType::Decimal(..)
| DType::Utf8(_)
| DType::Binary(_)
| DType::Variant(_) => true,
}
}
fn zip_return_dtype(if_true: &DType, if_false: &DType) -> VortexResult<DType> {
zip_nullability_union(if_true, if_false).ok_or_else(|| {
vortex_err!(
"zip requires if_true and if_false to have the same base type, got {} and {}",
if_true,
if_false
)
})
}
pub fn zip_nullability_union(lhs: &DType, rhs: &DType) -> Option<DType> {
let nullability = lhs.nullability() | rhs.nullability();
match (lhs, rhs) {
(DType::List(lhs_element, _), DType::List(rhs_element, _)) => Some(DType::List(
Arc::new(zip_nullability_union(lhs_element, rhs_element)?),
nullability,
)),
(
DType::FixedSizeList(lhs_element, lhs_size, _),
DType::FixedSizeList(rhs_element, rhs_size, _),
) if lhs_size == rhs_size => Some(DType::FixedSizeList(
Arc::new(zip_nullability_union(lhs_element, rhs_element)?),
*lhs_size,
nullability,
)),
(DType::Map(lhs_map, _), DType::Map(rhs_map, _))
if lhs_map.keys_sorted() == rhs_map.keys_sorted() =>
{
DType::map(
zip_nullability_union(&lhs_map.key_dtype(), &rhs_map.key_dtype())?,
zip_nullability_union(&lhs_map.value_dtype(), &rhs_map.value_dtype())?,
lhs_map.keys_sorted(),
nullability,
)
.ok()
}
(DType::Struct(lhs_fields, _), DType::Struct(rhs_fields, _))
if lhs_fields.names() == rhs_fields.names() =>
{
let fields = lhs_fields
.fields()
.zip(rhs_fields.fields())
.map(|(lhs, rhs)| zip_nullability_union(&lhs, &rhs))
.collect::<Option<Vec<_>>>()?;
Some(DType::Struct(
StructFields::new(lhs_fields.names().clone(), fields),
nullability,
))
}
(DType::Union(lhs_variants, _), DType::Union(rhs_variants, _))
if lhs_variants == rhs_variants =>
{
Some(DType::Union(lhs_variants.clone(), nullability))
}
_ if lhs.eq_ignore_nullability(rhs) => Some(lhs.with_nullability(nullability)),
_ => None,
}
}
fn zip_impl_with_builder(
if_true: &ArrayRef,
if_false: &ArrayRef,
mask: &MaskValues,
mut builder: Box<dyn ArrayBuilder>,
ctx: &mut ExecutionCtx,
) -> VortexResult<ArrayRef> {
for (start, end) in mask.slices() {
if builder.len() < *start {
if_false
.slice(builder.len()..*start)?
.append_to_builder(builder.as_mut(), ctx)?;
}
if_true
.slice(*start..*end)?
.append_to_builder(builder.as_mut(), ctx)?;
}
if builder.len() < if_false.len() {
if_false
.slice(builder.len()..if_false.len())?
.append_to_builder(builder.as_mut(), ctx)?;
}
Ok(builder.finish())
}
pub(crate) fn zip_validity(
if_true: Validity,
if_false: Validity,
mask: &Mask,
) -> VortexResult<Validity> {
match (&if_true, &if_false) {
(Validity::NonNullable, Validity::NonNullable) => return Ok(Validity::NonNullable),
(Validity::AllValid, Validity::AllValid) => return Ok(Validity::AllValid),
(Validity::AllInvalid, Validity::AllInvalid) => return Ok(Validity::AllInvalid),
_ => {}
}
let len = mask.len();
let validity = mask
.clone()
.into_array()
.zip(if_true.to_array(len), if_false.to_array(len))?;
Ok(Validity::Array(validity))
}
#[cfg(test)]
mod tests {
use std::sync::LazyLock;
use rstest::rstest;
use vortex_array::ArrayRef;
use vortex_array::Canonical;
use vortex_array::Columnar;
use vortex_array::IntoArray;
use vortex_array::VortexSessionExecute;
use vortex_array::arrays::Constant;
use vortex_array::arrays::ConstantArray;
use vortex_array::arrays::PrimitiveArray;
use vortex_array::arrays::Struct;
use vortex_array::arrays::StructArray;
use vortex_array::arrays::UnionArray;
use vortex_array::arrays::VarBinView;
use vortex_array::arrays::VarBinViewArray;
use vortex_array::arrays::VariantArray;
use vortex_array::assert_arrays_eq;
use vortex_array::builders::ArrayBuilder;
use vortex_array::builders::BufferGrowthStrategy;
use vortex_array::builders::VarBinViewBuilder;
use vortex_array::dtype::DType;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::PType;
use vortex_array::dtype::UnionVariants;
use vortex_array::scalar::Scalar;
use vortex_buffer::buffer;
use vortex_error::VortexResult;
use vortex_expr::Expression;
use vortex_expr::lit;
use vortex_expr::root;
use vortex_mask::Mask;
use vortex_session::VortexSession;
use crate::builtins::ArrayFunctions;
use crate::expr::zip_expr;
static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
let session = VortexSession::empty();
vortex_array::initialize(&session);
crate::initialize(&session);
session
});
#[test]
fn dtype() {
let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
let expr = zip_expr(lit(true), root(), lit(0i32));
let result_dtype = expr.return_dtype(&dtype).unwrap();
assert_eq!(
result_dtype,
DType::Primitive(PType::I32, Nullability::NonNullable)
);
}
#[test]
fn test_display() {
let expr = zip_expr(lit(true), root(), lit(0i32));
assert_eq!(expr.to_string(), "zip($, 0i32, true)");
}
#[test]
fn test_zip_basic() {
let mut ctx = SESSION.create_execution_ctx();
let mask = Mask::from_iter([true, false, false, true, false]);
let if_true = buffer![10, 20, 30, 40, 50].into_array();
let if_false = buffer![1, 2, 3, 4, 5].into_array();
let result = mask.into_array().zip(if_true, if_false).unwrap();
let expected = buffer![10, 2, 3, 40, 5].into_array();
assert_arrays_eq!(result, expected, &mut ctx);
}
#[test]
fn test_zip_all_true() {
let mut ctx = SESSION.create_execution_ctx();
let mask = Mask::new_true(4);
let if_true = buffer![10, 20, 30, 40].into_array();
let if_false =
PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), None]).into_array();
let result = mask.into_array().zip(if_true, if_false.clone()).unwrap();
let expected =
PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), Some(40)]).into_array();
assert_arrays_eq!(result, expected, &mut ctx);
assert_eq!(result.dtype(), if_false.dtype())
}
#[test]
fn test_zip_all_false_widens_nullability() {
let mut ctx = SESSION.create_execution_ctx();
let mask = Mask::new_false(4);
let if_true =
PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), None]).into_array();
let if_false = buffer![1i32, 2, 3, 4].into_array();
let result = mask.into_array().zip(if_true.clone(), if_false).unwrap();
let expected =
PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), Some(4)]).into_array();
assert_arrays_eq!(result, expected, &mut ctx);
assert_eq!(result.dtype(), if_true.dtype());
}
#[rstest]
#[case::all_true(Some(true), 10)]
#[case::all_false(Some(false), 20)]
#[case::null_mask(None, 20)]
fn test_zip_constant_mask_preserves_constant(
#[case] mask: Option<bool>,
#[case] expected: i32,
#[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability,
) -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let if_true = ConstantArray::new(10i32, 4).into_array();
let if_false = ConstantArray::new(Scalar::primitive(20i32, nullability), 4).into_array();
let result = ConstantArray::new(mask, 4)
.into_array()
.zip(if_true, if_false)?
.execute::<Columnar>(&mut ctx)?
.into_array();
assert!(result.is::<Constant>());
let expected = ConstantArray::new(Scalar::primitive(expected, nullability), 4);
assert_arrays_eq!(result, expected, &mut ctx);
Ok(())
}
#[test]
fn test_invalid_lengths() {
let mask = Mask::new_false(4);
let if_true = buffer![10, 20, 30].into_array();
let if_false = buffer![1, 2, 3, 4].into_array();
let error = mask.into_array().zip(if_true, if_false).unwrap_err();
assert!(
error
.to_string()
.contains("children equal to the array length")
);
}
#[test]
fn test_fragmentation() -> VortexResult<()> {
let len = 100;
let const1 = ConstantArray::new(
Scalar::utf8("hello_this_is_a_longer_string", Nullability::Nullable),
len,
)
.into_array();
let const2 = ConstantArray::new(
Scalar::utf8("world_this_is_another_string", Nullability::Nullable),
len,
)
.into_array();
let indices: Vec<usize> = (0..len).step_by(2).collect();
let mask = Mask::from_indices(len, indices);
let mask_array = mask.into_array();
let mut ctx = SESSION.create_execution_ctx();
let result = mask_array
.zip(const1.clone(), const2.clone())?
.execute::<Columnar>(&mut ctx)?
.into_array();
insta::assert_snapshot!(result.display_tree(), @r"
root: vortex.varbinview(utf8?, len=100) nbytes=1.66 kB (100.00%) [all_valid]
metadata:
buffer: buffer_0 host 29 B (align=1) (1.75%)
buffer: buffer_1 host 28 B (align=1) (1.69%)
buffer: views host 1.60 kB (align=16) (96.56%)
");
let expected = VarBinViewArray::from_iter_nullable_str((0..len).map(|index| {
Some(if index % 2 == 0 {
"hello_this_is_a_longer_string"
} else {
"world_this_is_another_string"
})
}));
assert_arrays_eq!(result, expected, &mut ctx);
let wrapped1 = StructArray::try_from_iter([("nested", const1)])?.into_array();
let wrapped2 = StructArray::try_from_iter([("nested", const2)])?.into_array();
let wrapped_result = mask_array
.zip(wrapped1, wrapped2)?
.execute::<ArrayRef>(&mut ctx)?;
assert!(wrapped_result.is::<Struct>());
assert_arrays_eq!(
wrapped_result,
StructArray::try_from_iter([("nested", expected.into_array())])?,
&mut ctx
);
Ok(())
}
#[test]
fn test_varbinview_zip() {
let if_true = {
let mut builder = VarBinViewBuilder::new_in(
DType::Utf8(Nullability::NonNullable),
10,
Default::default(),
BufferGrowthStrategy::fixed(64 * 1024),
0.0,
vortex_buffer::BufferAllocatorRef::statically_allocated(),
);
for _ in 0..100 {
builder.append_value("Hello");
builder.append_value("Hello this is a long string that won't be inlined.");
}
builder.finish()
};
let if_false = {
let mut builder = VarBinViewBuilder::new_in(
DType::Utf8(Nullability::NonNullable),
10,
Default::default(),
BufferGrowthStrategy::fixed(64 * 1024),
0.0,
vortex_buffer::BufferAllocatorRef::statically_allocated(),
);
for _ in 0..100 {
builder.append_value("Hello2");
builder.append_value("Hello2 this is a long string that won't be inlined.");
}
builder.finish()
};
let mask = Mask::from_indices(200, (0..100).filter(|i| i % 3 != 0));
let mask_array = mask.clone().into_array();
let mut ctx = SESSION.create_execution_ctx();
let zipped = mask_array
.zip(if_true, if_false)
.unwrap()
.execute::<ArrayRef>(&mut ctx)
.unwrap();
let zipped = zipped.as_opt::<VarBinView>().unwrap();
assert_eq!(zipped.data_buffers().len(), 2);
let true_value = |i: usize| {
if i.is_multiple_of(2) {
"Hello"
} else {
"Hello this is a long string that won't be inlined."
}
};
let false_value = |i: usize| {
if i.is_multiple_of(2) {
"Hello2"
} else {
"Hello2 this is a long string that won't be inlined."
}
};
let expected = VarBinViewArray::from_iter_str((0..200).map(|i| {
if mask.value(i) {
true_value(i)
} else {
false_value(i)
}
}));
assert_arrays_eq!(zipped.array().clone(), expected, &mut ctx);
}
#[rstest::rstest]
#[case::zip_true(
zip_expr(lit(true), lit(1i32), root()),
DType::Primitive(PType::I32, Nullability::Nullable)
)]
#[case::zip_false(
zip_expr(lit(false), root(), lit(1i32)),
DType::Primitive(PType::I32, Nullability::Nullable)
)]
fn literal_simplification_preserves_result_dtype(
#[case] expr: Expression,
#[case] scope: DType,
) -> VortexResult<()> {
let original = expr.bind(&scope)?;
let optimized = expr.bind(&scope)?.optimize_recursive()?;
assert_eq!(optimized.dtype(), original.dtype());
Ok(())
}
#[test]
fn test_zip_variant_mixed_mask() -> VortexResult<()> {
let variants = |value: i32| -> VortexResult<ArrayRef> {
let scalar = Scalar::variant(Scalar::primitive(value, Nullability::NonNullable));
let core_storage = ConstantArray::new(scalar, 4).into_array();
Ok(VariantArray::try_new(core_storage, None)?.into_array())
};
let mut ctx = SESSION.create_execution_ctx();
let zipped = Mask::from_iter([true, false, true, false])
.into_array()
.zip(variants(1)?, variants(2)?)?
.execute::<Canonical>(&mut ctx)?
.into_array();
for (i, expected) in [1i32, 2, 1, 2].into_iter().enumerate() {
assert_eq!(
zipped.execute_scalar(i, &mut ctx)?,
Scalar::variant(Scalar::primitive(expected, Nullability::NonNullable)),
);
}
Ok(())
}
#[test]
fn test_zip_union_mixed_mask_errors() -> VortexResult<()> {
let variants = UnionVariants::try_new(
["num"].into(),
vec![DType::Primitive(PType::I32, Nullability::NonNullable)],
vec![0],
)?;
let union_of = |value: i32| -> VortexResult<ArrayRef> {
Ok(UnionArray::try_new(
PrimitiveArray::from_iter([0u8, 0]).into_array(),
variants.clone(),
vec![PrimitiveArray::from_iter([value, value]).into_array()],
)?
.into_array())
};
let mut ctx = SESSION.create_execution_ctx();
let error = Mask::from_iter([true, false])
.into_array()
.zip(union_of(1)?, union_of(2)?)?
.execute::<Canonical>(&mut ctx)
.unwrap_err();
assert!(error.to_string().contains("is not supported"), "{error}");
Ok(())
}
}