diff --git a/encodings/parquet-variant/src/kernel.rs b/encodings/parquet-variant/src/kernel.rs index 547067a3686..774de4cb705 100644 --- a/encodings/parquet-variant/src/kernel.rs +++ b/encodings/parquet-variant/src/kernel.rs @@ -70,6 +70,7 @@ use vortex_error::vortex_err; use vortex_functions::variant_get::VariantGet; use vortex_functions::variant_get::VariantPath; use vortex_functions::variant_get::VariantPathElement; +use vortex_functions::variant_shred::VariantShred; use vortex_json::Json; use vortex_json::JsonToVariant; use vortex_mask::Mask; @@ -81,6 +82,7 @@ use crate::ParquetVariantArraySlotsExt; use crate::compute::AllNonDistinctParquetVariant; use crate::extract::covers; use crate::extract::extract; +use crate::shred::shred; pub(crate) fn initialize(session: &VortexSession) { let kernels = session.kernels(); @@ -110,6 +112,7 @@ pub(crate) fn initialize(session: &VortexSession) { const { &MaskReduceAdaptor(ParquetVariant) }, ); kernels.register_execute_parent_kernel(VariantGet.id(), ParquetVariant, VariantGetKernel); + kernels.register_execute_parent_kernel(VariantShred.id(), ParquetVariant, VariantShredKernel); kernels.register_execute_parent_kernel( JsonToVariant.id(), Extension, @@ -123,6 +126,35 @@ pub(crate) fn initialize(session: &VortexSession) { ); } +/// Shreds unshredded storage. Storage that is shredded already is left to +/// [`VariantShred`] itself, which rejects it. +#[derive(Default, Debug)] +struct VariantShredKernel; + +impl ExecuteParentKernel for VariantShredKernel { + type Parent = ExactScalarFn; + + fn execute_parent( + &self, + array: ArrayView<'_, ParquetVariant>, + parent: ScalarFnArrayView<'_, VariantShred>, + child_idx: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + if child_idx != 0 || array.typed_value().is_some() { + return Ok(None); + } + + shred( + &array, + parent.options.schema(), + parent.dtype().is_nullable(), + ctx, + ) + .map(Some) + } +} + #[derive(Default, Debug)] struct VariantGetKernel; diff --git a/encodings/parquet-variant/src/lib.rs b/encodings/parquet-variant/src/lib.rs index 0112fe07c9e..2b0c04b7ed7 100644 --- a/encodings/parquet-variant/src/lib.rs +++ b/encodings/parquet-variant/src/lib.rs @@ -35,6 +35,7 @@ mod extract; mod json_to_variant_tests; mod kernel; mod operations; +mod shred; mod validity; mod vtable; @@ -44,6 +45,7 @@ pub use array::ParquetVariantArrayExt; pub use array::ParquetVariantArraySlotsExt; pub use array::ParquetVariantSlots; pub use array::ParquetVariantSlotsView; +pub use shred::InferredShredding; use vortex_array::session::ArraySessionExt; use vortex_arrow::ArrowSessionExt; pub use vortex_json::JsonToVariant; diff --git a/encodings/parquet-variant/src/shred/infer.rs b/encodings/parquet-variant/src/shred/infer.rs new file mode 100644 index 00000000000..720e5d5e36c --- /dev/null +++ b/encodings/parquet-variant/src/shred/infer.rs @@ -0,0 +1,283 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Infers a schema from a sample of Parquet Variant objects. + +use std::collections::BTreeMap; + +use parquet_variant::Variant as PqVariant; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::Chunked; +use vortex_array::arrays::VariantArray; +use vortex_array::arrays::chunked::ChunkedArrayExt; +use vortex_array::arrays::variant::VariantArraySlotsExt; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldPath; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::StructFields; +use vortex_arrow::ArrowExportOptions; +use vortex_error::VortexResult; +use vortex_functions::variant_shred::VariantShred; +use vortex_functions::variant_shred::VariantShreddingPolicy; + +use crate::ParquetVariant; +use crate::ParquetVariantArrayExt; +use crate::arrow::prepare_variant_for_export; + +/// Caps the total path nodes allocated while sampling, bounding memory on dynamic map keys. +const MAX_TRACKED_NODES: usize = 16_384; + +/// Shreds the object fields that a sample of the values has in common. +/// +/// The schema is inferred from a bounded prefix of unshredded rows. It shreds each object field that +/// holds a string in every sampled row that has it, and that enough sampled rows have. A field +/// that also holds values of other types is not shredded, and stays in the residual binary +/// value. +#[derive(Clone, Debug)] +pub struct InferredShredding { + max_sampled_rows: usize, + max_depth: usize, + max_fields: usize, + min_presence_percent: usize, +} + +impl Default for InferredShredding { + fn default() -> Self { + Self { + max_sampled_rows: 1024, + max_depth: 4, + max_fields: 64, + min_presence_percent: 1, + } + } +} + +impl InferredShredding { + /// Requests up to `rows` unshredded rows from the writer. The default is 1024. + pub fn with_max_sampled_rows(mut self, rows: usize) -> Self { + self.max_sampled_rows = rows.max(1); + self + } + + /// Shreds fields at most `depth` objects deep. The default is 4. + pub fn with_max_depth(mut self, depth: usize) -> Self { + self.max_depth = depth; + self + } + + /// Shreds at most `fields` fields, those in the most sampled rows. The default is 64. + pub fn with_max_fields(mut self, fields: usize) -> Self { + self.max_fields = fields; + self + } + + /// Shreds a field only if at least `percent` percent of the sampled rows have it. The + /// default is 1. + pub fn with_min_presence_percent(mut self, percent: usize) -> Self { + self.min_presence_percent = percent.min(100); + self + } +} + +impl VariantShreddingPolicy for InferredShredding { + fn sample_rows(&self, _column: &FieldPath) -> usize { + self.max_sampled_rows + } + + fn schema( + &self, + _column: &FieldPath, + sample: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + self.infer_schema(sample, ctx) + } +} + +impl InferredShredding { + /// Infers a shredding schema from the leading rows of an unshredded Parquet Variant array. + pub fn infer_schema( + &self, + array: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + let sample = array.slice(0..array.len().min(self.max_sampled_rows))?; + let mut chunks = Vec::new(); + collect_shreddable_chunks(sample, &mut chunks, ctx)?; + if chunks.is_empty() { + return Ok(None); + } + + let mut root = Node::default(); + let mut sampled = 0usize; + let mut remaining_nodes = MAX_TRACKED_NODES; + for chunk in chunks { + let storage = prepare_variant_for_export(chunk, None, ctx)?; + let variants = storage + .as_::() + .to_arrow(&ArrowExportOptions::default(), ctx)?; + for idx in 0..variants.len() { + if variants.is_valid(idx) { + sampled += 1; + root.observe( + &variants.try_value(idx)?, + 0, + self.max_depth, + &mut remaining_nodes, + )?; + } + } + } + + let percent = self.min_presence_percent; + let min_rows = sampled / 100 * percent + (sampled % 100 * percent).div_ceil(100); + let mut fields = Vec::new(); + root.collect(&mut Vec::new(), min_rows.max(1), &mut fields); + + // The fields in the most rows, and of those the ones that sort first. + fields.sort_by(|(left_path, left), (right_path, right)| { + right.cmp(left).then_with(|| left_path.cmp(right_path)) + }); + fields.truncate(self.max_fields); + if fields.is_empty() { + return Ok(None); + } + + let mut shredded = Shredded::default(); + for (path, _) in fields { + shredded.insert(&path); + } + Ok(Some(shredded.dtype())) + } +} + +/// The tree of the fields to shred, which becomes the schema. +#[derive(Default)] +struct Shredded { + /// The fields of the object at this path. A path without fields is a string. + fields: BTreeMap, +} + +impl Shredded { + fn insert(&mut self, path: &[String]) { + if let Some((name, rest)) = path.split_first() { + self.fields.entry(name.clone()).or_default().insert(rest); + } + } + + /// A field is only shredded if no sampled row holds an object at it, so a path with fields + /// is never a string as well. + fn dtype(&self) -> DType { + if self.fields.is_empty() { + return DType::Utf8(Nullability::Nullable); + } + DType::Struct( + StructFields::from_iter( + self.fields + .iter() + .map(|(name, field)| (name.as_str(), field.dtype())), + ), + Nullability::Nullable, + ) + } +} + +fn collect_shreddable_chunks( + array: ArrayRef, + chunks: &mut Vec, + ctx: &mut ExecutionCtx, +) -> VortexResult<()> { + if array.is_empty() { + return Ok(()); + } + if let Some(chunked) = array.as_opt::() { + for chunk in chunked.iter_chunks() { + collect_shreddable_chunks(chunk.clone(), chunks, ctx)?; + } + return Ok(()); + } + let variant = array.execute::(ctx)?; + if variant.shredded().is_none() + && VariantShred::can_shred(variant.core_storage(), ctx.session()) + { + chunks.push(variant.into_array()); + } + Ok(()) +} + +/// What the sampled rows hold at one path. +#[derive(Default)] +struct Node { + /// How many rows hold a string. + strings: usize, + /// How many rows hold an object. + objects: usize, + /// How many rows hold a value of any other non-null type. + others: usize, + /// The fields of the objects at this path. + fields: BTreeMap, +} + +impl Node { + fn observe( + &mut self, + variant: &PqVariant<'_, '_>, + depth: usize, + max_depth: usize, + remaining_nodes: &mut usize, + ) -> VortexResult<()> { + match variant { + // A Variant null is in no typed column, and fits beside any. + PqVariant::Null => {} + PqVariant::String(_) | PqVariant::ShortString(_) => self.strings += 1, + PqVariant::Object(object) => { + self.objects += 1; + if depth < max_depth { + for field in object.iter_try() { + let (name, field) = field?; + if let Some(child) = self.fields.get_mut(name) { + child.observe(&field, depth + 1, max_depth, remaining_nodes)?; + } else if *remaining_nodes > 0 { + *remaining_nodes -= 1; + self.fields.entry(name.to_owned()).or_default().observe( + &field, + depth + 1, + max_depth, + remaining_nodes, + )?; + } + } + } + } + _ => self.others += 1, + } + Ok(()) + } + + /// Appends the fields to shred under this path, each with the number of rows that have it. + fn collect( + &self, + path: &mut Vec, + min_rows: usize, + fields: &mut Vec<(Vec, usize)>, + ) { + // A path that holds a string in every row that has it. The root is not a field. + if !path.is_empty() && self.objects == 0 && self.others == 0 && self.strings >= min_rows { + fields.push((path.clone(), self.strings)); + return; + } + + // Only descend into objects when no sampled row at this path holds a scalar or list; + // otherwise shredding this path as a struct would force those non-object rows into the + // residual and mark the chunk incomplete. + if self.strings == 0 && self.others == 0 && self.objects >= min_rows { + for (name, field) in &self.fields { + path.push(name.clone()); + field.collect(path, min_rows, fields); + path.pop(); + } + } + } +} diff --git a/encodings/parquet-variant/src/shred/mod.rs b/encodings/parquet-variant/src/shred/mod.rs new file mode 100644 index 00000000000..e48398ecb4a --- /dev/null +++ b/encodings/parquet-variant/src/shred/mod.rs @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Shreds unshredded Parquet Variant storage. +//! +//! A reader of an unshredded Variant decodes every value to extract one field of it. Shredding +//! the fields that the values have in common moves each into a typed column of its own, which a +//! reader extracts without touching the rest. +//! +//! Shredding never changes what a Variant holds: a row whose value does not fit the schema keeps +//! it in the residual binary value. So the schema only has to fit most rows to be worth it, and +//! [`InferredShredding`] infers it from a sample. +//! +//! Vortex currently accepts UTF-8 shredding leaves at the root or nested in structs and lists. +//! Numeric schemas need a separate type-preservation decision. For example, parquet-rs permits a +//! scale-zero decimal to occupy an integer column, which would change its type on an untyped read. + +mod infer; +#[cfg(test)] +mod tests; + +use std::sync::Arc; + +use arrow_schema::DataType; +use arrow_schema::Field; +use arrow_schema::Fields; +pub use infer::InferredShredding; +use parquet_variant_compute::shred_variant; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::dtype::DType; +use vortex_arrow::ArrowExportOptions; +use vortex_arrow::ArrowSessionExt; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; + +use crate::ParquetVariant; +use crate::ParquetVariantArrayExt; + +/// Shreds the unshredded storage `array` by `schema`. +/// +/// The result holds the same values as `array`, in Parquet Variant storage with a shredded +/// child, and is `nullable` or not. +pub(crate) fn shred( + array: &ArrayView<'_, ParquetVariant>, + schema: &DType, + nullable: bool, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let shredding = shredding_type(schema)?; + let variants = array.to_arrow(&ArrowExportOptions::default(), ctx)?; + let shredded = shred_variant(&variants, &shredding)?; + + ParquetVariant::from_arrow_variant_with_nullability(&shredded, nullable, &ctx.session().arrow()) +} + +/// The Arrow type that Parquet Variant shredding takes for the schema `dtype`. +/// +/// The leaves must be strings; see the module documentation. +fn shredding_type(dtype: &DType) -> VortexResult { + Ok(match dtype { + DType::Utf8(_) => DataType::Utf8, + DType::Struct(fields, _) => DataType::Struct( + fields + .names() + .iter() + .zip(fields.fields()) + .map(|(name, field)| Ok(Field::new(name.as_ref(), shredding_type(&field)?, true))) + .collect::>()?, + ), + DType::List(element, _) => DataType::List(Arc::new(Field::new_list_field( + shredding_type(element)?, + true, + ))), + _ => vortex_bail!( + "unsupported dtype {dtype} in Vortex's Parquet Variant shredding schema (expected UTF-8, struct, or list)" + ), + }) +} diff --git a/encodings/parquet-variant/src/shred/tests.rs b/encodings/parquet-variant/src/shred/tests.rs new file mode 100644 index 00000000000..a7016239849 --- /dev/null +++ b/encodings/parquet-variant/src/shred/tests.rs @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::Arc; +use std::sync::LazyLock; + +use arrow_array::ArrayRef as ArrowArrayRef; +use arrow_array::StringArray; +use parquet_variant_compute::json_to_variant; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::arrays::VariantArray; +use vortex_array::arrays::variant::VariantArraySlotsExt; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; +use vortex_arrow::ArrowSessionExt; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_expr::ArrayExprExt; +use vortex_expr::root; +use vortex_functions::expr::variant_get; +use vortex_functions::variant_get::VariantPath; +use vortex_functions::variant_shred::VariantShred; +use vortex_session::VortexSession; + +use crate::InferredShredding; +use crate::ParquetVariant; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +const ROWS: [&str; 4] = [ + r#"{"kind":"commit","time_us":1,"commit":{"collection":"post","rev":"a"},"tags":["x"]}"#, + r#"{"kind":"commit","time_us":2,"commit":{"collection":"like","rev":7}}"#, + r#"{"kind":"identity","time_us":3,"mixed":"text"}"#, + r#"{"kind":"account","time_us":"late","mixed":4}"#, +]; + +fn variants() -> VortexResult { + let json: ArrowArrayRef = Arc::new(StringArray::from_iter_values(ROWS)); + ParquetVariant::from_arrow_variant(&json_to_variant(&json)?, &SESSION.arrow()) +} + +fn utf8() -> DType { + DType::Utf8(Nullability::Nullable) +} + +fn object(fields: &[(&str, DType)]) -> DType { + DType::Struct( + StructFields::from_iter(fields.iter().map(|(name, dtype)| (*name, dtype.clone()))), + Nullability::Nullable, + ) +} + +fn shred_into(array: ArrayRef, dtype: DType) -> VortexResult { + VariantShred::try_new(array, dtype)? + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) +} + +fn inferred(policy: &InferredShredding) -> VortexResult> { + policy.infer_schema(&variants()?, &mut SESSION.create_execution_ctx()) +} + +fn shredded() -> VortexResult { + let dtype = + inferred(&InferredShredding::default())?.ok_or_else(|| vortex_err!("nothing to shred"))?; + shred_into(variants()?, dtype) +} + +/// The names of the fields of the shredded child of `array`. +fn shredded_names(array: ArrayRef) -> VortexResult> { + let shredded = array + .execute::(&mut SESSION.create_execution_ctx())? + .shredded() + .ok_or_else(|| vortex_err!("not shredded"))? + .dtype() + .clone(); + let DType::Struct(fields, _) = shredded else { + return Err(vortex_err!("shredded as {shredded}")); + }; + Ok(fields.names().iter().map(|name| name.to_string()).collect()) +} + +fn get(array: ArrayRef, path: &[&str], dtype: DType) -> VortexResult { + let path = VariantPath::new(path.iter().map(|name| (*name).into())); + array + .apply(&variant_get(root(), path, Some(dtype)))? + .execute::(&mut SESSION.create_execution_ctx()) +} + +#[test] +fn infers_the_fields_of_one_type() -> VortexResult<()> { + // `time_us`, `mixed` and `commit.rev` hold two types, and `tags` holds a list. + assert_eq!( + inferred(&InferredShredding::default())?, + Some(object(&[ + ("commit", object(&[("collection", utf8())])), + ("kind", utf8()), + ])) + ); + Ok(()) +} + +#[test] +fn infers_from_a_bounded_sample() -> VortexResult<()> { + // The first two rows disagree on `commit.rev`, and neither contains `mixed`. + let policy = InferredShredding::default().with_max_sampled_rows(2); + assert_eq!( + inferred(&policy)?, + Some(object(&[ + ("commit", object(&[("collection", utf8())])), + ("kind", utf8()), + ])) + ); + Ok(()) +} + +#[test] +fn infers_the_fields_in_the_most_rows() -> VortexResult<()> { + let policy = InferredShredding::default().with_max_fields(1); + assert_eq!(inferred(&policy)?, Some(object(&[("kind", utf8())]))); + Ok(()) +} + +#[test] +fn infers_fields_that_enough_rows_have() -> VortexResult<()> { + // `commit.collection` is in two rows of four. + let policy = InferredShredding::default().with_min_presence_percent(75); + assert_eq!(inferred(&policy)?, Some(object(&[("kind", utf8())]))); + Ok(()) +} + +#[test] +fn infers_fields_no_deeper_than_the_depth() -> VortexResult<()> { + let policy = InferredShredding::default().with_max_depth(1); + assert_eq!(inferred(&policy)?, Some(object(&[("kind", utf8())]))); + Ok(()) +} + +#[test] +fn infers_nothing_from_values_without_common_fields() -> VortexResult<()> { + let json: ArrowArrayRef = Arc::new(StringArray::from_iter_values(["1", "[1,2]", "\"a\""])); + let array = ParquetVariant::from_arrow_variant(&json_to_variant(&json)?, &SESSION.arrow())?; + let inferred = + InferredShredding::default().infer_schema(&array, &mut SESSION.create_execution_ctx())?; + assert!(inferred.is_none()); + Ok(()) +} + +#[test] +fn does_not_shred_a_mixed_scalar_and_object_field_as_a_struct() -> VortexResult<()> { + let json: ArrowArrayRef = Arc::new(StringArray::from_iter_values([ + r#"{"kind":"push","payload":"plain"}"#, + r#"{"kind":"push","payload":"plain"}"#, + r#"{"kind":"push","payload":{"sub":"nested"}}"#, + ])); + let array = ParquetVariant::from_arrow_variant(&json_to_variant(&json)?, &SESSION.arrow())?; + let inferred = + InferredShredding::default().infer_schema(&array, &mut SESSION.create_execution_ctx())?; + assert_eq!(inferred, Some(object(&[("kind", utf8())]))); + Ok(()) +} + +#[test] +fn shreds_by_the_given_schema() -> VortexResult<()> { + let schema = object(&[("kind", utf8())]); + assert_eq!(shredded_names(shred_into(variants()?, schema)?)?, ["kind"]); + Ok(()) +} + +#[test] +fn shreds_by_the_inferred_schema() -> VortexResult<()> { + assert_eq!(shredded_names(shredded()?)?, ["commit", "kind"]); + Ok(()) +} + +#[rstest] +#[case::integer(DType::Primitive(PType::I64, Nullability::Nullable))] +#[case::boolean(DType::Bool(Nullability::Nullable))] +#[case::variant(DType::Variant(Nullability::Nullable))] +fn shreds_strings_alone(#[case] leaf: DType) -> VortexResult<()> { + // Unsupported schemas must fail even if no input row matches the requested field. + assert!(shred_into(variants()?, object(&[("time_us", leaf)])).is_err()); + Ok(()) +} + +#[test] +fn does_not_shred_a_shredded_variant() -> VortexResult<()> { + assert!(shred_into(shredded()?, object(&[("kind", utf8())])).is_err()); + Ok(()) +} + +#[rstest] +#[case::shredded(&["kind"])] +#[case::nested(&["commit", "collection"])] +#[case::residual(&["mixed"])] +#[case::residual_nested(&["commit", "rev"])] +#[case::missing(&["nope"])] +fn shredding_keeps_the_strings(#[case] path: &[&str]) -> VortexResult<()> { + let expected = get(variants()?, path, utf8())? + .execute::(&mut SESSION.create_execution_ctx())?; + assert_arrays_eq!( + get(shredded()?, path, utf8())?, + expected, + &mut SESSION.create_execution_ctx() + ); + Ok(()) +} + +#[rstest] +#[case::residual(&["time_us"])] +#[case::residual_nested(&["commit", "rev"])] +fn shredding_keeps_the_integers(#[case] path: &[&str]) -> VortexResult<()> { + let int64 = DType::Primitive(PType::I64, Nullability::Nullable); + let expected = get(variants()?, path, int64.clone())? + .execute::(&mut SESSION.create_execution_ctx())?; + assert_arrays_eq!( + get(shredded()?, path, int64)?, + expected, + &mut SESSION.create_execution_ctx() + ); + Ok(()) +} diff --git a/encodings/parquet-variant/src/vtable/mod.rs b/encodings/parquet-variant/src/vtable/mod.rs index eefb076edc0..1908b73786d 100644 --- a/encodings/parquet-variant/src/vtable/mod.rs +++ b/encodings/parquet-variant/src/vtable/mod.rs @@ -218,6 +218,8 @@ impl VTable for ParquetVariant { #[cfg(test)] mod tests { + mod shredding; + use std::sync::Arc; use std::sync::LazyLock; diff --git a/encodings/parquet-variant/src/vtable/tests/shredding.rs b/encodings/parquet-variant/src/vtable/tests/shredding.rs new file mode 100644 index 00000000000..63318e2c28f --- /dev/null +++ b/encodings/parquet-variant/src/vtable/tests/shredding.rs @@ -0,0 +1,432 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::Arc; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; + +use arrow_array::ArrayRef as ArrowArrayRef; +use arrow_array::StringArray; +use parquet_variant_compute::json_to_variant; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::fns::all_non_distinct::variant_scalars_equal; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::StructArray as VxStruct; +use vortex_array::arrays::VariantArray; +use vortex_array::arrays::variant::VariantArraySlotsExt; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldPath; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::field_path; +use vortex_array::scalar::Scalar; +use vortex_array::stream::ArrayStreamExt; +use vortex_arrow::ArrowSessionExt; +use vortex_buffer::ByteBufferMut; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_expr::ArrayExprExt; +use vortex_expr::root; +use vortex_file::OpenOptionsSessionExt; +use vortex_file::WriteOptionsSessionExt; +use vortex_file::WriteStrategyBuilder; +use vortex_functions::expr::variant_get; +use vortex_functions::variant_get::VariantPath; +use vortex_functions::variant_get::VariantPathElement; +use vortex_functions::variant_shred::FixedShredding; +use vortex_functions::variant_shred::VariantShred; +use vortex_functions::variant_shred::VariantShreddingPolicy; +use vortex_layout::layouts::variant::Variant as VariantLayoutEncoding; +use vortex_session::VortexSession; + +use super::file_session_with_layout_edition; +use super::parquet_variant_file_session; +use super::typed_value_variant_array; +use crate::InferredShredding; +use crate::ParquetVariant; + +const WRITER_ROWS: [&str; 3] = [ + r#"{"kind":"commit","n":1,"commit":{"collection":"post"},"mixed":1}"#, + r#"{"kind":"identity","n":2,"mixed":"two"}"#, + r#"{"kind":"commit","n":3,"commit":{"collection":"like"}}"#, +]; + +fn writer_rows(session: &VortexSession) -> VortexResult { + let json: ArrowArrayRef = Arc::new(StringArray::from(WRITER_ROWS.to_vec())); + ParquetVariant::from_arrow_variant(&json_to_variant(&json)?, &session.arrow()) +} + +/// A writer with a shredding policy writes an unshredded Variant with the Variant layout +/// too, and a scan extracts what the unshredded Variant holds. +#[rstest] +#[tokio::test] +async fn test_file_roundtrip_variant_shredded_by_the_writer( + parquet_variant_file_session: VortexResult, +) -> VortexResult<()> { + let session = parquet_variant_file_session?; + crate::initialize(&session); + let unshredded = writer_rows(&session)?; + + let mut bytes = ByteBufferMut::empty(); + session + .write_options() + .with_strategy( + WriteStrategyBuilder::from_session(&session) + .with_variant_shredding(InferredShredding::default()) + .build(), + ) + .write(&mut bytes, unshredded.to_array_stream()) + .await?; + let file = session.open_options().open_buffer(bytes)?; + assert!(file.footer().layout().is::()); + + let utf8 = DType::Utf8(Nullability::Nullable); + let i64 = DType::Primitive(PType::I64, Nullability::Nullable); + let mut ctx = session.create_execution_ctx(); + for (path, dtype) in [ + (VariantPath::field("kind"), utf8.clone()), + ( + VariantPath::new([ + VariantPathElement::field("commit"), + VariantPathElement::field("collection"), + ]), + utf8.clone(), + ), + (VariantPath::field("n"), i64.clone()), + // A field of two types is not shredded, and stays in the core storage. + (VariantPath::field("mixed"), utf8), + (VariantPath::field("mixed"), i64), + ] { + let extraction = variant_get(root(), path, Some(dtype)); + let expected = unshredded + .clone() + .apply(&extraction)? + .execute::(&mut ctx)?; + let scanned = file + .scan()? + .with_projection(extraction.bind(file.dtype())?) + .into_array_stream()? + .read_all() + .await?; + assert_arrays_eq!(scanned, expected, &mut ctx); + } + Ok(()) +} + +#[rstest] +#[case::single_chunk(false)] +#[case::one_row_first_chunk(true)] +#[tokio::test] +async fn inferred_schema_spans_input_chunks( + parquet_variant_file_session: VortexResult, + #[case] split: bool, +) -> VortexResult<()> { + let session = parquet_variant_file_session?; + crate::initialize(&session); + let json: ArrowArrayRef = Arc::new(StringArray::from(vec![ + r#"{}"#, + r#"{"kind":"push","id":1}"#, + r#"{"kind":"fetch","id":2}"#, + ])); + let raw = ParquetVariant::from_arrow_variant(&json_to_variant(&json)?, &session.arrow())?; + let input = if split { + ChunkedArray::try_new([raw.slice(0..1)?, raw.slice(1..3)?], raw.dtype().clone())? + .into_array() + } else { + raw.clone() + }; + let mut bytes = ByteBufferMut::empty(); + session + .write_options() + .with_strategy( + WriteStrategyBuilder::from_session(&session) + .with_variant_shredding(InferredShredding::default()) + .build(), + ) + .write(&mut bytes, input.to_array_stream()) + .await?; + let read = session + .open_options() + .open_buffer(bytes)? + .scan()? + .into_array_stream()? + .read_all() + .await?; + let mut ctx = session.create_execution_ctx(); + let variant = read.execute::(&mut ctx)?; + let shredded = variant + .shredded() + .ok_or_else(|| vortex_err!("missing shredded kind"))?; + assert!(shredded.dtype().as_struct_fields().field("kind").is_some()); + assert_eq!(variant.len(), raw.len()); + for row in 0..raw.len() { + assert!(variant_scalars_equal( + &variant.execute_scalar(row, &mut ctx)?, + &raw.execute_scalar(row, &mut ctx)? + )); + } + Ok(()) +} + +struct CheckShreddingSample { + rows: usize, + expected: ArrayRef, + calls: Arc, +} + +impl VariantShreddingPolicy for CheckShreddingSample { + fn sample_rows(&self, _column: &FieldPath) -> usize { + self.rows + } + + fn schema( + &self, + column: &FieldPath, + sample: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + assert!(column.is_root()); + assert_arrays_eq!(sample.clone(), self.expected, ctx); + self.calls.fetch_add(1, Ordering::Relaxed); + Ok(None) + } +} + +#[rstest] +#[case::no_lookahead(0, 0, false)] +#[case::row_limit(2, 2, false)] +#[case::short_at_eof(100, 4, false)] +#[case::byte_limit(100, 3, true)] +#[tokio::test] +async fn shredding_replays_the_probe_in_order( + parquet_variant_file_session: VortexResult, + #[case] rows: usize, + #[case] expected_len: usize, + #[case] large_chunk: bool, +) -> VortexResult<()> { + let session = parquet_variant_file_session?; + crate::initialize(&session); + let padding = if large_chunk { + "x".repeat(1 << 20) + } else { + String::new() + }; + let json: ArrowArrayRef = Arc::new(StringArray::from(vec![ + r#"{"kind":"first"}"#.to_owned(), + format!(r#"{{"kind":"second","padding":"{padding}"}}"#), + r#"{"kind":"third"}"#.to_owned(), + r#"{"kind":"fourth"}"#.to_owned(), + ])); + let raw = ParquetVariant::from_arrow_variant(&json_to_variant(&json)?, &session.arrow())?; + let preshredded = typed_value_variant_array()?; + // Use independent buffers: slicing a large Arrow buffer can retain the full allocation. + let one = |start, len| -> VortexResult { + let strings = json.slice(start, len); + ParquetVariant::from_arrow_variant(&json_to_variant(&strings)?, &session.arrow()) + }; + let chunks = [ + preshredded.clone(), + one(0, 1)?, + preshredded, + one(1, 2)?, + one(3, 1)?, + ]; + let dtype = raw.dtype().clone(); + let input = ChunkedArray::try_new(chunks, dtype)?.into_array(); + let calls = Arc::new(AtomicUsize::new(0)); + let policy = CheckShreddingSample { + rows, + expected: raw.slice(0..expected_len)?, + calls: Arc::clone(&calls), + }; + let mut bytes = ByteBufferMut::empty(); + session + .write_options() + .with_strategy( + WriteStrategyBuilder::from_session(&session) + .with_variant_shredding(policy) + .build(), + ) + .write(&mut bytes, input.to_array_stream()) + .await?; + assert_eq!(calls.load(Ordering::Relaxed), 1); + let read = session + .open_options() + .open_buffer(bytes)? + .scan()? + .into_array_stream()? + .read_all() + .await?; + let mut ctx = session.create_execution_ctx(); + assert_eq!(read.len(), input.len()); + for row in 0..input.len() { + assert!(variant_scalars_equal( + &read.execute_scalar(row, &mut ctx)?, + &input.execute_scalar(row, &mut ctx)? + )); + } + Ok(()) +} + +/// A single policy sees logical paths, regardless of chunking or the physical storage tree. +#[rstest] +#[case::both(true, true)] +#[case::payload_only(true, false)] +#[case::other_only(false, true)] +#[case::neither(false, false)] +#[tokio::test] +async fn test_file_variant_shredding_for_each_field( + parquet_variant_file_session: VortexResult, + #[case] shred_payload: bool, + #[case] shred_other: bool, +) -> VortexResult<()> { + let session = parquet_variant_file_session?; + crate::initialize(&session); + let raw = writer_rows(&session)?; + let event = VxStruct::from_fields(&[("payload", raw.clone())])?.into_array(); + let table = VxStruct::from_fields(&[("event", event), ("other", raw)])?.into_array(); + let input = ChunkedArray::try_new(vec![table.clone(), table.clone()], table.dtype().clone())? + .into_array(); + let calls = Arc::new(AtomicUsize::new(0)); + let count = Arc::clone(&calls); + let schema = DType::struct_( + [("kind", DType::Utf8(Nullability::Nullable))], + Nullability::Nullable, + ); + let strategy = WriteStrategyBuilder::from_session(&session) + .with_variant_shredding(move |column: &FieldPath| { + count.fetch_add(1, Ordering::Relaxed); + let enabled = if *column == field_path!(event.payload) { + shred_payload + } else if *column == field_path!(other) { + shred_other + } else { + return Err(vortex_err!("unexpected logical column {column}")); + }; + Ok(enabled.then(|| schema.clone())) + }) + .build(); + let mut bytes = ByteBufferMut::empty(); + session + .write_options() + .with_strategy(strategy) + .write(&mut bytes, input.to_array_stream()) + .await?; + let file = session.open_options().open_buffer(bytes)?; + let fields = file.footer().layout().children()?; + assert_eq!( + fields[0].children()?[0].is::(), + shred_payload + ); + assert_eq!(fields[1].is::(), shred_other); + assert_eq!(calls.load(Ordering::Relaxed), 2); + Ok(()) +} + +#[rstest] +#[tokio::test] +async fn path_policy_respects_write_edition( + #[values(false, true)] allow_layout: bool, +) -> VortexResult<()> { + let session = file_session_with_layout_edition(allow_layout)?; + crate::initialize(&session); + let raw = writer_rows(&session)?; + let dtype = raw.dtype().clone(); + let schema = DType::struct_( + [("kind", DType::Utf8(Nullability::Nullable))], + Nullability::Nullable, + ); + let shredded = VariantShred::try_new(raw.clone(), schema)? + .into_array() + .execute::(&mut session.create_execution_ctx())? + .into_array(); + let input = ChunkedArray::try_new(vec![shredded, raw.clone(), raw], dtype)?.into_array(); + let calls = Arc::new(AtomicUsize::new(0)); + let count = Arc::clone(&calls); + let strategy = WriteStrategyBuilder::from_session(&session) + .with_variant_shredding(move |column: &FieldPath| { + assert!(column.is_root()); + count.fetch_add(1, Ordering::Relaxed); + Ok(None) + }) + .build(); + let mut bytes = ByteBufferMut::empty(); + session + .write_options() + .with_strategy(strategy) + .write(&mut bytes, input.to_array_stream()) + .await?; + assert_eq!(calls.load(Ordering::Relaxed), usize::from(allow_layout)); + Ok(()) +} + +#[rstest] +#[case::inferred(true)] +#[case::fixed(false)] +#[tokio::test] +async fn writer_shreds_parquet_variant_beside_constant_chunks( + parquet_variant_file_session: VortexResult, + #[case] inferred: bool, +) -> VortexResult<()> { + let session = parquet_variant_file_session?; + crate::initialize(&session); + let json: ArrowArrayRef = Arc::new(StringArray::from(WRITER_ROWS.to_vec())); + let raw = + ParquetVariant::from_arrow_variant_nullable(&json_to_variant(&json)?, &session.arrow())?; + let dtype = raw.dtype().clone(); + let null_run = ConstantArray::new(Scalar::null(dtype.clone()), 2).into_array(); + let scalar_run = + ConstantArray::new(Scalar::variant(Scalar::from(42i32)).cast(&dtype)?, 2).into_array(); + let input = ChunkedArray::try_new( + [null_run, raw.slice(0..1)?, scalar_run, raw.slice(1..3)?], + dtype, + )? + .into_array(); + + let builder = WriteStrategyBuilder::from_session(&session); + let strategy = if inferred { + builder + .with_variant_shredding(InferredShredding::default()) + .build() + } else { + let schema = DType::struct_( + [("kind", DType::Utf8(Nullability::Nullable))], + Nullability::Nullable, + ); + builder + .with_variant_shredding(FixedShredding::new(schema)) + .build() + }; + + let mut bytes = ByteBufferMut::empty(); + session + .write_options() + .with_strategy(strategy) + .write(&mut bytes, input.to_array_stream()) + .await?; + + let file = session.open_options().open_buffer(bytes)?; + assert!( + file.footer() + .layout() + .children()? + .iter() + .any(|child| child.is::()) + ); + let read = file.scan()?.into_array_stream()?.read_all().await?; + let mut ctx = session.create_execution_ctx(); + assert_eq!(read.len(), input.len()); + for row in 0..input.len() { + assert!(variant_scalars_equal( + &read.execute_scalar(row, &mut ctx)?, + &input.execute_scalar(row, &mut ctx)? + )); + } + Ok(()) +} diff --git a/vortex-file/src/strategy.rs b/vortex-file/src/strategy.rs index b35cf6e118b..987f9f6218b 100644 --- a/vortex-file/src/strategy.rs +++ b/vortex-file/src/strategy.rs @@ -13,6 +13,7 @@ use vortex_btrblocks::schemes::integer::IntDictScheme; use vortex_edition::ComponentKind; use vortex_edition::EditionSessionExt; use vortex_error::VortexExpect; +use vortex_functions::variant_shred::VariantShreddingPolicy; use vortex_layout::LayoutStrategy; use vortex_layout::VTable; use vortex_layout::layouts::buffered::BufferedStrategy; @@ -121,6 +122,7 @@ fn coalesce_then_compress( /// layouts. pub struct WriteStrategyBuilder { compressor: CompressorConfig, + variant_shredding: Option>, row_block_size: usize, data_block_target_bytes: Option, dict_max_bytes: usize, @@ -138,6 +140,7 @@ impl WriteStrategyBuilder { /// further configured, and then finally built yielding the [`LayoutStrategy`]. pub fn from_session(session: &VortexSession) -> Self { Self { + variant_shredding: None, compressor: CompressorConfig::BtrBlocks(BtrBlocksCompressorBuilder::from_session( session, )), @@ -153,6 +156,33 @@ impl WriteStrategyBuilder { } } + /// Chooses typed fields for Variant columns when the write edition permits the Variant layout. + /// By default the writer preserves the shredding supplied by the input. + /// + /// A policy may select a fixed schema, infer one from a bounded sample spanning input chunks, + /// or return `None` for a column. For example, to shred only `event.payload.kind` when + /// `event.payload` is a Variant column: + /// + /// ``` + /// use vortex_array::dtype::{DType, FieldPath, Nullability::Nullable}; + /// use vortex_array::field_path; + /// use vortex_file::WriteStrategyBuilder; + /// # use vortex_session::VortexSession; + /// # fn example(session: &VortexSession) { + /// let payload = field_path!(event.payload); + /// let schema = DType::struct_([("kind", DType::Utf8(Nullable))], Nullable); + /// let strategy = WriteStrategyBuilder::from_session(session) + /// .with_variant_shredding(move |column: &FieldPath| { + /// Ok((column == &payload).then(|| schema.clone())) + /// }) + /// .build(); + /// # } + /// ``` + pub fn with_variant_shredding(mut self, policy: impl VariantShreddingPolicy) -> Self { + self.variant_shredding = Some(Arc::new(policy)); + self + } + /// Override the row block size used for row repartitioning and zoned statistics. /// /// Larger blocks reduce footer/statistics overhead. Smaller blocks can improve pruning and @@ -321,6 +351,10 @@ impl WriteStrategyBuilder { TableStrategy::new(Arc::new(validity_strategy), Arc::new(constant)) .with_field_writers(self.field_writers); + if let Some(policy) = self.variant_shredding { + table_strategy = table_strategy.with_variant_shredding(policy); + } + if self.use_list_layout { // We need a closure here to enable recursive application of list layout. table_strategy = table_strategy.with_list_layout_factory( diff --git a/vortex-functions/src/expr/mod.rs b/vortex-functions/src/expr/mod.rs index 463411c118b..1473ce8e310 100644 --- a/vortex-functions/src/expr/mod.rs +++ b/vortex-functions/src/expr/mod.rs @@ -72,6 +72,8 @@ use crate::variant_get::VariantGetOptions; use crate::variant_get::VariantPath; use crate::variant_pack::VariantPack; use crate::variant_pack::VariantPackOptions; +use crate::variant_shred::VariantShred; +use crate::variant_shred::VariantShredOptions; use crate::zip::Zip; /// Convert a [`Date`], [`Time`], or [`Timestamp`] to a coarser `unit` with an explicit @@ -809,6 +811,12 @@ pub fn variant_pack(core: Expression, shredded: Expression, complete: bool) -> E VariantPack.new_expr(VariantPackOptions::new(complete), [core, shredded]) } +/// Creates an expression that shreds the unshredded Variant `child` by `schema`, keeping the +/// values it holds. +pub fn variant_shred(child: Expression, schema: DType) -> Expression { + VariantShred.new_expr(VariantShredOptions::new(schema), vec![child]) +} + // ---- Like ---- /// Creates a SQL LIKE expression. diff --git a/vortex-functions/src/lib.rs b/vortex-functions/src/lib.rs index 2e07802fac0..9c47f33aa0e 100644 --- a/vortex-functions/src/lib.rs +++ b/vortex-functions/src/lib.rs @@ -55,6 +55,7 @@ pub mod timestamp_to_date; pub mod timestamp_to_time; pub mod variant_get; pub mod variant_pack; +pub mod variant_shred; pub mod zip; #[cfg(test)] @@ -93,6 +94,7 @@ pub fn initialize(session: &VortexSession) { scalar_fns.register(timestamp_to_date::TimestampToDate); scalar_fns.register(timestamp_to_time::TimestampToTime); scalar_fns.register(variant_pack::VariantPack); + scalar_fns.register(variant_shred::VariantShred); session .kernels() .register_scalar_fn_supports(change_time_unit::ChangeTimeUnit); diff --git a/vortex-functions/src/variant_shred/mod.rs b/vortex-functions/src/variant_shred/mod.rs new file mode 100644 index 00000000000..3a01282b939 --- /dev/null +++ b/vortex-functions/src/variant_shred/mod.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The `vortex.variant_shred` scalar function. + +mod policy; + +use std::fmt; +use std::fmt::Display; +use std::fmt::Formatter; + +pub use policy::FixedShredding; +pub use policy::VariantShreddingPolicy; +use prost::Message; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::Masked; +use vortex_array::arrays::ScalarFnArray; +use vortex_array::arrays::VariantArray; +use vortex_array::arrays::masked::MaskedArrayExt; +use vortex_array::arrays::masked::MaskedArraySlotsExt; +use vortex_array::arrays::variant::VariantArraySlotsExt; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::optimizer::kernels::ArrayKernelsExt; +use vortex_array::proto::dtype as pb; +use vortex_array::scalar_fn::Arity; +use vortex_array::scalar_fn::ChildName; +use vortex_array::scalar_fn::ExecutionArgs; +use vortex_array::scalar_fn::ScalarFnId; +use vortex_array::scalar_fn::ScalarFnVTable; +use vortex_array::scalar_fn::ScalarFnVTableExt; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +/// Shreds an unshredded Variant by a schema. +/// +/// The schema is a tree of the typed columns to shred into: a struct for an object, a list for +/// an array, and any other dtype for a typed leaf. The result holds the same values as the input. +/// Each value that fits the schema moves into the shredded child, and the core storage keeps the +/// rest. So the schema only says where the values are stored, not what they are. +/// +/// The shredded child follows the shape of the schema, but its dtype is not the schema: a leaf +/// can be a Variant, which also holds the values of other types. +/// +/// The encoding of the Variant storage does the work, through a kernel that it registers for this +/// function. An encoding without such a kernel cannot be shredded, and execution fails. +#[derive(Clone)] +pub struct VariantShred; + +impl VariantShred { + /// Creates a lazy shredding of the Variant `input` by `schema`. + /// + /// # Errors + /// + /// Returns an error if `input` is not a Variant. + pub fn try_new(input: ArrayRef, schema: DType) -> VortexResult { + ScalarFnArray::try_new(VariantShred.bind(VariantShredOptions::new(schema)), [input]) + } + + /// Returns whether `core` can be shredded by a kernel registered in `session`. + pub fn can_shred(core: &ArrayRef, session: &VortexSession) -> bool { + let mut current = core; + while let Some(masked) = current.as_opt::() { + current = masked.child(); + } + session + .kernels() + .has_execute_parent(VariantShred.id(), current.encoding_id()) + } +} + +/// Options for [`VariantShred`]. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct VariantShredOptions { + schema: DType, +} + +impl VariantShredOptions { + /// Creates options that shred by `schema`. + pub fn new(schema: DType) -> Self { + Self { schema } + } + + /// The tree of the typed columns to shred into. + pub fn schema(&self) -> &DType { + &self.schema + } +} + +impl Display for VariantShredOptions { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.schema) + } +} + +impl ScalarFnVTable for VariantShred { + type Options = VariantShredOptions; + + fn id(&self) -> ScalarFnId { + static ID: CachedId = CachedId::new("vortex.variant_shred"); + *ID + } + + fn serialize(&self, options: &Self::Options) -> VortexResult>> { + Ok(Some(pb::DType::try_from(&options.schema)?.encode_to_vec())) + } + + fn deserialize(&self, metadata: &[u8], session: &VortexSession) -> VortexResult { + let dtype = pb::DType::decode(metadata)?; + Ok(VariantShredOptions::new(DType::from_proto( + &dtype, session, + )?)) + } + + fn arity(&self, _options: &Self::Options) -> Arity { + Arity::Exact(1) + } + + fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName { + match child_idx { + 0 => ChildName::from("input"), + _ => unreachable!("Invalid child index {child_idx} for VariantShred expression"), + } + } + + fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult { + vortex_ensure!( + arg_dtypes[0].is_variant(), + "VariantShred input must be a Variant, found {}", + arg_dtypes[0] + ); + Ok(arg_dtypes[0].clone()) + } + + /// Hands the core storage of the input to the kernel of its encoding. + /// + /// The kernels are keyed on the storage encodings. An input that is a canonical Variant, or + /// a lazy array over one, reaches this point first. + fn execute( + &self, + options: &Self::Options, + args: &dyn ExecutionArgs, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let input = args.get(0)?; + let variant = input.clone().execute::(ctx)?; + vortex_ensure!( + variant.shredded().is_none(), + "VariantShred takes a Variant that is not shredded" + ); + + let core = variant.core_storage(); + if let Some(masked) = core.as_opt::() { + let validity = masked.masked_validity().to_array(masked.len()); + return VariantShred::try_new(masked.child().clone(), options.schema.clone())? + .into_array() + .mask(validity)? + .execute::(ctx); + } + if core.encoding_id() == input.encoding_id() { + vortex_bail!( + "Variant storage {} has no kernel to shred it", + core.encoding_id() + ); + } + VariantShred::try_new(core.clone(), options.schema.clone())? + .into_array() + .execute::(ctx) + } +} + +#[cfg(test)] +mod tests { + use vortex_array::dtype::DType; + use vortex_array::dtype::FieldName; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::dtype::StructFields; + use vortex_array::scalar_fn::ScalarFnVTable; + use vortex_error::VortexResult; + use vortex_session::VortexSession; + + use super::VariantShred; + use super::VariantShredOptions; + + #[test] + fn options_roundtrip() -> VortexResult<()> { + let dtype = DType::Struct( + StructFields::from_iter([ + ( + FieldName::from("a"), + DType::Primitive(PType::I64, Nullability::Nullable), + ), + (FieldName::from("b"), DType::Utf8(Nullability::Nullable)), + ]), + Nullability::Nullable, + ); + let options = VariantShredOptions::new(dtype); + + let metadata = VariantShred.serialize(&options)?.unwrap_or_default(); + let decoded = VariantShred.deserialize(&metadata, &VortexSession::empty())?; + + assert_eq!(decoded, options); + Ok(()) + } + + #[test] + fn return_dtype_is_the_input_dtype() -> VortexResult<()> { + let options = VariantShredOptions::new(DType::Utf8(Nullability::Nullable)); + let variant = DType::Variant(Nullability::NonNullable); + + assert_eq!( + VariantShred.return_dtype(&options, std::slice::from_ref(&variant))?, + variant + ); + assert!( + VariantShred + .return_dtype(&options, &[DType::Utf8(Nullability::Nullable)]) + .is_err() + ); + Ok(()) + } +} diff --git a/vortex-functions/src/variant_shred/policy.rs b/vortex-functions/src/variant_shred/policy.rs new file mode 100644 index 00000000000..14a1de65dfd --- /dev/null +++ b/vortex-functions/src/variant_shred/policy.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::Arc; + +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldPath; +use vortex_error::VortexResult; + +/// Selects the schema for a Variant column at write time. +/// +/// The writer makes one decision per column stream that contains nonempty unshredded input. +/// The root column has an empty path. Return `Some(dtype)` to shred matching values, or +/// `None` to leave the column unshredded. Pre-shredded batches keep their own schemas. +/// Columns may be written concurrently. A closure over the column path is a zero-sample policy. +pub trait VariantShreddingPolicy: Send + Sync + 'static { + /// Requests a prefix of unshredded rows, across input chunks. Zero requires no lookahead. + /// The sample can be shorter at end of stream or when the writer reaches its buffer limit. + fn sample_rows(&self, _column: &FieldPath) -> usize { + 0 + } + + /// Chooses a schema supported by the storage encoding's [`VariantShred`](super::VariantShred) kernel. + /// `sample` has the column's Variant dtype and may be chunked. It is empty for a zero-row request. + fn schema( + &self, + column: &FieldPath, + sample: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult>; +} + +impl VariantShreddingPolicy for F +where + F: Fn(&FieldPath) -> VortexResult> + Send + Sync + 'static, +{ + fn schema( + &self, + column: &FieldPath, + _sample: &ArrayRef, + _ctx: &mut ExecutionCtx, + ) -> VortexResult> { + self(column) + } +} + +impl VariantShreddingPolicy for Arc { + fn sample_rows(&self, column: &FieldPath) -> usize { + self.as_ref().sample_rows(column) + } + + fn schema( + &self, + column: &FieldPath, + sample: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + self.as_ref().schema(column, sample, ctx) + } +} + +/// Applies a single shredding schema to every Variant column. +#[derive(Clone, Debug)] +pub struct FixedShredding(DType); + +impl FixedShredding { + /// Shreds matching values into the typed columns described by `schema`. + pub fn new(schema: DType) -> Self { + Self(schema) + } +} + +impl VariantShreddingPolicy for FixedShredding { + fn schema( + &self, + _column: &FieldPath, + _sample: &ArrayRef, + _ctx: &mut ExecutionCtx, + ) -> VortexResult> { + Ok(Some(self.0.clone())) + } +} diff --git a/vortex-layout/src/layouts/table.rs b/vortex-layout/src/layouts/table.rs index 06696bacb6b..22ea3203606 100644 --- a/vortex-layout/src/layouts/table.rs +++ b/vortex-layout/src/layouts/table.rs @@ -17,7 +17,9 @@ use async_trait::async_trait; use vortex_array::dtype::Field; use vortex_array::dtype::FieldName; use vortex_array::dtype::FieldPath; +use vortex_array::dtype::StructFields; use vortex_error::VortexResult; +use vortex_functions::variant_shred::VariantShreddingPolicy; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; use vortex_utils::aliases::hash_set::HashSet; @@ -51,6 +53,8 @@ type ListLayoutFactory = Arc Arc)>, /// A set of field-path overrides, e.g. to force one column to be compact-compressed. Keys are /// paths relative to the level this dispatcher sits at. leaf_writers: HashMap>, @@ -86,6 +90,7 @@ impl TableStrategy { /// ``` pub fn new(validity: Arc, fallback: Arc) -> Self { Self { + variant_shredding: None, leaf_writers: Default::default(), validity, leaf: fallback, @@ -145,6 +150,12 @@ impl TableStrategy { self } + /// Selects shredding schemas for the logical Variant columns handled by this dispatcher. + pub fn with_variant_shredding(mut self, policy: Arc) -> Self { + self.variant_shredding = Some((FieldPath::root(), policy)); + self + } + /// Override the default strategy for leaf columns that don't have overrides. pub fn with_default_strategy(mut self, default: Arc) -> Self { self.leaf = default; @@ -184,12 +195,18 @@ impl TableStrategy { /// /// Each field that has an override (or a deeper override beneath it) is resolved up front; /// every other field falls through to a clean descended dispatcher. - fn struct_strategy(&self) -> StructStrategy { + fn struct_strategy(&self, fields: &StructFields) -> StructStrategy { let mut field_writers: HashMap> = HashMap::default(); - // The distinct named first-segments of our override paths are the only fields that need - // anything other than the default dispatcher. + // A Variant policy needs the path of each logical column it might reach. let mut named_first: HashSet = HashSet::default(); + if self.variant_shredding.is_some() { + for (name, dtype) in fields.names().iter().zip(fields.fields()) { + if dtype.is_variant() || dtype.is_struct() || dtype.is_list() { + named_first.insert(name.clone()); + } + } + } for path in self.leaf_writers.keys() { if let Some(Field::Name(name)) = path.parts().first() { named_first.insert(name.clone()); @@ -224,7 +241,7 @@ impl TableStrategy { fn list_strategy(&self) -> Option> { let factory = self.list_layout_factory.as_ref()?; let list_layout = ListLayoutStrategy::default() - .with_elements(Arc::new(self.descend_clean())) + .with_elements(Arc::new(self.child_dispatcher(&Field::ElementType))) .with_offsets(Arc::clone(&self.leaf)) .with_validity(Arc::clone(&self.leaf)) .with_fallback(Arc::clone(&self.leaf)); @@ -247,9 +264,17 @@ impl TableStrategy { Self { leaf_writers: new_writers, - validity: Arc::clone(&self.validity), - leaf: Arc::clone(&self.leaf), - list_layout_factory: self.list_layout_factory.clone(), + ..self.child_dispatcher(field) + } + } + + fn child_dispatcher(&self, field: &Field) -> Self { + Self { + variant_shredding: self + .variant_shredding + .as_ref() + .map(|(path, policy)| (path.clone().push(field.clone()), Arc::clone(policy))), + ..self.descend_clean() } } @@ -257,6 +282,7 @@ impl TableStrategy { /// that carry no override. fn descend_clean(&self) -> Self { Self { + variant_shredding: None, leaf_writers: HashMap::default(), validity: Arc::clone(&self.validity), leaf: Arc::clone(&self.leaf), @@ -296,9 +322,9 @@ impl LayoutStrategy for TableStrategy { ) -> VortexResult { let dtype = stream.dtype().clone(); - if dtype.is_struct() { + if let Some(fields) = dtype.as_struct_fields_opt() { return self - .struct_strategy() + .struct_strategy(fields) .write_stream(ctx, segment_sink, stream, eof, session) .await; } @@ -313,9 +339,14 @@ impl LayoutStrategy for TableStrategy { if dtype.is_variant() { // The stored struct goes back through a clean dispatcher, so that its shredded - // child is split into columns, and a Variant in it is split in turn. - let storage = self.descend_clean(); - return VariantStrategy::new(Arc::new(storage), Arc::clone(&self.leaf)) + // child is split into columns. Its residual core must never re-enter the logical + // column's shredding policy. + let mut writer = + VariantStrategy::new(Arc::new(self.descend_clean()), Arc::clone(&self.leaf)); + if let Some((path, policy)) = &self.variant_shredding { + writer = writer.with_shredding(path.clone(), Arc::clone(policy)); + } + return writer .write_stream(ctx, segment_sink, stream, eof, session) .await; } diff --git a/vortex-layout/src/layouts/variant/mod.rs b/vortex-layout/src/layouts/variant/mod.rs index 0302348eb35..efcb4d1dec1 100644 --- a/vortex-layout/src/layouts/variant/mod.rs +++ b/vortex-layout/src/layouts/variant/mod.rs @@ -10,6 +10,7 @@ //! **Note**: this is an unstable and experimental format that is expected to change. Using it may //! lead to unreadable files in the future. +mod sample; #[cfg(test)] mod tests; pub mod writer; diff --git a/vortex-layout/src/layouts/variant/sample.rs b/vortex-layout/src/layouts/variant/sample.rs new file mode 100644 index 00000000000..1981217f139 --- /dev/null +++ b/vortex-layout/src/layouts/variant/sample.rs @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Bounded lookahead for a Variant column's schema policy. + +use futures::StreamExt; +use futures::TryStreamExt; +use futures::stream; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::VariantArray; +use vortex_array::arrays::variant::VariantArraySlotsExt; +use vortex_error::VortexResult; +use vortex_io::Backpressure; + +use crate::sequence::SendableSequentialStream; +use crate::sequence::SequencePointer; +use crate::sequence::SequentialStreamAdapter; +use crate::sequence::SequentialStreamExt; + +/// Stop polling for more input when the chunks held for replay reach 1 MiB. +/// The current input chunk can itself exceed the budget. +pub(super) const MAX_BUFFERED_BYTES: u64 = 1 << 20; + +/// Called only when the first unshredded chunk fits in the buffer and has fewer than `rows` rows. +pub(super) async fn sample_prefix( + first: ArrayRef, + rows: usize, + mut input: SendableSequentialStream, + eof: SequencePointer, + backpressure: &Backpressure, + ctx: &mut ExecutionCtx, +) -> VortexResult<(ArrayRef, SendableSequentialStream)> { + let dtype = input.dtype().clone(); + let mut remaining = rows - first.len(); + let mut sample = vec![first.clone()]; + let mut bytes = first.nbytes(); + let mut buffered = vec![(first, backpressure.reserve_pending(bytes))]; + + let mut ids = loop { + let Some((id, chunk)) = input.try_next().await? else { + // The exhausted producer may still own a sequence pointer preceding `eof`. + input = SequentialStreamAdapter::new(dtype.clone(), stream::empty()).sendable(); + break eof; + }; + if !chunk.is_empty() { + let variant = chunk.clone().execute::(ctx)?; + if variant.shredded().is_none() { + let take = remaining.min(chunk.len()); + sample.push(chunk.slice(0..take)?); + remaining -= take; + } + } + let size = chunk.nbytes(); + // Include a per-entry cost so empty or bufferless arrays cannot grow the queue forever. + bytes = bytes + .saturating_add(size) + .saturating_add(size_of::() as u64); + buffered.push((chunk, backpressure.reserve_pending(size))); + if remaining == 0 || bytes >= MAX_BUFFERED_BYTES { + break id.descend(); + } + // Dropping this ID lets sibling writers make progress while we poll the next batch. + }; + + let sample = ChunkedArray::try_new(sample, dtype.clone())?.into_array(); + let replay = stream::iter( + buffered + .into_iter() + .map(move |(chunk, _reservation)| Ok((ids.advance(), chunk))), + ); + let input = SequentialStreamAdapter::new(dtype, replay.chain(input)).sendable(); + Ok((sample, input)) +} diff --git a/vortex-layout/src/layouts/variant/tests.rs b/vortex-layout/src/layouts/variant/tests.rs index 5678e0d3071..40ae86531bd 100644 --- a/vortex-layout/src/layouts/variant/tests.rs +++ b/vortex-layout/src/layouts/variant/tests.rs @@ -3,6 +3,9 @@ use std::sync::Arc; +use futures::FutureExt; +use futures::StreamExt; +use futures::TryStreamExt; use futures::stream; use prost::Message; use vortex_array::ArrayContext; @@ -22,6 +25,7 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_expr::lit; use vortex_expr::mask; +use vortex_io::Backpressure; use vortex_io::runtime::single::block_on; use vortex_io::session::RuntimeSession; use vortex_io::session::RuntimeSessionExt; @@ -32,6 +36,7 @@ use vortex_session::registry::ReadContext; use super::Variant; use super::VariantLayout; use super::VariantLayoutMetadata; +use super::sample::sample_prefix; use super::storage_dtype; use super::writer::VariantStrategy; use crate::LayoutBuildContext; @@ -251,6 +256,38 @@ fn variant_rejects_invalid_shredded_dtype() -> VortexResult<()> { Ok(()) } +#[tokio::test] +async fn sample_releases_input_sequence_ids_before_polling_and_replay() -> VortexResult<()> { + let core = ConstantArray::new(Scalar::variant(1i32.into()), 1).into_array(); + let chunk = VariantArray::try_new(core, None)?.into_array(); + let (mut producer, eof) = SequenceId::root().split(); + let tail = stream::iter([chunk.clone(), chunk.clone()]).map(move |chunk| { + let mut id = producer.advance(); + // A sibling can finish its preceding writes before delivering this batch. + assert!(id.collapse().now_or_never().is_some()); + Ok((id, chunk)) + }); + let input = SequentialStreamAdapter::new(chunk.dtype().clone(), tail).sendable(); + let (sample, mut replay) = sample_prefix( + chunk, + 10, + input, + eof, + &Backpressure::new(), + &mut SESSION.create_execution_ctx(), + ) + .await?; + assert_eq!(sample.len(), 3); + let mut count = 0; + while let Some((mut id, _)) = replay.try_next().await? { + // Even an exhausted producer can hold an earlier sequence pointer until dropped. + assert!(id.collapse().now_or_never().is_some()); + count += 1; + } + assert_eq!(count, 3); + Ok(()) +} + #[test] fn variant_rejects_invalid_shredded_is_masked() -> VortexResult<()> { let (_, layout) = layouts()?; diff --git a/vortex-layout/src/layouts/variant/writer.rs b/vortex-layout/src/layouts/variant/writer.rs index 6d2787db8c0..f11cffb2e61 100644 --- a/vortex-layout/src/layouts/variant/writer.rs +++ b/vortex-layout/src/layouts/variant/writer.rs @@ -22,12 +22,15 @@ use vortex_array::arrays::variant::decode_unshredded_storage; use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; use vortex_array::dtype::FieldName; +use vortex_array::dtype::FieldPath; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_functions::variant_get::VariantGet; use vortex_functions::variant_get::VariantGetOptions; use vortex_functions::variant_get::VariantPath; +use vortex_functions::variant_shred::VariantShred; +use vortex_functions::variant_shred::VariantShreddingPolicy; use vortex_io::session::RuntimeSessionExt; use vortex_session::VortexSession; @@ -35,6 +38,8 @@ use super::CORE; use super::SHREDDED; use super::Variant; use super::VariantLayout; +use super::sample::MAX_BUFFERED_BYTES; +use super::sample::sample_prefix; use crate::LayoutRef; use crate::LayoutStrategy; use crate::LayoutWriterContext; @@ -55,6 +60,7 @@ use crate::sequence::SequentialStreamExt; /// it may lead to unreadable files in the future. #[derive(Clone)] pub struct VariantStrategy { + shredding: Option<(FieldPath, Arc)>, /// Writes the struct of the core storage and the shredded child. storage: Arc, /// Writes a Variant stream that is not shredded. @@ -65,7 +71,21 @@ impl VariantStrategy { /// Creates a Variant writer that writes the struct of a shredded Variant through `storage`, /// and a Variant that is not shredded through `fallback`. pub fn new(storage: Arc, fallback: Arc) -> Self { - Self { storage, fallback } + Self { + storage, + fallback, + shredding: None, + } + } + + /// Applies a schema policy to unshredded batches of this logical column. + pub fn with_shredding( + mut self, + column: FieldPath, + policy: Arc, + ) -> Self { + self.shredding = Some((column, policy)); + self } } @@ -92,6 +112,8 @@ impl LayoutStrategy for VariantStrategy { .await; } let dtype = stream.dtype().clone(); + let mut policy = self.shredding.as_ref(); + let mut schema = None; let mut writers = Vec::new(); let mut active = None; let mut all_sent = true; @@ -99,7 +121,45 @@ impl LayoutStrategy for VariantStrategy { if chunk.is_empty() { continue; } - let (shredding, array) = storage_chunk(chunk, &mut session.create_execution_ctx())?; + let mut exec = session.create_execution_ctx(); + let mut variant = chunk.clone().execute::(&mut exec)?; + if variant.shredded().is_none() + && VariantShred::can_shred(variant.core_storage(), session) + { + if let Some((column, policy)) = policy.take() { + let rows = policy.sample_rows(column); + if rows > chunk.len() && chunk.nbytes() < MAX_BUFFERED_BYTES { + // Release the input ID before waiting for more chunks. A sibling column + // may need to write its segment before the parent can send another row batch. + drop(id); + drop(variant); + // Split the sequence pointer only when buffering across chunks so earlier + // pre-shredded runs never wait on an unused sample pointer. + let sample_eof = eof.split_off(); + let (sample, replay) = sample_prefix( + chunk, + rows, + stream, + sample_eof, + ctx.backpressure(), + &mut exec, + ) + .await?; + schema = policy.schema(column, &sample, &mut exec)?; + stream = replay; + continue; + } + let sample = variant.core_storage().slice(0..rows.min(chunk.len()))?; + schema = policy.schema(column, &sample, &mut exec)?; + } + if let Some(schema) = &schema { + variant = + VariantShred::try_new(variant.core_storage().clone(), schema.clone())? + .into_array() + .execute::(&mut exec)?; + } + } + let (shredding, array) = storage_chunk(chunk, &variant, &mut exec)?; let sender = match &active { Some((previous, sender)) if previous == &shredding => sender, _ => { @@ -169,9 +229,9 @@ struct Shredding { fn storage_chunk( chunk: ArrayRef, + variant: &VariantArray, ctx: &mut ExecutionCtx, ) -> VortexResult<(Option, ArrayRef)> { - let variant = chunk.clone().execute::(ctx)?; let Some(shredded) = variant.shredded() else { return Ok((None, chunk)); };