This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git


The following commit(s) were added to refs/heads/main by this push:
     new 4ea4d225e4 fix(variant): preserve nulls for missing shredded list 
indexes (#12224)
4ea4d225e4 is described below

commit 4ea4d225e4312f968e8cc9ab3922aa460ac377e6
Author: Kosta Tarasov <[email protected]>
AuthorDate: Fri Nov 13 05:13:32 2026 +0000

    fix(variant): preserve nulls for missing shredded list indexes (#12224)
    
    # Which issue does this PR close?
    
    - Closes #11050.
    - Supersedes #11052.
    
    # Rationale for this change
    
    This carries @emecii's fix from #11052, which was approved but has had
    no activity since October. The commit is unchanged and keeps their
    authorship, rebased onto current `main`.
    
    An out-of-bounds list lookup and a present Variant null both produce
    null child columns after `take`. Without tracking index validity
    separately, shredded input turns missing list positions into valid
    Variant nulls, unlike unshredded input.
    
    # What changes are included in this PR?
    
    - Carry the list index validity mask through shredded path traversal
    (@emecii's commit).
    - Apply that mask to the output while preserving explicit Variant null
    elements as valid values.
    - Regression test distinguishing an empty list, an explicit null
    element, and a typed element.
    - When no row has the requested index in bounds, the path step is
    `Missing` and `take` is skipped. This addresses the all-out-of-bounds
    slowdown measured in #11052. `value` is not consulted because arrays are
    never stored there when `typed_value` is a list, which matches Spark
    (`SparkShreddingUtils` returns null for an out-of-bounds index without
    reading `value`).
    - For the same reason, the two existing no-match exits of the list index
    step (elements are not a struct, or elements hold no values) now also
    return `Missing` instead of falling back to `value` row by row. For
    valid data this changes no results, since `value` can only hold
    non-arrays there, which index to NULL.
    - A `Missing` path step with no `as_type` now returns an all-null
    `VariantArray`, as documented on `GetOptions::as_type`, instead of a
    `NullArray`.
    
    # Are these changes tested?
    
    Yes. `test_shredded_list_out_of_bounds_is_null` distinguishes an empty
    list, an explicit null element, a typed element, and a non-list row, for
    both a mixed and an all-out-of-bounds index. The existing missing-path
    Variant output test now also runs without `as_type`.
    
    `variant_get_list_index_all_oob_int64_64_rows` goes from 1.32 µs to 0.47
    µs locally compared to #11052. The other `variant_get_list_index`
    benchmarks are within noise.
    
    # Are there any significant user-facing changes?
    
    `variant_get` without `as_type` now returns an all-null `VariantArray`
    instead of a `NullArray` when the path cannot match a shredded column,
    for example a field that does not exist on a fully shredded object.
    
    # AI usage disclosure
    
    The original change was written with OpenAI Codex (see #11052). Claude
    Code carried the commit over and drafted this description.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-authored-by: Yifan Chen <[email protected]>
    
    ---------
    
    Co-authored-by: Yifan Chen <[email protected]>
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 parquet-variant-compute/src/variant_get.rs | 153 ++++++++++++++++++-----------
 1 file changed, 98 insertions(+), 55 deletions(-)

diff --git a/parquet-variant-compute/src/variant_get.rs 
b/parquet-variant-compute/src/variant_get.rs
index 6d7f28318e..b0f1ceb339 100644
--- a/parquet-variant-compute/src/variant_get.rs
+++ b/parquet-variant-compute/src/variant_get.rs
@@ -25,7 +25,11 @@ use std::sync::Arc;
 
 pub(crate) enum ShreddedPathStep {
     /// Path step succeeded, return the new shredding state
-    Success(ShreddingState),
+    Success {
+        state: ShreddingState,
+        /// Validity after evaluating this path element.
+        path_nulls: Option<NullBuffer>,
+    },
     /// The path element is not present in the `typed_value` column and the 
`value` column is
     /// all-null, so we know it does not exist. It, and all paths under it, 
are all-NULL.
     Missing,
@@ -35,12 +39,14 @@ pub(crate) enum ShreddedPathStep {
     NotShredded,
 }
 
-/// Build the next shredding state by taking one list-like element (at 
`index`) per input row.
+/// Take one list-like element (at `index`) per input row as the next path 
step.
 ///
-fn take_list_like_index_as_shredding_state<L: ListLikeArray + 'static>(
+/// Arrays are never stored in `value` when `typed_value` is a list, so when 
no element can match,
+/// the step is [`ShreddedPathStep::Missing`] without consulting `value`.
+fn follow_list_like_index<L: ListLikeArray + 'static>(
     typed_value: &dyn Array,
     index: usize,
-) -> Result<Option<ShreddingState>> {
+) -> Result<ShreddedPathStep> {
     let list_array = typed_value.as_any().downcast_ref::<L>().ok_or_else(|| {
         ArrowError::ComputeError(format!(
             "Expected array type '{}' while handling list-like path step, got 
'{}'",
@@ -52,7 +58,7 @@ fn take_list_like_index_as_shredding_state<L: ListLikeArray + 
'static>(
     let values = list_array.values();
 
     let Some(struct_array) = values.as_struct_opt() else {
-        return Ok(None);
+        return Ok(ShreddedPathStep::Missing);
     };
     let shredding_state = ShreddingState::try_from(struct_array)?;
 
@@ -61,17 +67,27 @@ fn take_list_like_index_as_shredding_state<L: ListLikeArray 
+ 'static>(
 
     // If list elements have neither typed nor fallback values, this path step 
is missing.
     if typed_array.is_none() && value_array.null_count() == value_array.len() {
-        return Ok(None);
+        return Ok(ShreddedPathStep::Missing);
     }
 
     let mut take_indices = Vec::with_capacity(list_array.len());
+    let mut any_in_bounds = false;
     for row in 0..list_array.len() {
         let row_range = list_array.element_range(row);
         let take_index = (index < row_range.len()).then(|| (row_range.start + 
index) as u64);
+        any_in_bounds |= take_index.is_some();
         take_indices.push(take_index);
     }
 
+    if !any_in_bounds {
+        return Ok(ShreddedPathStep::Missing);
+    }
+
     let index_array = UInt64Array::from(take_indices);
+    // Keep index validity separate from the gathered child arrays: both child 
columns are null
+    // for an out-of-bounds index, but that same physical state represents an 
explicit Variant null
+    // for a present list element.
+    let path_nulls = index_array.nulls().cloned();
 
     // Gather both typed and fallback values at the requested element index.
     let taken_value = take(value_array, &index_array, None)?;
@@ -79,7 +95,10 @@ fn take_list_like_index_as_shredding_state<L: ListLikeArray 
+ 'static>(
         .map(|typed| take(typed, &index_array, None))
         .transpose()?;
 
-    Ok(Some(ShreddingState::new(taken_value, taken_typed)))
+    Ok(ShreddedPathStep::Success {
+        state: ShreddingState::new(taken_value, taken_typed),
+        path_nulls,
+    })
 }
 
 /// Given a shredded variant field -- a `(value?, typed_value?)` pair -- try 
to take one path step
@@ -143,31 +162,28 @@ pub(crate) fn follow_shredded_path_element(
             })?;
 
             let state = ShreddingState::try_from(struct_array)?;
-            Ok(ShreddedPathStep::Success(state))
+            Ok(ShreddedPathStep::Success {
+                state,
+                path_nulls: None,
+            })
         }
         VariantPathElement::Index { index } => {
-            let state = match typed_value.data_type() {
-                DataType::List(_) => take_list_like_index_as_shredding_state::<
-                    GenericListArray<i32>,
-                >(typed_value.as_ref(), *index)?,
-                DataType::LargeList(_) => 
take_list_like_index_as_shredding_state::<
-                    GenericListArray<i64>,
-                >(typed_value.as_ref(), *index)?,
-                DataType::ListView(_) => 
take_list_like_index_as_shredding_state::<
-                    GenericListViewArray<i32>,
-                >(typed_value.as_ref(), *index)?,
-                DataType::LargeListView(_) => 
take_list_like_index_as_shredding_state::<
-                    GenericListViewArray<i64>,
-                >(typed_value.as_ref(), *index)?,
-                _ => {
-                    // JSONPath semantics: indexing a non-list yields no match.
-                    return Ok(missing_path_step());
+            let typed_value = typed_value.as_ref();
+            match typed_value.data_type() {
+                DataType::List(_) => {
+                    
follow_list_like_index::<GenericListArray<i32>>(typed_value, *index)
                 }
-            };
-
-            match state {
-                Some(state) => Ok(ShreddedPathStep::Success(state)),
-                None => Ok(missing_path_step()),
+                DataType::LargeList(_) => {
+                    
follow_list_like_index::<GenericListArray<i64>>(typed_value, *index)
+                }
+                DataType::ListView(_) => {
+                    
follow_list_like_index::<GenericListViewArray<i32>>(typed_value, *index)
+                }
+                DataType::LargeListView(_) => {
+                    
follow_list_like_index::<GenericListViewArray<i64>>(typed_value, *index)
+                }
+                // JSONPath semantics: indexing a non-list yields no match.
+                _ => Ok(missing_path_step()),
             }
         }
         VariantPathElement::ListElement => 
Err(ArrowError::InvalidArgumentError(
@@ -266,34 +282,34 @@ fn shredded_get_path(
     let mut path_index = 0;
     for path_element in path {
         match follow_shredded_path_element(&shredding_state, path_element, 
cast_options)? {
-            ShreddedPathStep::Success(state) => {
+            ShreddedPathStep::Success { state, path_nulls } => {
                 // Union nulls from the typed_value we just accessed
                 if let Some(typed_value) = 
shredding_state.typed_value_column() {
                     accumulated_nulls =
                         NullBuffer::union(accumulated_nulls.as_ref(), 
typed_value.nulls());
                 }
+                accumulated_nulls =
+                    NullBuffer::union(accumulated_nulls.as_ref(), 
path_nulls.as_ref());
                 shredding_state = state;
                 path_index += 1;
             }
             ShreddedPathStep::Missing => {
                 let num_rows = input.len();
-                if 
as_field.is_some_and(Field::has_valid_extension_type::<VariantType>) {
-                    let all_nulls = 
Some(arrow::buffer::NullBuffer::from(vec![false; num_rows]));
-                    // Propagating metadata is not necessary for an all-NULL 
array, but is cheaper than constructing
-                    // a new empty metadata array. (n * 3 bytes vs Arc bump)
-                    let metadata = input.metadata_column().clone();
-                    let arr = VariantArray::from_parts_unshredded(
-                        metadata,
-                        all_null_value_column(num_rows),
-                        all_nulls,
-                    );
-                    return Ok(ArrayRef::from(arr));
+                if let Some(field) =
+                    as_field.filter(|f| 
!f.has_valid_extension_type::<VariantType>())
+                {
+                    return Ok(array::new_null_array(field.data_type(), 
num_rows));
                 }
-                let arr = match as_field.map(|f| f.data_type()) {
-                    Some(data_type) => array::new_null_array(data_type, 
num_rows),
-                    None => Arc::new(array::NullArray::new(num_rows)) as _,
-                };
-                return Ok(arr);
+                let all_nulls = 
Some(arrow::buffer::NullBuffer::from(vec![false; num_rows]));
+                // Propagating metadata is not necessary for an all-NULL 
array, but is cheaper than constructing
+                // a new empty metadata array. (n * 3 bytes vs Arc bump)
+                let metadata = input.metadata_column().clone();
+                let arr = VariantArray::from_parts_unshredded(
+                    metadata,
+                    all_null_value_column(num_rows),
+                    all_nulls,
+                );
+                return Ok(ArrayRef::from(arr));
             }
             ShreddedPathStep::NotShredded => {
                 let target = make_target_variant(
@@ -1997,8 +2013,8 @@ mod test {
         for (case, array_gen) in shredded_list_like_cases() {
             let result = variant_get(&array_gen(), options.clone()).unwrap();
             let result_variant = VariantArray::try_new(&result).unwrap();
-            assert_eq!(result_variant.value(0), Variant::Null, "{case}");
-            assert_eq!(result_variant.value(1), Variant::Null, "{case}");
+            assert!(result_variant.is_null(0), "{case}");
+            assert!(result_variant.is_null(1), "{case}");
         }
     }
 
@@ -2073,6 +2089,30 @@ mod test {
         assert_eq!(&casted, &expected);
     }
 
+    #[test]
+    fn test_shredded_list_out_of_bounds_is_null() {
+        // The non-list row is stored in the list-level `value` column.
+        let json: ArrayRef = Arc::new(StringArray::from(vec!["[]", "[null]", 
"[1]", r#""x""#]));
+        let input = json_to_variant(&json).unwrap();
+        let list_schema = DataType::new_list(DataType::Int64, true);
+        let shredded = ArrayRef::from(shred_variant(&input, 
&list_schema).unwrap());
+
+        let options = GetOptions::new_with_path(VariantPath::from(0));
+        let result = variant_get(&shredded, options).unwrap();
+        let result = VariantArray::try_new(&result).unwrap();
+
+        assert!(result.is_null(0));
+        assert!(!result.is_null(1));
+        assert_eq!(result.value(1), Variant::Null);
+        assert_eq!(result.value(2), Variant::Int64(1));
+        assert!(result.is_null(3));
+
+        let options = GetOptions::new_with_path(VariantPath::from(5));
+        let result = variant_get(&shredded, options).unwrap();
+        let result = VariantArray::try_new(&result).unwrap();
+        assert!((0..4).all(|i| result.is_null(i)));
+    }
+
     /// Helper to create a shredded list-like variant array used by list index 
tests.
     ///
     /// Rows:
@@ -2489,14 +2529,17 @@ mod test {
         let variant_field = 
VariantArray::try_new(&unshredded).unwrap().field("result");
 
         // indexing into a struct typed_value can never match: all-null 
variant output
-        let options = 
GetOptions::new_with_path(VariantPath::try_from("field_name[0]").unwrap())
-            .with_as_type(Some(FieldRef::from(variant_field)));
-        let result = variant_get(&shredded, options).unwrap();
-        let result_variant = VariantArray::try_new(&result).unwrap();
+        for as_type in [Some(FieldRef::from(variant_field)), None] {
+            let options =
+                
GetOptions::new_with_path(VariantPath::try_from("field_name[0]").unwrap())
+                    .with_as_type(as_type);
+            let result = variant_get(&shredded, options).unwrap();
+            let result_variant = VariantArray::try_new(&result).unwrap();
 
-        assert_eq!(result_variant.inner().null_count(), result_variant.len());
-        let value_field = 
result_variant.inner().field_by_name("value").unwrap();
-        assert!(!value_field.is_nullable());
+            assert_eq!(result_variant.inner().null_count(), 
result_variant.len());
+            let value_field = 
result_variant.inner().field_by_name("value").unwrap();
+            assert!(!value_field.is_nullable());
+        }
     }
 
     fn create_variant_get_as_variant_test_data() -> (ArrayRef, ArrayRef) {

Reply via email to