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
24 changes: 24 additions & 0 deletions vortex-functions/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ use crate::strpos::Strpos;
use crate::variant_get::VariantGet;
use crate::variant_get::VariantGetOptions;
use crate::variant_get::VariantPath;
use crate::variant_pack::VariantPack;
use crate::variant_pack::VariantPackOptions;
use crate::zip::Zip;

/// Creates a CASE WHEN expression with one WHEN/THEN pair and an ELSE value.
Expand Down Expand Up @@ -644,6 +646,28 @@ pub fn bound_variant_get(
.vortex_expect("variant-get expressions require a Variant child")
}

/// Creates a Variant expression from core storage and its shredded child.
///
/// `complete` says whether every shredded path is absent from `core`; see
/// [`VariantPackOptions::complete`].
pub fn variant_pack(core: Expression, shredded: Expression, complete: bool) -> Expression {
VariantPack.new_expr(VariantPackOptions::new(complete), vec![core, shredded])
}

/// Creates a Variant expression from core storage, a non-nullable shredded struct, and the
/// struct's validity.
pub fn variant_pack_with_validity(
core: Expression,
shredded: Expression,
validity: Expression,
complete: bool,
) -> Expression {
VariantPack.new_expr(
VariantPackOptions::with_shredded_validity(complete),
vec![core, shredded, validity],
)
}

// ---- Like ----

/// Creates a SQL LIKE expression.
Expand Down
2 changes: 2 additions & 0 deletions vortex-functions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub mod replace_time_zone;
pub mod stat;
pub mod strpos;
pub mod variant_get;
pub mod variant_pack;
pub mod zip;

#[cfg(test)]
Expand All @@ -68,6 +69,7 @@ pub fn initialize(session: &VortexSession) {
scalar_fns.register(replace_time_zone::ReplaceTimeZone);
scalar_fns.register(stat::StatFn);
scalar_fns.register(strpos::Strpos);
scalar_fns.register(variant_pack::VariantPack);
}

/// A scalar function has a negative cost if applying it to an array and
Expand Down
213 changes: 213 additions & 0 deletions vortex-functions/src/variant_get/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,12 @@ use vortex_array::scalar::Scalar;
use vortex_array::scalar_fn::Arity;
use vortex_array::scalar_fn::ChildName;
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::builtin::get_item::GetItem;
use vortex_array::scalar_fn::builtin::mask::Mask;
use vortex_array::scalar_fn::session::ScalarFnSessionExt;
use vortex_error::VortexResult;
Expand All @@ -46,6 +49,8 @@ use vortex_session::VortexSession;
use vortex_session::registry::CachedId;
use vortex_utils::aliases::StringEscape;

use crate::variant_pack::VariantPack;

/// How many lazy layers `variant_get` unwraps from its input before it extracts row by row.
const MAX_CANONICALIZE_DEPTH: usize = 8;

Expand Down Expand Up @@ -223,6 +228,66 @@ impl ScalarFnVTable for VariantGet {
builder.finish_into_variant().map(IntoArray::into_array)
}

/// Reads a shredded path from the shredded child of a [`VariantPack`] input, leaving its
/// core storage unread.
fn reduce<T: ReduceNode>(&self, options: &Self::Options, node: &T) -> VortexResult<Option<T>> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This rewrite decides which column a scan reads, so a wrong branch returns wrong values without an error. The PR has one test, and it covers the case where nothing is rewritten: the root struct with a validity child. Please add rstest cases that compare the reduced expression with the unreduced one over the same data, one for each branch:

  • a shredded field when complete is set;
  • the same field when complete is not set, which must not reduce;
  • a field that is not shredded, which reads core;
  • a path that ends in a nested shredded Variant;
  • a leaf of another type than the requested one.

It would also help to make core an array that fails when executed in the complete case, so that the test proves core is not read.

let input = node.child(0);
let Some(pack) = input
.scalar_fn()
.and_then(|scalar_fn| scalar_fn.as_opt::<VariantPack>())
else {
return Ok(None);
};
let core = input.child(0);
let mut current = input.child(1);
let mut path = options.path().elements();
// Whether `current` is below the shredded child itself. Only the shredded child can
// have left values in the core storage, so only reading it needs it to be complete.
let mut descended = false;

loop {
let dtype = current.node_dtype()?;
match (&dtype, path.split_first()) {
// A shredded Variant holds the rest of the path itself.
(DType::Variant(_), _) if descended => {
let rest = VariantGetOptions::new(
VariantPath::new(path.iter().cloned()),
options.dtype().cloned(),
);
return node.new_node(VariantGet.bind(rest), &[current]).map(Some);
}
(DType::Struct(fields, _), Some((VariantPathElement::Field(name), rest))) => {
if fields.find(name.as_ref()).is_none() {
// A field that was not shredded is only in the core storage.
return if descended {
Ok(None)
} else {
node.new_node(VariantGet.bind(options.clone()), &[core])
.map(Some)
};
}
if !descended && !pack.complete() {
return Ok(None);
}
current = current.new_node(GetItem.bind(name.clone()), &[current.clone()])?;
path = rest;
descended = true;
}
// The end of the path at a typed value of the requested dtype.
(dtype, None)
if options.dtype().is_some_and(|requested| {
!requested.is_variant() && dtype.eq_ignore_nullability(requested)
}) && (descended || (pack.complete() && !pack.shredded_validity())) =>
{
return node
.new_node(Cast.bind(node.node_dtype()?), &[current])
.map(Some);
}
_ => return Ok(None),
}
}
}

fn is_strict(&self, _options: &Self::Options) -> bool {
true
}
Expand Down Expand Up @@ -602,16 +667,20 @@ mod tests {
use std::sync::Arc;
use std::sync::LazyLock;

use rstest::rstest;
use vortex_array::ArrayRef;
use vortex_array::Canonical;
use vortex_array::IntoArray;
use vortex_array::VortexSessionExecute;
use vortex_array::arrays::BoolArray;
use vortex_array::arrays::Chunked;
use vortex_array::arrays::ChunkedArray;
use vortex_array::arrays::ConstantArray;
use vortex_array::arrays::PrimitiveArray;
use vortex_array::arrays::ScalarFn;
use vortex_array::arrays::StructArray;
use vortex_array::arrays::VariantArray;
use vortex_array::arrays::scalar_fn::ScalarFnArrayExt;
use vortex_array::arrays::variant::VariantArraySlotsExt;
use vortex_array::assert_arrays_eq;
use vortex_array::assert_nth_scalar_is_null;
Expand All @@ -628,6 +697,7 @@ mod tests {
use vortex_array::scalar::Scalar;
use vortex_array::scalar::ScalarValue;
use vortex_array::scalar_fn::ScalarFnVTable;
use vortex_array::validity::Validity;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure;
Expand All @@ -639,6 +709,7 @@ mod tests {
use crate::variant_get::VariantGetOptions;
use crate::variant_get::VariantPath;
use crate::variant_get::VariantPathElement;
use crate::variant_pack::VariantPack;

static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
let session = VortexSession::empty();
Expand Down Expand Up @@ -1322,4 +1393,146 @@ mod tests {
}
Ok(())
}

#[test]
fn variant_get_root_struct_respects_variant_pack_shredded_validity() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let core = variant_rows([
Scalar::variant(variant_object([])),
Scalar::null(DType::Variant(Nullability::Nullable)),
])?;
let shredded = StructArray::try_new(
FieldNames::from_iter(["a"]),
vec![PrimitiveArray::from_option_iter([Some(10i32), None]).into_array()],
2,
Validity::NonNullable,
)?
.into_array();
let validity = BoolArray::from_iter([true, false]).into_array();
let packed =
VariantPack::try_new_with_validity(core, shredded, validity, true)?.into_array();

let target = DType::struct_(
[("a", DType::Primitive(PType::I32, Nullability::Nullable))],
Nullability::Nullable,
);
let expr = variant_get(root(), VariantPath::root(), Some(target));
let result = packed
.apply(&expr)?
.optimize_ctx(&ctx)?
.execute::<ArrayRef>(&mut ctx)?;
assert!(result.is_valid(0, &mut ctx)?);
assert_eq!(
result
.execute_scalar(0, &mut ctx)?
.as_struct()
.field("a")
.and_then(|s| s.as_primitive().typed_value::<i32>()),
Some(10),
);
assert!(result.is_invalid(1, &mut ctx)?);
Ok(())
}

/// How [`VariantGet`] over a [`VariantPack`] reduces.
#[derive(Debug, Clone, Copy)]
enum Reduced {
/// To a read of the shredded child alone.
ToShredded,
/// To an extraction from the core storage alone.
ToCore,
/// Not at all: the pack stays and executes to a whole Variant.
No,
}

/// Variant objects whose field `a` is shredded as `i32` and field `n` as a shredded Variant,
/// over core storage that holds field `b`. When the pack is not complete, the core storage
/// also holds `a` for the last row, where the shredded `a` is null.
fn pack_over_core(complete: bool) -> VortexResult<(ArrayRef, ArrayRef, ArrayRef)> {
let b = |value: i32| Scalar::primitive(value, Nullability::NonNullable);
let last_row = if complete {
variant_object([("b", b(3))])
} else {
variant_object([
("a", Scalar::primitive(7i32, Nullability::NonNullable)),
("b", b(3)),
])
};
let core = variant_rows([
Scalar::variant(variant_object([("b", b(1))])),
Scalar::variant(variant_object([("b", b(2))])),
Scalar::variant(last_row),
])?;

let c = |value: i64| {
Scalar::variant(variant_object([(
"c",
Scalar::primitive(value, Nullability::NonNullable),
)]))
};
let shredded = StructArray::try_new(
FieldNames::from_iter(["a", "n"]),
vec![
PrimitiveArray::from_option_iter([Some(10i32), Some(20), None]).into_array(),
variant_rows([c(1), c(2), c(3)])?,
],
3,
Validity::NonNullable,
)?
.into_array();

let packed = VariantPack::try_new(core.clone(), shredded.clone(), complete)?.into_array();
Ok((core, shredded, packed))
}

/// Each rule of [`VariantGet::reduce`] over a [`VariantPack`] extracts what the Variant that
/// the pack builds gives, and reads only the child that the rule says it reads.
#[rstest]
#[case::shredded_field_of_complete_pack(&["a"], PType::I32, true, Reduced::ToShredded)]
#[case::shredded_field_of_partial_pack(&["a"], PType::I32, false, Reduced::No)]
#[case::field_not_shredded(&["b"], PType::I32, true, Reduced::ToCore)]
#[case::path_into_shredded_variant(&["n", "c"], PType::I64, true, Reduced::ToShredded)]
#[case::leaf_of_other_type(&["a"], PType::I64, true, Reduced::No)]
fn variant_get_over_variant_pack_reduces(
#[case] path: &[&str],
#[case] ptype: PType,
#[case] complete: bool,
#[case] reduced: Reduced,
) -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let (core, shredded, packed) = pack_over_core(complete)?;
let expr = variant_get(
root(),
VariantPath::new(path.iter().map(|field| VariantPathElement::field(*field))),
Some(DType::Primitive(ptype, Nullability::Nullable)),
);

let actual = packed.apply(&expr)?.optimize_ctx(&ctx)?;

let nodes = actual.depth_first_traversal().collect::<Vec<_>>();
let has_pack = nodes.iter().any(|node| {
node.as_opt::<ScalarFn>()
.is_some_and(|scalar_fn| scalar_fn.scalar_fn().id() == VariantPack.id())
});
// The optimizer can push the extraction into the chunks of `core`, so any of its arrays
// counts as reading it.
let core_nodes = core.depth_first_traversal().collect::<Vec<_>>();
let reads_core = nodes.iter().any(|node| {
core_nodes
.iter()
.any(|core_node| ArrayRef::ptr_eq(node, core_node))
});
match reduced {
Reduced::ToShredded => assert!(!has_pack && !reads_core, "{actual}"),
Reduced::ToCore => assert!(!has_pack && reads_core, "{actual}"),
Reduced::No => assert!(has_pack, "{actual}"),
}

let expected = VariantArray::try_new(core, Some(shredded))?
.into_array()
.apply(&expr)?
.execute::<ArrayRef>(&mut ctx)?;
assert_arrays_eq!(actual.execute::<ArrayRef>(&mut ctx)?, expected, &mut ctx);
Ok(())
}
}
Loading
Loading