This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-11534-bfdcd26caebd331b928d3530097a97315af1442b in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 23ac45ed817d3200e69113473746942f0615ed47 Author: Jeffrey Vo <[email protected]> AuthorDate: Wed Oct 14 05:54:15 2026 +0000 fix: implement `ArrayData::validate_values` for union types (#11534) # Which issue does this PR close? <!-- It is not necessary to raise an issue, but it is encouraged if it is a non-trivial enhancement/bug. If this PR relates to an existing issue, but does not fully resolve it, please change the wording below from "Closes #NNN" to "Relates to #NNN" or "Part of #NNN" to avoid false closing an issue. --> - None # Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. Please try to explain the problem you are trying to solve in terms of the user-visible behavior, rather than the implementation. --> Ensure our validation APIs actually validate, to ensure downstream usages can rely on enforced invariants. # What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> Implement validation logic for union arrays in `ArrayData::validate_values`: - check all type ids are valid (non-negative, associated with a field in `UnionFields`) - dense offsets are within bounds for associated child array # Are these changes tested? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests, if so identify these tests)? If this PR claims a performance improvement, please include evidence such as benchmark results. DO NOT simply paste a list of commands ran to verify the code; this is what our CI is for and it pollutes the PR. ONLY explain if testing was included with this PR, or why it wasn't. --> Added new unit tests # Are there any significant user-facing changes? <!-- Significant user-facing changes include: - Breaking public API change - Significant change to existing functionality (e.g. function returns something different) These need to be explicitly called out to ensure we have proper documentation if required and to ensure we follow proper semantic versioning. DO NOT restate the changes of this PR; if a bug was fixed and already explained above, we don't need this to be restated as a user-facing change. --> No --- arrow-data/src/data.rs | 119 ++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 113 insertions(+), 6 deletions(-) diff --git a/arrow-data/src/data.rs b/arrow-data/src/data.rs index 82dfefcac0..d58bdcf963 100644 --- a/arrow-data/src/data.rs +++ b/arrow-data/src/data.rs @@ -1609,12 +1609,47 @@ impl ArrayData { let child = self.child_at(0)?; self.validate_offsets_full::<i64>(child.len) } - DataType::Union(_, _) => { - // Validate Union Array as part of implementing new Union semantics - // See comments in `ArrayData::validate()` - // https://github.com/apache/arrow-rs/issues/85 - // - // TODO file follow on ticket for full union validation + DataType::Union(fields, mode) => { + let mut child_lens: Vec<Option<usize>> = vec![None; 128]; + for (index, (type_id, _)) in fields.iter().enumerate() { + let child = self.child_at(index)?; + child_lens[type_id as usize] = Some(child.len()); + } + + // Type id values must match one of the fields. + let type_ids = self.typed_buffer::<i8>(0, self.len)?; + for (index, &type_id) in type_ids.iter().enumerate() { + if type_id < 0 { + return Err(ArrowError::InvalidArgumentError(format!( + "Type id values cannot be negative, got {type_id} at index {index}" + ))); + } + let type_id = type_id as usize; + if child_lens[type_id].is_none() { + return Err(ArrowError::InvalidArgumentError(format!( + "Type id values must match one of the field type ids, got {type_id} at index {index}" + ))); + } + } + + // Check the value offsets are in bounds. + if mode == &UnionMode::Dense { + let offsets = self.typed_buffer::<i32>(1, self.len)?; + + if type_ids + .iter() + .zip(offsets.iter()) + .any(|(&type_id, &offset)| { + offset < 0 || offset as usize >= child_lens[type_id as usize].unwrap() + }) + { + return Err(ArrowError::InvalidArgumentError( + "Offsets must be non-negative and within the length of the child array" + .to_string(), + )); + } + } + Ok(()) } DataType::Dictionary(key_type, _value_type) => { @@ -3963,4 +3998,76 @@ mod tests { let data_type = DataType::Union(UnionFields::empty(), UnionMode::Dense); let _ = ArrayData::new_null(&data_type, 1); } + + #[test] + fn test_union_validate_type_ids() { + let dt = DataType::Union( + UnionFields::try_new( + vec![5], + vec![Arc::new(Field::new("a", DataType::Int32, true))], + ) + .unwrap(), + UnionMode::Sparse, + ); + + let child = ArrayData::builder(DataType::Int32) + .len(2) + .add_buffer(make_i32_buffer(2)) + .build() + .unwrap(); + + let err = ArrayDataBuilder::new(dt) + .len(2) + .offset(0) + .buffers(vec![vec![5_i8, 2].into()]) + .child_data(vec![child]) + .build() + .unwrap_err(); + assert_eq!( + err.to_string(), + "Invalid argument error: Type id values must match one of the field type ids, got 2 at index 1" + ); + } + + #[test] + fn test_union_validate_dense_offsets() { + let dt = DataType::Union( + UnionFields::try_new( + vec![5], + vec![Arc::new(Field::new("a", DataType::Int32, true))], + ) + .unwrap(), + UnionMode::Dense, + ); + + let child = ArrayData::builder(DataType::Int32) + .len(2) + .add_buffer(make_i32_buffer(2)) + .build() + .unwrap(); + + let err = ArrayDataBuilder::new(dt.clone()) + .len(2) + // 2nd offset '10' is out of bounds + .buffers(vec![vec![5_i8, 5].into(), vec![0_i32, 10].into()]) + .child_data(vec![child.clone()]) + .build() + .unwrap_err(); + assert_eq!( + err.to_string(), + "Invalid argument error: Offsets must be non-negative and within the length of the child array" + ); + + let err = ArrayDataBuilder::new(dt) + .len(2) + // 2nd offset is negative + .buffers(vec![vec![5_i8, 5].into(), vec![0_i32, -1].into()]) + .child_data(vec![child]) + .build() + .unwrap_err(); + assert_eq!( + err.to_string(), + "Invalid argument error: Offsets must be non-negative and within the length of the child array" + ); + } }
