Skip to content

fix(parquet-variant-compute): preserve nested Variant values in cast_to_variant - #12211

Merged
sdf-jkl merged 3 commits into
apache:mainfrom
Mola-maker:fix/11942-cast-to-variant-nested
Nov 27, 2026
Merged

sdf-jkl merged 3 commits into
apache:mainfrom
Mola-maker:fix/11942-cast-to-variant-nested

Conversation

@Mola-maker

@Mola-maker Mola-maker commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Rationale for this change

cast_to_variant ignores the VariantType extension on nested fields, so a Variant child is written as an object of its storage columns: a struct child a holding 1 becomes {"a":{"metadata":"...","value":"..."}} instead of {"a":1}. This affects struct, list, map, union and run-end-encoded children.

What changes are included in this PR?

  • make_arrow_to_variant_row_builder_for_field picks a new VariantArrowToVariantBuilder when the child field carries a valid VariantType extension, and otherwise falls back to the existing DataType dispatch.
  • VariantArrowToVariantBuilder unshreds the child and copies each row's Variant value.
  • The struct, list-like, map, union and run-end-encoded builders use the field-aware factory. Dictionary values have no field and are unchanged.

Are these changes tested?

Yes, one test per container in cast_to_variant.rs. The struct test also covers a shredded child and an unannotated metadata/value struct, which stays an object.

Are there any significant user-facing changes?

No.

AI usage disclosure

AI assistance was used to implement the fix and tests, following the approach sketched in #11942; the changes were verified with the crate's test suite, clippy and fmt.

@boring-cyborg boring-cyborg Bot added the parquet-variant parquet-variant* crates label Nov 12, 2026
@Rich-T-kid Rich-T-kid added the bug Squash those bugs label Nov 16, 2026
JonSnow1807 pushed a commit to JonSnow1807/arrow-rs that referenced this pull request Nov 16, 2026
…ll-null cast_to_variant input (apache#12246)

# Which issue does this PR close?

- Closes apache#11946
- Part of apache#10546

# Rationale for this change

`cast_to_variant` returned `Ok` for duration/interval types (directly or
nested) when the input was empty or all null, and the unsupported-type
error as soon as one row held a value. There are two causes:

1. The all-null fast path in `cast_to_variant_with_options` returned
before `make_arrow_to_variant_row_builder`, which is the only place
types are checked.
2. `UnionArrowToVariantBuilder::new` looped over the per-row
`type_ids()` buffer, so it only built (and type-checked) the children
some row selects, and rebuilt that child's builder once per row.

Moving the type check before the shortcut, as the issue suggests, fixes
the first cause but not the second: an empty union with a duration
child, or one whose rows never select that child, is still accepted. So
the union loop also changes.

# What changes are included in this PR?

- Build the row builder before the all-null fast path, so the existing
recursive type check runs first. Supported types still take the bulk
`append_nulls` fast path.
- Create one union child builder per declared field
(`union_array.fields().iter()`) instead of per row. This matches the
comment above the loop and the behaviour before apache#8299.

apache#12211 also edits the body of the same union loop, so one of the two
will need a small rebase.

# Are these changes tested?

Yes. `test_cast_to_variant_duration_or_interval_errors` now also checks
empty and all-null arrays of each of the seven duration/interval types,
directly and inside a list, a struct and a sparse union, plus supported
controls. Without the fix it fails with `List(Duration(s)) with 0 rows`;
with only the fast-path reorder it still fails on the empty union case.

# Are there any significant user-facing changes?

- Empty or all-null arrays of unsupported types (including nested ones),
and unions that declare an unsupported child, now return the same
`InvalidArgumentError` as populated arrays instead of `Ok`. No
signatures change.
- All-null map and dictionary inputs now pay builder construction (for
maps, casting the keys to Utf8; for dictionaries, normalising the keys).
Because a map slice's keys are the parent's whole entries array, an
all-null 1000-row slice of a 1M-entry map goes from ~0.01 ms to ~17 ms,
the same as a populated slice of that map already costs. Other all-null
types show no measurable change.
- Valid unions convert ~1.8× faster, since child builders are no longer
rebuilt per row.

If you'd rather keep the fast path cost-free for maps, the alternatives
are narrowing the map key cast to the offsets range, or a
`DataType`-only recursive check before the shortcut.

# AI usage disclosure

The patch, test, verification and the benchmark numbers above were
produced with an AI coding agent (Claude Code), and a separate agent
session re-checked them before submission.
@Mola-maker

Copy link
Copy Markdown
Contributor Author

@bharadwaj-pendyala This fixes #11942, which you reproduced and sketched the fix for. The PR has been open for 10 days with no review yet. Would you be able to take a look?

@sdf-jkl sdf-jkl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @Mola-maker 🙏

Left some suggestions

impl VariantArrowToVariantBuilder {
pub(crate) fn new(array: &dyn Array) -> Result<Self, ArrowError> {
Ok(Self {
variant_array: VariantArray::try_new(array)?,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

try_value can't build a borrowed Variant from a struct or list typed_value. It returns NotYetImplemented. So a child shredded as an object or array fails the whole cast.

Repro: shred [{"x":1,"y":"e"}, {"x":"s"}, 42] with Struct(x: Int64), then wrap it as Variant field a in a struct. cast_to_variant returns:

NotYetImplemented("VariantArray::try_value cannot materialize typed_value of type Struct(\"x\": ...) as a borrowed Variant; call unshred_variant first")

Before this PR the same input did not error (the output was the storage object, so still wrong). variant_get unshreds before returning Variant output (variant_get.rs:236), and the same works here:

Suggested change
variant_array: VariantArray::try_new(array)?,
// `try_value` cannot materialize struct or list `typed_value`
variant_array: crate::unshred_variant(&VariantArray::try_new(array)?)?,

unshred_variant returns a clone when there is no typed_value, so unshredded children pay nothing extra. Please also replace the Int32 shredding in test_cast_to_variant_struct_with_shredded_variant_child with the object shredding above. try_value supports Int32, so the current test doesn't catch this.

Comment on lines +279 to +283
/// Builds the row builder for a child array described by `field`.
///
/// When the field carries a valid [`VariantType`] extension, the child is already
/// a [`VariantArray`] and its rows are copied through unchanged; otherwise this
/// falls back to dispatching on the field's data type.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The doc comments mostly repeat the code. One line is enough:

Suggested change
/// Builds the row builder for a child array described by `field`.
///
/// When the field carries a valid [`VariantType`] extension, the child is already
/// a [`VariantArray`] and its rows are copied through unchanged; otherwise this
/// falls back to dispatching on the field's data type.
/// Like [`make_arrow_to_variant_row_builder`], but reads a Variant-annotated child as Variant
/// values instead of as its storage struct.

Comment on lines +521 to +523
/// Builder for a child array that is already a [`VariantArray`]. Rows are copied
/// through unchanged instead of being re-serialized as objects, including rows
/// stored as shredded `typed_value`s.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Same here:

Suggested change
/// Builder for a child array that is already a [`VariantArray`]. Rows are copied
/// through unchanged instead of being re-serialized as objects, including rows
/// stored as shredded `typed_value`s.
/// Builder for a Variant-annotated child array.

pub(crate) fn new(array: &'a L, options: &'a CastOptions) -> Result<Self, ArrowError> {
let values = array.values();
// The values field carries the extension type of the values, if any.
let values_field: &Field = match array.data_type() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The error arm can't be reached, because ListLikeArray is only implemented for these five types. make_arrow_to_variant_row_builder already matches DataType::List(_) and the other list types, so it can pass the field in and this match goes away:

DataType::List(f) => List(ListArrowToVariantBuilder::new(f, array.as_list(), options)?),
// same for LargeList, ListView, LargeListView, FixedSizeList(f, _)
pub(crate) fn new(
    values_field: &'a Field,
    array: &'a L,
    options: &'a CastOptions,
) -> Result<Self, ArrowError> {
    let values_builder =
        make_arrow_to_variant_row_builder_for_field(values_field, array.values(), options)?;

child_array.as_ref(),
options,
)?;
let child_builder = match union_array.fields().find_by_type_id(type_id) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

#12246 changed this loop on main to for (type_id, _) in union_array.fields().iter(). After the rebase the field is already in hand, so find_by_type_id and the None arm can go (union_array.child(type_id) panics for an unknown id before None could matter):

for (type_id, child_field) in union_array.fields().iter() {
    let child_array = union_array.child(type_id);
    let child_builder =
        make_arrow_to_variant_row_builder_for_field(child_field, child_array.as_ref(), options)?;
    child_builders.insert(type_id, Box::new(child_builder));
}

}

#[test]
fn test_cast_to_variant_struct_with_variant_child() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The tests can be much shorter without losing coverage. The new builder has two branches (is_null and try_value) and each container needs its child field wired, so one row per container is enough. Building the child from JSON and comparing JSON output also removes the two VariantBuilder blocks for the expected list values:

/// `None` is SQL NULL.
fn json_variants(json: &[Option<&str>]) -> VariantArray {
    json_to_variant(&(Arc::new(StringArray::from(json.to_vec())) as ArrayRef)).unwrap()
}

fn assert_cast_json(input: &dyn Array, expected: &str) {
    let output = ArrayRef::from(cast_to_variant(input).unwrap());
    assert_eq!(variant_to_json(&output).unwrap().value(0), expected);
}

#[test]
fn test_cast_to_variant_list_with_variant_values() {
    let values = json_variants(&[Some(r#"{"k":[2]}"#), None]);
    let field = Arc::new(values.field("item"));
    let input = ListArray::new(field, OffsetBuffer::from_lengths([2]), values.into(), None);
    assert_cast_json(&input, r#"[{"k":[2]},null]"#);
}

The nested {"k":[2]} value also checks that field names from the child's metadata end up in the output metadata, which no current test covers. The None element covers the is_null branch.

The shredded case fits in the struct test as a third column, next to the annotated and unannotated ones:

let input = StructArray::from(vec![
    (Arc::new(child.field("a")), ArrayRef::from(child.clone())),
    (Arc::new(Field::new("b", child.inner().data_type().clone(), true)), child.into()),
    (Arc::new(shredded.field("c")), shredded.into()),
]);
assert_cast_json(&input, r#"{"a":1,"b":{"metadata":"AQAA","value":"DAE="},"c":{"x":1,"y":"e"}}"#);

I would drop the null row from the struct test. obj1.get("a") == None pins the current "drop null members" behaviour, which #11965 (open) changes, and it is not what this PR is about. The list test covers the SQL NULL branch already.

For the union, a single Variant field is enough (UnionFields::from_fields(vec![child.field("v")])). The Int32 child goes through the existing path.

Mola-maker and others added 2 commits November 25, 2026 10:13
…to_variant

Nested Variant storage (a child field carrying the VariantType extension)
was serialized as an ordinary object with metadata/value columns instead of
being copied through as a Variant value.

Add a Variant row builder that wraps the child in VariantArray::try_new and
copies rows with try_value (null rows stay null), and a field-aware factory
that selects it when the child field has a valid VariantType extension.
Wire it into the struct, list-like, map, union and run-end-encoded builders,
which already have the child field; dictionary values carry no field and are
unchanged, as are unannotated structs with metadata/value columns.
- Unshred Variant-annotated children before reading rows, because
  `VariantArray::try_value` cannot materialize a struct or list
  `typed_value`; the shredded test now shreds an object so it covers this.
- Pass the values field into `ListArrowToVariantBuilder::new` and drop the
  unreachable data type match.
- Iterate union fields directly instead of looking them up by type id.
- Shorten doc comments and simplify the tests with JSON helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BSuRaS8ckKUDuVKcPq3VoJ
@Mola-maker
Mola-maker force-pushed the fix/11942-cast-to-variant-nested branch from 372cd89 to e24e164 Compare November 25, 2026 10:26
@Mola-maker

Mola-maker commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All six comments are addressed in the new head. The shredded child is unshredded before try_value, and the test now shreds an object so it covers the bug. The struct test no longer has the null row. The union test uses a single Variant field. The doc comments are one line each. ListArrowToVariantBuilder::new takes the values field directly. The union loop iterates fields directly. The tests use the json_variants and assert_cast_json helpers.

@Mola-maker

Copy link
Copy Markdown
Contributor Author

@sdf-jkl Ready for another look when you have time. All your comments are addressed; I also merged main (the fork CI failure was a cargo-audit advisory on url, unrelated) and refreshed the description.

@sdf-jkl sdf-jkl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @Mola-maker LGTM

@sdf-jkl
sdf-jkl added this pull request to the merge queue Nov 27, 2026
Merged via the queue into apache:main with commit b325878 Nov 27, 2026
22 checks passed
@sdf-jkl

sdf-jkl commented Nov 27, 2026

Copy link
Copy Markdown
Member

Thanks again @Mola-maker 🙏

@Mola-maker

Copy link
Copy Markdown
Contributor Author

ovo

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

Labels

bug Squash those bugs parquet-variant parquet-variant* crates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Variant] cast_to_variant serializes nested Variant storage as ordinary objects

4 participants