From 071e3a16b00ae20dfd34025e0ba509a44981b16a Mon Sep 17 00:00:00 2001 From: bc15575202581 Date: Wed, 2 Dec 2026 15:58:17 +0800 Subject: [PATCH 1/3] fix(arrow-cast): preserve null rows when casting size-1 FixedSizeList Signed-off-by: bc15575202581 --- arrow-cast/src/cast/list.rs | 24 ++++++--- arrow-cast/tests/cast/list.rs | 98 +++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 6 deletions(-) diff --git a/arrow-cast/src/cast/list.rs b/arrow-cast/src/cast/list.rs index 0f1ec3f750c5..aba4a2ba6078 100644 --- a/arrow-cast/src/cast/list.rs +++ b/arrow-cast/src/cast/list.rs @@ -4,6 +4,7 @@ use crate::cast::*; use arrow_buffer::ScalarBuffer; +use arrow_select::filter::filter; /// Converts a non-list array to a list array where every element is a single element /// list. `NULL`s in the original array become `[NULL]` (i.e. output list array @@ -55,17 +56,28 @@ pub(crate) fn cast_values_to_list_view( Ok(Arc::new(list)) } -/// Cast fixed size list array to inner values type, essentially flattening the -/// lists. -/// -/// For example: `FixedSizeList([[1, 2], [3, 4]]) -> Int32([1, 2, 3, 4])` +/// Cast a size-one fixed-size list to its child type, preserving null rows. pub(crate) fn cast_single_element_fixed_size_list_to_values( array: &dyn Array, to: &DataType, cast_options: &CastOptions, ) -> Result { - let values = array.as_fixed_size_list().values(); - cast_with_options(values, to, cast_options) + let array = array.as_fixed_size_list(); + let values = array.values(); + let Some(nulls) = array.nulls().filter(|nulls| nulls.null_count() != 0) else { + return cast_with_options(values, to, cast_options); + }; + + // Skip masked child values so a strict cast cannot fail on a null row. + let valid = BooleanArray::new(nulls.inner().clone(), None); + let values = filter(values.as_ref(), &valid)?; + let values = cast_with_options(values.as_ref(), to, cast_options)?; + let mut valid_indices = 0_u64..; + let indices: UInt64Array = nulls + .iter() + .map(|valid| if valid { valid_indices.next() } else { None }) + .collect(); + take(values.as_ref(), &indices, None) } fn cast_fixed_size_list_to_list_inner( diff --git a/arrow-cast/tests/cast/list.rs b/arrow-cast/tests/cast/list.rs index c27c43618b05..2494befe4f40 100644 --- a/arrow-cast/tests/cast/list.rs +++ b/arrow-cast/tests/cast/list.rs @@ -1801,3 +1801,101 @@ fn test_first_last_none() { )) as ArrayRef; assert_eq!(*fixed_array, *r); } + +#[test] +fn test_cast_single_element_fixed_size_list_preserves_nulls() { + let values = StringArray::from(vec![ + Some("skip"), + Some("10"), + Some("99"), + Some("invalid"), + None, + Some("20"), + ]); + let array = FixedSizeListArray::new( + Arc::new(Field::new_list_field(DataType::Utf8, true)), + 1, + Arc::new(values), + Some(NullBuffer::from(vec![true, true, false, false, true, true])), + ) + .slice(1, 5); + + let expected = Int32Array::from(vec![Some(10), None, None, None, Some(20)]); + for safe in [true, false] { + let options = CastOptions { + safe, + ..Default::default() + }; + let casted = cast_with_options(&array, &DataType::Int32, &options).unwrap(); + assert_eq!(casted.as_primitive::(), &expected); + } + + // Same-type unwrap with masked non-null child values under null list rows. + let int_array = FixedSizeListArray::new( + Arc::new(Field::new_list_field(DataType::Int32, false)), + 1, + Arc::new(Int32Array::from(vec![1, 999, 3])), + Some(NullBuffer::from(vec![true, false, true])), + ); + let unwrapped = cast(&int_array, &DataType::Int32).unwrap(); + assert_eq!( + unwrapped.as_primitive::(), + &Int32Array::from(vec![Some(1), None, Some(3)]) + ); + + // All-null single-element fixed-size list. + let all_null = FixedSizeListArray::new( + Arc::new(Field::new_list_field(DataType::Int32, false)), + 1, + Arc::new(Int32Array::from(vec![7, 8])), + Some(NullBuffer::from(vec![false, false])), + ); + let unwrapped_all_null = cast(&all_null, &DataType::Int32).unwrap(); + assert_eq!( + unwrapped_all_null.as_primitive::(), + &Int32Array::from(vec![None, None]) + ); + + // Struct child with a non-nullable field under a null list row. + let struct_fields = arrow_schema::Fields::from(vec![Field::new("x", DataType::Int32, false)]); + let struct_values = arrow_array::StructArray::try_new( + struct_fields.clone(), + vec![Arc::new(Int32Array::from(vec![10, 999])) as ArrayRef], + None, + ) + .unwrap(); + let struct_list = FixedSizeListArray::new( + Arc::new(Field::new_list_field( + DataType::Struct(struct_fields.clone()), + true, + )), + 1, + Arc::new(struct_values), + Some(NullBuffer::from(vec![true, false])), + ); + let casted_struct = cast(&struct_list, &DataType::Struct(struct_fields)).unwrap(); + assert!(casted_struct.is_valid(0)); + assert!(casted_struct.is_null(1)); + assert_eq!( + casted_struct + .as_struct() + .column(0) + .as_primitive::() + .value(0), + 10 + ); + + // Casting through a dictionary target preserves parent nulls as well. + let dict_type = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Int32)); + let casted_dict = cast_with_options( + &array, + &dict_type, + &CastOptions { + safe: false, + ..Default::default() + }, + ) + .unwrap(); + let roundtrip = cast(&casted_dict, &DataType::Int32).unwrap(); + assert_eq!(roundtrip.as_primitive::(), &expected); +} From 8a8d13554555c9e541fa99bf0bb4a67867cef4f7 Mon Sep 17 00:00:00 2001 From: bc15575202581 Date: Thu, 3 Dec 2026 13:06:20 +0800 Subject: [PATCH 2/3] Gate filter on strict casts and union null buffers directly Signed-off-by: bc15575202581 --- arrow-cast/src/cast/list.rs | 47 +++++++++++++++++----- arrow-cast/tests/cast/list.rs | 76 ++++++++++++++++++++++++++--------- 2 files changed, 92 insertions(+), 31 deletions(-) diff --git a/arrow-cast/src/cast/list.rs b/arrow-cast/src/cast/list.rs index aba4a2ba6078..5a88953a6e69 100644 --- a/arrow-cast/src/cast/list.rs +++ b/arrow-cast/src/cast/list.rs @@ -3,7 +3,7 @@ // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements use crate::cast::*; -use arrow_buffer::ScalarBuffer; +use arrow_buffer::{NullBuffer, ScalarBuffer}; use arrow_select::filter::filter; /// Converts a non-list array to a list array where every element is a single element @@ -68,16 +68,41 @@ pub(crate) fn cast_single_element_fixed_size_list_to_values( return cast_with_options(values, to, cast_options); }; - // Skip masked child values so a strict cast cannot fail on a null row. - let valid = BooleanArray::new(nulls.inner().clone(), None); - let values = filter(values.as_ref(), &valid)?; - let values = cast_with_options(values.as_ref(), to, cast_options)?; - let mut valid_indices = 0_u64..; - let indices: UInt64Array = nulls - .iter() - .map(|valid| if valid { valid_indices.next() } else { None }) - .collect(); - take(values.as_ref(), &indices, None) + if !cast_options.safe && values.data_type() != to { + // Skip masked child values so a strict cast cannot fail on a null row. + let valid = BooleanArray::new(nulls.inner().clone(), None); + let values = filter(values.as_ref(), &valid)?; + let values = cast_with_options(values.as_ref(), to, cast_options)?; + let mut valid_indices = 0_u64..; + let indices: UInt64Array = nulls + .iter() + .map(|valid| if valid { valid_indices.next() } else { None }) + .collect(); + return take(values.as_ref(), &indices, None); + } + + let values = cast_with_options(values, to, cast_options)?; + apply_null_mask(values, nulls) +} + +fn apply_null_mask(values: ArrayRef, nulls: &NullBuffer) -> Result { + match values.data_type() { + DataType::Null => Ok(values), + DataType::RunEndEncoded(_, _) | DataType::Union(_, _) => { + let indices: UInt64Array = nulls + .iter() + .enumerate() + .map(|(index, valid)| valid.then_some(index as u64)) + .collect(); + take(values.as_ref(), &indices, None) + } + _ => { + let merged = NullBuffer::union(Some(nulls), values.nulls()); + let data = values.to_data().into_builder().nulls(merged); + // SAFETY: Only adding nulls to a data type whose layout supports a null buffer. + Ok(make_array(unsafe { data.build_unchecked() })) + } + } } fn cast_fixed_size_list_to_list_inner( diff --git a/arrow-cast/tests/cast/list.rs b/arrow-cast/tests/cast/list.rs index 2494befe4f40..fa46187fedb6 100644 --- a/arrow-cast/tests/cast/list.rs +++ b/arrow-cast/tests/cast/list.rs @@ -1830,18 +1830,25 @@ fn test_cast_single_element_fixed_size_list_preserves_nulls() { assert_eq!(casted.as_primitive::(), &expected); } - // Same-type unwrap with masked non-null child values under null list rows. + // Same-type unwrap with masked non-null child values under null list rows (including sliced). let int_array = FixedSizeListArray::new( Arc::new(Field::new_list_field(DataType::Int32, false)), 1, - Arc::new(Int32Array::from(vec![1, 999, 3])), - Some(NullBuffer::from(vec![true, false, true])), - ); - let unwrapped = cast(&int_array, &DataType::Int32).unwrap(); - assert_eq!( - unwrapped.as_primitive::(), - &Int32Array::from(vec![Some(1), None, Some(3)]) - ); + Arc::new(Int32Array::from(vec![0, 1, 999, 3])), + Some(NullBuffer::from(vec![true, true, false, true])), + ) + .slice(1, 3); + for safe in [true, false] { + let options = CastOptions { + safe, + ..Default::default() + }; + let unwrapped = cast_with_options(&int_array, &DataType::Int32, &options).unwrap(); + assert_eq!( + unwrapped.as_primitive::(), + &Int32Array::from(vec![Some(1), None, Some(3)]) + ); + } // All-null single-element fixed-size list. let all_null = FixedSizeListArray::new( @@ -1885,17 +1892,46 @@ fn test_cast_single_element_fixed_size_list_preserves_nulls() { 10 ); - // Casting through a dictionary target preserves parent nulls as well. + // Casting through a dictionary target preserves parent nulls in both safe and strict modes. let dict_type = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Int32)); - let casted_dict = cast_with_options( - &array, - &dict_type, - &CastOptions { - safe: false, + for safe in [true, false] { + let options = CastOptions { + safe, ..Default::default() - }, - ) - .unwrap(); - let roundtrip = cast(&casted_dict, &DataType::Int32).unwrap(); - assert_eq!(roundtrip.as_primitive::(), &expected); + }; + let casted_dict = cast_with_options(&array, &dict_type, &options).unwrap(); + let roundtrip = cast(&casted_dict, &DataType::Int32).unwrap(); + assert_eq!(roundtrip.as_primitive::(), &expected); + } + + // Null child array unwraps cleanly without attaching a null buffer. + let null_list = FixedSizeListArray::new( + Arc::new(Field::new_list_field(DataType::Null, true)), + 1, + Arc::new(arrow_array::NullArray::new(2)), + Some(NullBuffer::from(vec![true, false])), + ); + let unwrapped_null = cast(&null_list, &DataType::Null).unwrap(); + assert_eq!(unwrapped_null.data_type(), &DataType::Null); + assert_eq!(unwrapped_null.len(), 2); + assert!(unwrapped_null.nulls().is_none()); + assert_eq!(unwrapped_null.logical_null_count(), 2); + + // Strict cast still fails when an invalid child value is in a valid row. + let bad_row = FixedSizeListArray::new( + Arc::new(Field::new_list_field(DataType::Utf8, true)), + 1, + Arc::new(StringArray::from(vec![Some("invalid"), Some("20")])), + Some(NullBuffer::from(vec![true, false])), + ); + let strict = CastOptions { + safe: false, + ..Default::default() + }; + assert!(cast_with_options(&bad_row, &DataType::Int32, &strict).is_err()); + let safe_invalid = cast(&bad_row, &DataType::Int32).unwrap(); + assert_eq!( + safe_invalid.as_primitive::(), + &Int32Array::from(vec![None, None]) + ); } From f6c93c2f4e1b73477112af921b795c57bf20bd30 Mon Sep 17 00:00:00 2001 From: bc15575202581 Date: Fri, 4 Dec 2026 04:49:07 +0800 Subject: [PATCH 3/3] Fallback to filter+take when safe cast fails on masked child row Signed-off-by: bc15575202581 --- arrow-cast/src/cast/list.rs | 40 ++++++++++++++------- arrow-cast/tests/cast/list.rs | 68 +++++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+), 12 deletions(-) diff --git a/arrow-cast/src/cast/list.rs b/arrow-cast/src/cast/list.rs index 5a88953a6e69..f0ed23b9290f 100644 --- a/arrow-cast/src/cast/list.rs +++ b/arrow-cast/src/cast/list.rs @@ -69,20 +69,36 @@ pub(crate) fn cast_single_element_fixed_size_list_to_values( }; if !cast_options.safe && values.data_type() != to { - // Skip masked child values so a strict cast cannot fail on a null row. - let valid = BooleanArray::new(nulls.inner().clone(), None); - let values = filter(values.as_ref(), &valid)?; - let values = cast_with_options(values.as_ref(), to, cast_options)?; - let mut valid_indices = 0_u64..; - let indices: UInt64Array = nulls - .iter() - .map(|valid| if valid { valid_indices.next() } else { None }) - .collect(); - return take(values.as_ref(), &indices, None); + return cast_valid_values_and_take(values.as_ref(), nulls, to, cast_options); } - let values = cast_with_options(values, to, cast_options)?; - apply_null_mask(values, nulls) + match cast_with_options(values, to, cast_options) { + Ok(values) => apply_null_mask(values, nulls), + Err(_) if values.data_type() != to => { + // Even in safe mode, casting a masked child row can fail (e.g. a non-nullable + // field inside a masked Struct). Fall back to filtering out null list rows first. + cast_valid_values_and_take(values.as_ref(), nulls, to, cast_options) + } + Err(err) => Err(err), + } +} + +fn cast_valid_values_and_take( + values: &dyn Array, + nulls: &NullBuffer, + to: &DataType, + cast_options: &CastOptions, +) -> Result { + // Skip masked child values so a cast cannot fail on a null list row. + let valid = BooleanArray::new(nulls.inner().clone(), None); + let values = filter(values, &valid)?; + let values = cast_with_options(values.as_ref(), to, cast_options)?; + let mut valid_indices = 0_u64..; + let indices: UInt64Array = nulls + .iter() + .map(|valid| if valid { valid_indices.next() } else { None }) + .collect(); + take(values.as_ref(), &indices, None) } fn apply_null_mask(values: ArrayRef, nulls: &NullBuffer) -> Result { diff --git a/arrow-cast/tests/cast/list.rs b/arrow-cast/tests/cast/list.rs index fa46187fedb6..ed9e1634190f 100644 --- a/arrow-cast/tests/cast/list.rs +++ b/arrow-cast/tests/cast/list.rs @@ -1934,4 +1934,72 @@ fn test_cast_single_element_fixed_size_list_preserves_nulls() { safe_invalid.as_primitive::(), &Int32Array::from(vec![None, None]) ); + + // Safe and strict casts of a masked invalid non-nullable struct child succeed. + let src_fields = arrow_schema::Fields::from(vec![Field::new("number", DataType::Utf8, false)]); + let dst_fields = arrow_schema::Fields::from(vec![Field::new("number", DataType::Int32, false)]); + let src_type = DataType::Struct(src_fields.clone()); + let dst_type = DataType::Struct(dst_fields); + let src_struct = arrow_array::StructArray::try_new( + src_fields.clone(), + vec![Arc::new(StringArray::from(vec!["2", "invalid"])) as ArrayRef], + None, + ) + .unwrap(); + let masked_struct_list = FixedSizeListArray::new( + Arc::new(Field::new_list_field(src_type.clone(), true)), + 1, + Arc::new(src_struct), + Some(NullBuffer::from(vec![true, false])), + ); + for safe in [true, false] { + let options = CastOptions { + safe, + ..Default::default() + }; + let casted = cast_with_options(&masked_struct_list, &dst_type, &options).unwrap(); + assert!(casted.is_valid(0)); + assert!(casted.is_null(1)); + assert_eq!( + casted + .as_struct() + .column(0) + .as_primitive::() + .value(0), + 2 + ); + } + + // All-null masked invalid non-nullable struct child also succeeds. + let all_null_src_struct = arrow_array::StructArray::try_new( + src_fields.clone(), + vec![Arc::new(StringArray::from(vec!["bad1", "bad2"])) as ArrayRef], + None, + ) + .unwrap(); + let all_null_struct_list = FixedSizeListArray::new( + Arc::new(Field::new_list_field(src_type.clone(), true)), + 1, + Arc::new(all_null_src_struct), + Some(NullBuffer::from(vec![false, false])), + ); + let casted_all_null = cast(&all_null_struct_list, &dst_type).unwrap(); + assert_eq!(casted_all_null.len(), 2); + assert!(casted_all_null.is_null(0)); + assert!(casted_all_null.is_null(1)); + + // An invalid non-nullable struct child in a valid row still fails in safe mode. + let invalid_valid_row_struct = arrow_array::StructArray::try_new( + src_fields, + vec![Arc::new(StringArray::from(vec!["invalid", "2"])) as ArrayRef], + None, + ) + .unwrap(); + let invalid_valid_row_list = FixedSizeListArray::new( + Arc::new(Field::new_list_field(src_type, true)), + 1, + Arc::new(invalid_valid_row_struct), + Some(NullBuffer::from(vec![true, false])), + ); + assert!(cast(&invalid_valid_row_list, &dst_type).is_err()); }