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
32 changes: 32 additions & 0 deletions encodings/parquet-variant/src/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
Expand Down Expand Up @@ -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,
Expand All @@ -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<ParquetVariant> for VariantShredKernel {
type Parent = ExactScalarFn<VariantShred>;

fn execute_parent(
&self,
array: ArrayView<'_, ParquetVariant>,
parent: ScalarFnArrayView<'_, VariantShred>,
child_idx: usize,
ctx: &mut ExecutionCtx,
) -> VortexResult<Option<ArrayRef>> {
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;

Expand Down
2 changes: 2 additions & 0 deletions encodings/parquet-variant/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ mod extract;
mod json_to_variant_tests;
mod kernel;
mod operations;
mod shred;
mod validity;
mod vtable;

Expand All @@ -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;
Expand Down
283 changes: 283 additions & 0 deletions encodings/parquet-variant/src/shred/infer.rs
Original file line number Diff line number Diff line change
@@ -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<Option<DType>> {
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<Option<DType>> {
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_::<ParquetVariant>()
.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<String, Shredded>,
}

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<ArrayRef>,
ctx: &mut ExecutionCtx,
) -> VortexResult<()> {
if array.is_empty() {
return Ok(());
}
if let Some(chunked) = array.as_opt::<Chunked>() {
for chunk in chunked.iter_chunks() {
collect_shreddable_chunks(chunk.clone(), chunks, ctx)?;
}
return Ok(());
}
let variant = array.execute::<VariantArray>(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<String, Node>,
}

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<String>,
min_rows: usize,
fields: &mut Vec<(Vec<String>, 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();
}
}
}
}
Loading
Loading