Skip to content

[Variant] Add low level support for shredding and unshredding #7715

Closed as duplicate

Description

@scovich

Is your feature request related to a problem or challenge? Please describe what you are trying to do.

The variant shredding specification allows for variant values to be "shredded" where part of the overall variant is strongly-typed and part is normal binary variant. Working with shredded variant values requires writers to pull out specific subsets of a variant object that match a target schema ("shredding"). It also requires readers to potentially "unshred" by injecting strongly typed values back into the binary variant they came from.

Partial shredding of object values increases the complexity significantly -- some fields of an object could be shredded out as a struct, while others are not. And so on, recursively.

NOTE: The specification mandates that the variant metadata dictionary must contain all path parts, regardless of whether a given path is shredded or not. So (un)shredding operations do not need to modify the variant metadata dictionary.

Describe the solution you'd like

Ultimately, shredding and unshredding will be a problem for arrow-array and/or arrow-compute to solve (see below). But those higher level operations will need low-level support from Variant and its decoders/builders in order to do their work.

We should start figuring out what that low-level support looks like. A likely starting point would be the ability to insert and remove specific variant values from an existing variant object. These should be cheap byte-shuffling operations that don't waste time introspecting unrelated parts of the variant value buffer. And it needs to be efficient even when doing recursive inserts and removes as part of a partial (un)shredding operation.

At the higher level:

The parquet reader and writer will just use whatever shredding schema they receive from the parquet footer or user, respectively. No special low-level variant support needed there. But a user wishing to write shredded parquet will need a way to convert an Array of binary variant values into an Array of shredded variant values, or a strongly typed Array (e.g. StructArray) into an Array of shredded variant values. And a user wishing to read shredded parquet will will need a way to convert an Array of shredded variant values (with a specific shredding schema) to an Array of binary variant values, or an Array of shredded variant values having a different shredding schema, or a strongly typed Array (e.g. StructArray).

Describe alternatives you've considered

Just starting to think about this, and realizing we should probably start figuring out the low-level building blocks that arrow-array will eventually rely on. Now that we actually have variant builders and decoders, we can probably make progress here.

Additional context

https://github.com/apache/parquet-format/blob/master/VariantShredding.md

Activity

  1. added
    enhancement
    on Jun 19, 2025
  2. tustvold commented on Jun 19, 2025

    @tustvold
    Contributor

    Just a small point, we probably want to avoid fundamental crates like arrow-array, etc... from needing to depend on variants. These crates are used in contexts that are size sensitive, e.g. WASM, and so keeping them lightweight is important.

    I'm not sure what kernel support for variants should look like, but my ideal would be to find a way to minimise the need for explicit support in kernels outside of those specifically for variants. I had envisaged that variants would need to be materialized/coerced to a concrete arrow array before being processed by arrow kernels such as take, cast, eq, etc...

    Forcing people to depend on variant functionality, when it isn't actually part of arrow but instead parquet, feels unfortunate

  3. scovich commented on Jun 19, 2025

    @scovich
    ContributorAuthor

    I'm not sure what kernel support for variants should look like, but my ideal would be to find a way to minimise the need for explicit support in kernels outside of those specifically for variants.

    This issue is specifically about the low-level (byte slice) support for manipulating individual variant values -- a building block for future higher level columnar operations -- and that logic should almost certainly live in the parquet-variant crate?

    Meanwhile -- One way or another, people will need a way to manipulate columns of variant values in and out of more strongly-typed forms. Otherwise I'm not sure how useful variant would be in practice? Where that higher level logic lives seems like a secondary question. Probably some arrow-variant crate that depends on arrow-schema, arrow-array, and parquet-variant?

    I had envisaged that variants would need to be materialized/coerced to a concrete arrow array before being processed by arrow kernels such as take, cast, eq, etc...

    Not sure how the type system should handle it -- I'm not really familiar arrow's logical type system -- but both binary and shredded variant columns physically take the form of structs. So I'd expect the parquet reader to produce a StructArray with the appropriate columns (metadata, value, and/or typed_value). The problem is what to do with it at that point.

    One could imagine defining kernels like variant_extract (that fetch a sub-variant by path, possibly with some form of casting), a variant "reader builder" (similar to JSON builder) that can convert variant values to strongly-typed (**), a "writer builder" that can convert strongly-typed values to variant, etc. All of those would likely need the kinds of byte-level manipulation this issue describes.

    (**) Problem is, the JSON reader builder has a lot of semantics challenges that people have kind of been expecting variant to solve... so we have some work to do there if we don't want to just lift and shift the problem from json to variant.

  4. alamb commented on Jun 20, 2025

    @alamb
    Contributor

    Here is how I was imagining Variant support looks like:

    1. To arrow-rs , arrays that hold variant will be StructArrays with at least two field: metadata, and value of binary (or maybe binary dictionary / RLE) type. This mirrrors the parquet physical representation
    2. The fact that the column is a Variant is represented using the Metadata on a field (as an extension type)
    3. Arrays that hold "shredded" variant values will be StructArrays with the two metadata and value columns and the additional shredded columns
    4. Higher level engines (like DataFusion) will need to translate requests to extract a field from a variant object to the appropriate APIs on those StructArrays
    5. We will need some new kernels (probably living in parquet-variant)

    SOme potential new kernels

    1. Extract a field of a Variant column (annotated StructArray) into a new array (variant_extract as proposed by @scovich perhaps)
    2. (maybe) add a new field/fields to a Variant column
    3. json value -->variant (annotated StructArray)
    4. variant --> json
    5. variant_to_struct (an extension of variant_extract perhaps to cast to/from variant and a (real) StructArray

    I'll try and work up an example / diagram of how this would work over the next few days

  5. friendlymatthew commented on Jul 1, 2025

    @friendlymatthew
    Contributor

    take

  6. adriangb commented on Jul 2, 2025

    @adriangb
    Contributor
    • Higher level engines (like DataFusion) will need to translate requests to extract a field from a variant object to the appropriate APIs on those StructArrays

    I've started working on this bit: apache/datafusion#15057

  7. carpecodeum commented on Jul 2, 2025

    @carpecodeum
    Contributor

    @friendlymatthew I have the time to work on this as well. Should we break this issue down into a set of tasks that we can both work on simultaneously?

  8. alamb commented on Jul 2, 2025

    @alamb
    Contributor

    BTW I made some slides to try and show how I think parquet is going to work.

    https://docs.google.com/presentation/d/1NN583KuJ3nelIrrH64HAASmbRtO9khhNSO3fw0_Nslc/edit?slide=id.g33d6952b95a_0_321#slide=id.g33d6952b95a_0_321

    Image

    I would suggest you begin by sketching out what the APIs look like with an example usecase:

    1. You have a variant encoded as a StructArray with metadata/value fields (see slides)
    2. You want to "shred" it -- extract some fields from the variant into new columns

    So maybe we need a "shred" kernel that takes a StructArray in with a shredding specification and produces a StructArray out with the appropriate fields added 🤔

  9. adriangb commented on Jul 2, 2025

    @adriangb
    Contributor

    So maybe we need a "shred" kernel that takes a StructArray in with a shredding specification and produces a StructArray out with the appropriate fields added 🤔

    I think this would be great. I'd also consider a kernel to go directly from json -> shredded if that's significantly cheaper computationally.

    One thing to consider is how we're going to define the shredding strategy: first encountered keys, a fixed list of keys, most frequent keys, largest keys by size, ... I think there's a lot of possible strategies!

  10. adriangb commented on Jul 2, 2025

    @adriangb
    Contributor

    Btw @alamb I think slides are private

  11. alamb commented on Jul 3, 2025

    @alamb
    Contributor

    Btw @alamb I think slides are private

    Sorry -- fixed

    One thing to consider is how we're going to define the shredding strategy: first encountered keys, a fixed list of keys, most frequent keys, largest keys by size, ... I think there's a lot of possible strategies!

    Yes, I agree -- this is a key design API.

    I beleive @RyanBlue said they used a "Shredded Schema" specification in iceberg-java on the Parquet call the other day-- maybe we can take a friendly look at what they have done there for API inspiration

  12. changed the title [-]Add low level support for shredding and unshredding[/-] [+][Variant] Add low level support for shredding and unshredding[/+] on Jul 10, 2025
  13. alamb commented on Jul 10, 2025

    @alamb
    Contributor

    We should start figuring out what that low-level support looks like. A likely starting point would be the ability to insert and remove specific variant values from an existing variant object. These should be cheap byte-shuffling operations that don't waste time introspecting unrelated parts of the variant value buffer. And it needs to be efficient even when doing recursive inserts and removes as part of a partial (un)shredding operation.

    @friendlymatthew and I spoke a bit about this API today. Here is what I think I heard

    Add new kernels (in the parquet-variant-compute crate that @harshmotw-db is making in #7884), something like

    Field Access

    The first kernel we need is something to extract a field from a variant

    Here is a databricks function that does this: https://docs.databricks.com/gcp/en/sql/language-manual/functions/variant_get

    /// Given a StructArray with a Variant value stored as `metadata`, `value`, and optionally typed_value fields
    /// returns the specified field
    /// The returned array might be another Variant StructArray or a Primitive or StringArray
    /// if the requested field was shredded
    pub fn variant_get(variant_array: StructArray, path: VariantPath) -> Result>ArrayRef { 
    ..
    }

    Open questions:

    1. What should the "path" argument be? A String? A JSON path? Some structured thing (Vec)`?
    2. Should we also provide a "requested data type" field? Similar to the data bricks function
    /// Given a StructArray with a Variant value stored as `metadata`, `value`, and optionally typed_value fields
    /// returns the specified field CAST TO `as_type`, TYPE, IF SPECIFIED
    /// 
    /// if `as_type` is None, the returned array might be another Variant StructArray or a Primitive or StringArray
    /// if the requested field was shredded 
    ///
    /// if `as_type` is Some(type) the field is returned as the specified type. To specify returning
    /// a Variant, pass a Field with variant type in the metadata
    pub fn variant_get(variant_array: StructArray, path: VariantPath, as_type: Option<&Field>) -> Result<ArrayRef> { 
    ..
    }

    Shredding Kernel

    /// Given a StructArray with a Variant value stored in the `metadata` and value fields, 
    /// returns a new StructArray with metadata, value, and typed_value fields
    /// that have the specified columns "shredded" into strongly typed columns
    pub fn shred_variant(variant_array: StructArray, spec: ShreddingSpecification) -> StructArray { 
    ..
    }

    Open questions:

    1. What does ShreddingSpecification look like (we could look at the API in iceberg-java) to figure this out
    2. What should happen if the input variant_array already has some shredded columns
    3. Do we need an unshred_variant kernel
  14. 6 remaining items

  15. scovich commented on Jul 10, 2025

    @scovich
    ContributorAuthor

    I don't think it should be a JSON path representation. variant_get in databricks only supports a subset of JSON path. Specifically only field accesses ($.fieldName or $['fieldName']) and array indexing ($[0]) are supported. Here's the reference (look for variant) for this.

    I'm not sure I follow this argument? If Databricks only supports a subset, that just means it would never send other types of JSON paths. Is there some harm if the underlying variant library supports more?

    Or is this an argument that the Databricks-supported subset is "good enough" and there's no need to go fancier?

    Anyway tho, this seems like another reason to be cautious about variant paths in general -- different engines will likely have different (maybe even conflicting) expectations and abilities when it comes to pathing.

    Should we also provide a "requested data type" field? Similar to the data bricks function

    IMO, yes. If we don't specify a type, how do we infer what type to extract the value as? In a variant, the type could change for every row. Databricks chooses not to do any type inference and explicitly requires the user to specify a type for any variant access. When the type is not specified, like in variant_col:someField, databricks returns another variant instead of trying to infer a type. This behavior makes sense to me.

    +1

  16. alamb commented on Jul 10, 2025

    @alamb
    Contributor

    I filed a ticket with an API proposal for variant_get here:

  17. alamb commented on Jul 10, 2025

    @alamb
    Contributor

    pub fn get_object_field(&self, field_name: &str) -> Option {
    match self {
    Variant::Object(object) => object.get(field_name),
    _ => None,
    }
    }

    (plus the analagous get_array_element method)

    I think this API makes a lot of sense

    What should the "path" argument be? A String? A JSON path? Some structured thing (Vec)`?

    ....

    Overall, I would favor a variant_get that does "safe" casts only (widening, or lossless narrowing), as a compromise. Many engines will hopefully like that sane default, and those that find it too strict or too loose can always request variant and cast the result however they like.

    I think the API I sketeched out on the following issue is consistent with this plan

    If an engine wants to implement their own casting semantics, the will provide None to the API and the result with Variant and then they can do their own casting.

    If they want to cast as Arrow types they can use the existing kernel

    Though you bring up an excellent point -- given Variant has its own type system, supporting casts will require definining cast semantics for casting to Arrow types for all the variant types.

    However this seems like a reasonable low level primitive.

  18. scovich commented on Jul 10, 2025

    @scovich
    ContributorAuthor

    pub fn get_object_field(&self, field_name: &str) -> Option {
    match self {
    Variant::Object(object) => object.get(field_name),
    _ => None,
    }
    }
    (plus the analagous get_array_element method)

    I think this API makes a lot of sense

  19. alamb commented on Jul 11, 2025

    @alamb
    Contributor

    I wrote up an idea of how we might implement variant shredding here in a ticket. The idea would be to create a builder that did the shredding on creation

  20. alamb commented on Jul 11, 2025

    @alamb
    Contributor

    What if the the writer just passes a shredding schema? For example, if they want to shred v:c::INT, they could provide:

    This is an excellent idea and it seems consistent with other implementations. I tried to capture it in

  21. alamb commented on Jul 11, 2025

    @alamb
    Contributor

    Do we need an unshred_variant kernel

    Yes.

    If nothing else, we need a way for engines that don't support shredding to correctly consume shredded variant. Or who do support shredding to some degree, but don't want the high complexity of propagating shredded variant all through the query plan above the scan. Or who fully support variant but want to write it back out with a different shredding schema (see below).

    I also agree with this @scovich -- however, I am not quite sure what the API would look like yet so I am not sure yet what ticket to file

  22. scovich commented on Jul 11, 2025

    @scovich
    ContributorAuthor

    Do we need an unshred_variant kernel

    Yes.
    If nothing else, we need a way for engines that don't support shredding to correctly consume shredded variant. Or who do support shredding to some degree, but don't want the high complexity of propagating shredded variant all through the query plan above the scan. Or who fully support variant but want to write it back out with a different shredding schema (see below).

    I also agree with this @scovich -- however, I am not quite sure what the API would look like yet so I am not sure yet what ticket to file

    The public API seems simple enough? A shredded variant column would (physically) be a StructArray with typed_value alongside its metadata and value fields. I would expect an unshred_variant kernel to take such an input, and produce an output that does not have a typed_value column any more. The shredding spec requires that the metadata column already contain every needed variant path name, so it's really just a matter of rewriting the value column under the hood.

    The internal API (for low-level variant operations) would leverage a variant builder with some tweaks:

    • Wraps a VariantMetadata instead of a VariantMetadataBuilder, and field insertions fail if the key is not present
    • Ability to manually inject the bytes of an existing variant object as the value of an object field or array element, so we can bring across existing variant-encoded fields. With optional full validation, in case the input variant bytes are untrusted.

    That's what immediately comes to mind; some pathfinding would probably be required to go any further.

  23. alamb commented on Jul 11, 2025

    @alamb
    Contributor

    I also agree with this @scovich -- however, I am not quite sure what the API would look like yet so I am not sure yet what ticket to file

    The public API seems simple enough? A shredded variant column would (physically) be a StructArray with typed_value alongside its metadata and value fields. I would expect an unshred_variant kernel to take such an input, and produce an output that does not have a typed_value column any more. The shredding spec requires that the metadata column already contain every needed variant path name, so it's really just a matter of rewriting the value column under the hood.

    This makes sense to me. After some sleep and coding, I think it would be a natural follow on when we have VariantArray that encapsulates the shredding

    Basically a kernel like

    /// Unshreds Variant
    fn unshred_variant(input: VariantArray) -> VariantArray { ... }
  24. alamb commented on Jul 12, 2025

    @alamb
    Contributor

    Basically a kernel like

    /// Unshreds Variant
    fn unshred_variant(input: VariantArray) -> VariantArray { ... }

    FYI @zeroshade I think said the Golang implementation somehow re-shredded on read (VariantArray returned a Variant) - #7905 (comment)

    I haven't fully worked out how that would work

  25. alamb commented on Jul 13, 2025

    @alamb
    Contributor

    For anyone else following along, @scovich and I are discussing low level shredded variant access here: #7915 (comment)

  26. alamb commented on Jul 18, 2025

    @alamb
    Contributor

    We are discussing reading shredded variants here;

    We are discussing writing shredded variants here:

  27. alamb commented on Aug 15, 2025

    @alamb
    Contributor
  28. alamb commented on Sep 19, 2025

    @alamb
    Contributor

    I think with the merging of #8366 we should claim this ticket is done -- we have support for shredding / unshredding, though we need to fill out a lot of type support still

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions