From c687e0970c9bce6009a34b8b6095899896f83f39 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Thu, 16 Jul 2026 13:42:45 -0400 Subject: [PATCH 01/20] Use PiecewiseSequential indices for FSL take Signed-off-by: Daniel King --- vortex-array/src/arrays/bool/compute/take.rs | 58 ++++ .../src/arrays/decimal/compute/take.rs | 67 ++++ .../arrays/fixed_size_list/compute/take.rs | 326 ++++++++++-------- .../src/arrays/piecewise_sequence/mod.rs | 58 ++++ .../src/arrays/piecewise_sequence/tests.rs | 116 +++++++ .../src/arrays/primitive/compute/take/mod.rs | 59 ++++ .../src/arrays/varbin/compute/take.rs | 178 ++++++++++ .../src/arrays/varbinview/compute/take.rs | 68 ++++ 8 files changed, 786 insertions(+), 144 deletions(-) diff --git a/vortex-array/src/arrays/bool/compute/take.rs b/vortex-array/src/arrays/bool/compute/take.rs index 8469c7e25c2..fe7955fbbae 100644 --- a/vortex-array/src/arrays/bool/compute/take.rs +++ b/vortex-array/src/arrays/bool/compute/take.rs @@ -4,6 +4,7 @@ use itertools::Itertools as _; use num_traits::AsPrimitive; use vortex_buffer::BitBuffer; +use vortex_buffer::BitBufferMut; use vortex_buffer::BitBufferView; use vortex_buffer::get_bit; use vortex_error::VortexResult; @@ -15,12 +16,16 @@ use crate::array::ArrayView; use crate::arrays::Bool; use crate::arrays::BoolArray; use crate::arrays::ConstantArray; +use crate::arrays::PiecewiseSequence; use crate::arrays::PrimitiveArray; use crate::arrays::bool::BoolArrayExt; use crate::arrays::dict::TakeExecute; +use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; +use crate::arrays::piecewise_sequence::validate_index_ranges; use crate::builtins::ArrayBuiltins; use crate::executor::ExecutionCtx; use crate::match_each_integer_ptype; +use crate::match_each_unsigned_integer_ptype; use crate::scalar::Scalar; impl TakeExecute for Bool { @@ -29,6 +34,12 @@ impl TakeExecute for Bool { indices: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { + if let Some(piecewise_indices) = indices.as_opt::() + && let Some(taken) = take_piecewise_sequence(array, piecewise_indices, indices, ctx)? + { + return Ok(Some(taken)); + } + let indices_nulls_zeroed = match indices.validity()?.execute_mask(indices.len(), ctx)? { Mask::AllTrue(_) => indices.clone(), Mask::AllFalse(_) => { @@ -55,6 +66,31 @@ impl TakeExecute for Bool { } } +fn take_piecewise_sequence( + array: ArrayView<'_, Bool>, + indices: ArrayView<'_, PiecewiseSequence>, + indices_ref: &ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { + return Ok(None); + }; + let buffer = match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { + take_piecewise_bits( + &array.to_bit_buffer(), + starts.as_slice::(), + lengths.as_slice::(), + indices_ref.len(), + )? + }) + }); + + Ok(Some( + BoolArray::new(buffer, array.validity()?.take(indices_ref)?).into_array(), + )) +} + fn take_valid_indices>(bools: BitBufferView<'_>, indices: &[I]) -> BitBuffer { // For boolean arrays that roughly fit into a single page (at least, on Linux), it's worth // the overhead to convert to a Vec. @@ -82,6 +118,28 @@ fn take_bool_impl>(bools: BitBufferView<'_>, indices: &[I] }) } +fn take_piecewise_bits( + source: &BitBuffer, + starts: &[S], + lengths: &[L], + output_len: usize, +) -> VortexResult +where + S: crate::dtype::UnsignedPType, + L: crate::dtype::UnsignedPType, +{ + validate_index_ranges(source.len(), starts, lengths, output_len)?; + + let mut values = BitBufferMut::with_capacity(output_len); + for (&start, &length) in starts.iter().zip_eq(lengths) { + let start = start.as_(); + let length = length.as_(); + values.append_buffer(&source.slice(start..start + length)); + } + + Ok(values.freeze()) +} + #[cfg(test)] mod test { use rstest::rstest; diff --git a/vortex-array/src/arrays/decimal/compute/take.rs b/vortex-array/src/arrays/decimal/compute/take.rs index ce786f8e4ab..213d6db39bf 100644 --- a/vortex-array/src/arrays/decimal/compute/take.rs +++ b/vortex-array/src/arrays/decimal/compute/take.rs @@ -1,7 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use itertools::Itertools as _; use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; use vortex_error::VortexResult; use crate::ArrayRef; @@ -9,13 +11,17 @@ use crate::IntoArray; use crate::array::ArrayView; use crate::arrays::Decimal; use crate::arrays::DecimalArray; +use crate::arrays::PiecewiseSequence; use crate::arrays::PrimitiveArray; use crate::arrays::dict::TakeExecute; +use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; +use crate::arrays::piecewise_sequence::validate_index_ranges; use crate::dtype::IntegerPType; use crate::dtype::NativeDecimalType; use crate::executor::ExecutionCtx; use crate::match_each_decimal_value_type; use crate::match_each_integer_ptype; +use crate::match_each_unsigned_integer_ptype; impl TakeExecute for Decimal { fn take( @@ -23,6 +29,12 @@ impl TakeExecute for Decimal { indices: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { + if let Some(piecewise_indices) = indices.as_opt::() + && let Some(taken) = take_piecewise_sequence(array, piecewise_indices, indices, ctx)? + { + return Ok(Some(taken)); + } + let indices = indices.clone().execute::(ctx)?; let validity = array.validity()?.take(&indices.clone().into_array())?; @@ -42,10 +54,65 @@ impl TakeExecute for Decimal { } } +fn take_piecewise_sequence( + array: ArrayView<'_, Decimal>, + indices: ArrayView<'_, PiecewiseSequence>, + indices_ref: &ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { + return Ok(None); + }; + match_each_decimal_value_type!(array.values_type(), |D| { + match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { + let values = take_piecewise_to_buffer::( + starts.as_slice::(), + lengths.as_slice::(), + array.buffer::().as_slice(), + indices_ref.len(), + )?; + let validity = array.validity()?.take(indices_ref)?; + + // SAFETY: contiguous gather preserves the decimal dtype and value representation. + Ok( + Some(unsafe { + DecimalArray::new_unchecked(values, array.decimal_dtype(), validity) + } + .into_array()), + ) + }) + }) + }) +} + fn take_to_buffer(indices: &[I], values: &[T]) -> Buffer { indices.iter().map(|idx| values[idx.as_()]).collect() } +fn take_piecewise_to_buffer( + starts: &[S], + lengths: &[L], + values: &[T], + output_len: usize, +) -> VortexResult> +where + S: crate::dtype::UnsignedPType, + L: crate::dtype::UnsignedPType, + T: NativeDecimalType, +{ + validate_index_ranges(values.len(), starts, lengths, output_len)?; + + let mut result = BufferMut::::with_capacity(output_len); + for (&start, &length) in starts.iter().zip_eq(lengths) { + let start = start.as_(); + let length = length.as_(); + result.extend_from_slice(&values[start..start + length]); + } + + Ok(result.freeze()) +} + #[cfg(test)] mod tests { use rstest::rstest; diff --git a/vortex-array/src/arrays/fixed_size_list/compute/take.rs b/vortex-array/src/arrays/fixed_size_list/compute/take.rs index 193730f62c4..b2533d132b9 100644 --- a/vortex-array/src/arrays/fixed_size_list/compute/take.rs +++ b/vortex-array/src/arrays/fixed_size_list/compute/take.rs @@ -1,221 +1,259 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use vortex_buffer::BitBufferMut; +use itertools::Itertools; +use vortex_buffer::Buffer; use vortex_buffer::BufferMut; -use vortex_error::VortexExpect; use vortex_error::VortexResult; -use vortex_error::vortex_panic; -use vortex_mask::Mask; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; use crate::ArrayRef; use crate::IntoArray; use crate::array::ArrayView; -use crate::arrays::BoolArray; +use crate::arrays::ConstantArray; use crate::arrays::FixedSizeList; use crate::arrays::FixedSizeListArray; +use crate::arrays::PiecewiseSequenceArray; use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; -use crate::arrays::bool::BoolArrayExt; use crate::arrays::dict::TakeExecute; use crate::arrays::fixed_size_list::FixedSizeListArrayExt; use crate::arrays::primitive::PrimitiveArrayExt; +use crate::builders::builder_with_capacity; +use crate::dtype::DType; use crate::dtype::IntegerPType; +use crate::dtype::Nullability; use crate::executor::ExecutionCtx; -use crate::match_each_unsigned_integer_ptype; -use crate::match_smallest_offset_type; +use crate::match_each_integer_ptype; use crate::validity::Validity; /// Take implementation for [`FixedSizeListArray`]. /// -/// Unlike `ListView`, `FixedSizeListArray` must rebuild the elements array because it requires -/// that elements start at offset 0 and be perfectly packed without gaps. We expand list indices -/// into element indices and push them down to the child elements array. +/// `FixedSizeListArray` must rebuild its elements array because selected lists need to become +/// packed from offset 0. The FSL layer translates selected list rows into ordered element runs and +/// delegates the execution strategy to the elements child via `PiecewiseSequenceArray` indices. impl TakeExecute for FixedSizeList { fn take( array: ArrayView<'_, FixedSizeList>, indices: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { - let max_element_idx = array.elements().len(); - // Indices are non-negative; dispatch over the 4 unsigned widths (the executed array is - // reinterpreted to unsigned in `take_with_indices`). `E` is already unsigned. - match_each_unsigned_integer_ptype!(indices.dtype().as_ptype().to_unsigned(), |I| { - match_smallest_offset_type!(max_element_idx, |E| { - take_with_indices::(array, indices, ctx) - }) - }) - .map(Some) + if array.is_empty() { + return take_empty_fsl(array, indices, ctx).map(Some); + } + + take_non_empty_fsl(array, indices, ctx).map(Some) } } -/// Dispatches to the appropriate take implementation based on list size and nullability. -fn take_with_indices( +fn take_empty_fsl( array: ArrayView<'_, FixedSizeList>, indices: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult { - let list_size = array.list_size() as usize; + debug_assert!(array.is_empty()); - let indices_array = indices.clone().execute::(ctx)?; - // Reinterpret to unsigned so `as_slice::` (with unsigned `I`) matches; values are unchanged. - let indices_array = indices_array.reinterpret_cast(indices_array.ptype().to_unsigned()); - - // Make sure to handle degenerate case where lists have size 0 (these can take fast paths). - if list_size == 0 { - debug_assert!( - array.elements().is_empty(), - "degenerate list must have empty elements" + let new_len = indices.len(); + if new_len != 0 { + let indices_validity = indices.validity()?.execute_mask(new_len, ctx)?; + vortex_ensure!( + indices_validity.all_false(), + "cannot take valid indices from an empty FixedSizeList" ); + } - // Since there are no elements to take, we just need to take on the validity map. - let new_validity = array.validity()?.take(indices)?; - let new_len = indices_array.len(); - - Ok( - // SAFETY: list_size is 0, elements array is empty, and validity has the correct length. - unsafe { - FixedSizeListArray::new_unchecked( - array.elements().clone(), // Remember that this is an empty array. - array.list_size(), - new_validity, - new_len, - ) - } - .into_array(), + let list_size = array.list_size() as usize; + let elements_len = new_len.checked_mul(list_size).ok_or_else(|| { + vortex_err!( + "FixedSizeList take output length overflow: {new_len} lists of size {list_size}" ) + })?; + let new_elements = default_elements(array, elements_len); + let new_validity = if new_len == 0 { + array.validity()?.take(indices)? } else { - // The result's nullability is the union of the input nullabilities. - if array.dtype().is_nullable() || indices_array.dtype().is_nullable() { - let indices_array = indices_array.as_view(); - take_nullable_fsl::(array, indices_array, ctx) - } else { - let indices_array = indices_array.as_view(); - take_non_nullable_fsl::(array, indices_array) - } + Validity::AllInvalid + }; + + // SAFETY: empty output needs no child values; otherwise the index validity mask proves every + // output row is null. Placeholder child elements have the exact length required by FSL. + Ok(unsafe { + FixedSizeListArray::new_unchecked(new_elements, array.list_size(), new_validity, new_len) } + .into_array()) } -/// Takes from an array when both the array and indices are non-nullable. -fn take_non_nullable_fsl( +fn take_non_empty_fsl( array: ArrayView<'_, FixedSizeList>, - indices_array: ArrayView<'_, Primitive>, + indices: &ArrayRef, + ctx: &mut ExecutionCtx, ) -> VortexResult { - let list_size = array.list_size() as usize; - let indices: &[I] = indices_array.as_slice::(); - let new_len = indices.len(); - - // Build the element indices directly without validity tracking. - let mut elements_indices = BufferMut::::with_capacity(new_len * list_size); - - // Build the element indices for each list. - for data_idx in indices { - let data_idx = data_idx - .to_usize() - .unwrap_or_else(|| vortex_panic!("Failed to convert index to usize: {}", data_idx)); + debug_assert!(!array.is_empty()); - let list_start = data_idx * list_size; - let list_end = (data_idx + 1) * list_size; + let DType::Primitive(ptype, nullability) = indices.dtype() else { + vortex_bail!("Invalid indices dtype: {}", indices.dtype()) + }; + if !ptype.is_int() { + vortex_bail!("Invalid indices dtype: {}", indices.dtype()); + } - // Expand the list into individual element indices. - for i in list_start..list_end { - // SAFETY: We've allocated enough space for enough indices for all `new_len` lists (that each consist of `list_size = list_end - list_start` elements), so we know we have enough capacity. - unsafe { - elements_indices.push_unchecked(E::from_usize(i).vortex_expect("i < list_end")) - }; - } + if array.list_size() == 0 { + return take_non_empty_degenerate_fsl(array, indices, ctx); } - let elements_indices = elements_indices.freeze(); - debug_assert_eq!(elements_indices.len(), new_len * list_size); + let indices_array = indices.clone().execute::(ctx)?; + match_each_integer_ptype!(indices_array.ptype(), |I| { + take_non_empty_non_degenerate_fsl::( + array, + indices, + indices_array.as_view(), + *nullability, + ctx, + ) + }) +} + +fn take_non_empty_degenerate_fsl( + array: ArrayView<'_, FixedSizeList>, + indices: &ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult { + debug_assert!(!array.is_empty()); + debug_assert_eq!(array.list_size(), 0); + vortex_ensure!( + array.elements().is_empty(), + "degenerate list must have empty elements" + ); - let elements_indices_array = PrimitiveArray::new(elements_indices, Validity::NonNullable); - let new_elements = array.elements().take(elements_indices_array.into_array())?; - debug_assert_eq!(new_elements.len(), new_len * list_size); + let indices_array = indices.clone().execute::(ctx)?; + match_each_integer_ptype!(indices_array.ptype(), |I| { + bounds_check_valid_indices::(&indices_array.as_view(), array.as_ref().len(), ctx) + })?; + let new_validity = array.validity()?.take(indices)?; + let new_len = indices_array.len(); - // Both inputs are non-nullable, so the result is non-nullable. + // SAFETY: degenerate FSL inputs have no elements, valid index payloads were checked against + // the source length, and `Validity::take` produces validity for `new_len`. Ok(unsafe { FixedSizeListArray::new_unchecked( - new_elements, + array.elements().clone(), array.list_size(), - Validity::NonNullable, + new_validity, new_len, ) } .into_array()) } -/// Takes from an array when either the array or indices are nullable. -fn take_nullable_fsl( +fn take_non_empty_non_degenerate_fsl( array: ArrayView<'_, FixedSizeList>, + indices: &ArrayRef, indices_array: ArrayView<'_, Primitive>, + indices_nullability: Nullability, ctx: &mut ExecutionCtx, ) -> VortexResult { + debug_assert!(!array.is_empty()); + debug_assert_ne!(array.list_size(), 0); + + let (new_elements, new_len) = + take_non_empty_non_degenerate_elements::(array, indices_array, ctx)?; + let new_validity = if array.dtype().is_nullable() || indices_nullability.is_nullable() { + array.validity()?.take(indices)? + } else { + Validity::NonNullable + }; + + // SAFETY: `new_elements` has `new_len * list_size` elements. `new_validity` is either + // non-nullable or was produced by `Validity::take` for `new_len`. + Ok(unsafe { + FixedSizeListArray::new_unchecked(new_elements, array.list_size(), new_validity, new_len) + } + .into_array()) +} + +fn take_non_empty_non_degenerate_elements( + array: ArrayView<'_, FixedSizeList>, + indices_array: ArrayView<'_, Primitive>, + ctx: &mut ExecutionCtx, +) -> VortexResult<(ArrayRef, usize)> { + debug_assert!(!array.is_empty()); + debug_assert_ne!(array.list_size(), 0); + let list_size = array.list_size() as usize; + let array_len = array.as_ref().len(); let indices: &[I] = indices_array.as_slice::(); let new_len = indices.len(); + let elements_len = new_len.checked_mul(list_size).ok_or_else(|| { + vortex_err!( + "FixedSizeList take output length overflow: {new_len} lists of size {list_size}" + ) + })?; - let array_validity = array - .fixed_size_list_validity() - .execute_mask(array.as_ref().len(), ctx) - .vortex_expect("Failed to compute validity mask"); - let indices_len = indices_array.as_ref().len(); - let indices_validity = match indices_array - .validity() - .vortex_expect("Failed to compute validity mask") - { - Validity::NonNullable | Validity::AllValid => Mask::new_true(indices_len), - Validity::AllInvalid => Mask::new_false(indices_len), - Validity::Array(a) => a.execute::(ctx)?.execute_mask(ctx), - }; + let indices_validity = indices_array.validity()?.execute_mask(new_len, ctx)?; + let starts = indices + .iter() + .zip_eq(indices_validity.iter()) + .map(|(&data_idx, is_index_valid)| { + if !is_index_valid { + return Ok(0); + } - // We must use placeholder zeros for null lists to maintain the array length without - // propagating nullability to the element array's take operation. - let mut elements_indices = BufferMut::::with_capacity(new_len * list_size); - let mut new_validity_builder = BitBufferMut::with_capacity(new_len); - - // Build the element indices while tracking which lists are null. - for (data_idx, is_index_valid) in indices.iter().zip(indices_validity.iter()) { - let data_idx = data_idx - .to_usize() - .unwrap_or_else(|| vortex_panic!("Failed to convert index to usize: {}", data_idx)); - - // The list is null if the index is null or the indexed element is null. - if !is_index_valid || !array_validity.value(data_idx) { - // Append placeholder zeros for null lists. These will be masked by the validity array. - // We cannot use append_nulls here as explained above. - unsafe { elements_indices.push_n_unchecked(E::zero(), list_size) }; - new_validity_builder.append(false); - } else { - // Append the actual element indices for this list. - let list_start = data_idx * list_size; - let list_end = (data_idx + 1) * list_size; - - // Expand the list into individual element indices. - for i in list_start..list_end { - // SAFETY: We've allocated enough space for enough indices for all `new_len` lists (that each consist of `list_size = list_end - list_start` elements), so we know we have enough capacity. - unsafe { - elements_indices.push_unchecked(E::from_usize(i).vortex_expect("i < list_end")) - }; + let data_idx: usize = data_idx.as_(); + if data_idx >= array_len { + vortex_bail!(OutOfBounds: data_idx, 0, array_len); } + Ok((data_idx * list_size) as u64) + }) + .process_results(|iter| iter.collect::>())?; + + let new_elements = + take_element_runs(array.elements(), starts.freeze(), list_size, elements_len)?; + + Ok((new_elements, new_len)) +} - new_validity_builder.append(true); +fn bounds_check_valid_indices( + indices_array: &ArrayView<'_, Primitive>, + array_len: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult<()> { + let indices: &[I] = indices_array.as_slice::(); + let indices_validity = indices_array.validity()?.execute_mask(indices.len(), ctx)?; + + for (&data_idx, is_index_valid) in indices.iter().zip_eq(indices_validity.iter()) { + if is_index_valid { + let data_idx = data_idx.as_(); + if data_idx >= array_len { + vortex_bail!(OutOfBounds: data_idx, 0, array_len); + } } } + Ok(()) +} - let elements_indices = elements_indices.freeze(); - debug_assert_eq!(elements_indices.len(), new_len * list_size); - - let elements_indices_array = PrimitiveArray::new(elements_indices, Validity::NonNullable); - let new_elements = array.elements().take(elements_indices_array.into_array())?; - debug_assert_eq!(new_elements.len(), new_len * list_size); +fn default_elements(array: ArrayView<'_, FixedSizeList>, len: usize) -> ArrayRef { + let mut builder = builder_with_capacity(array.elements().dtype(), len); + builder.append_defaults(len); + builder.finish() +} - // At least one input was nullable, so the result is nullable. - let new_validity = Validity::from(new_validity_builder.freeze()); - debug_assert!(new_validity.maybe_len().is_none_or(|vl| vl == new_len)); +fn take_element_runs( + elements: &ArrayRef, + starts: Buffer, + length: usize, + output_len: usize, +) -> VortexResult { + let run_count = starts.len(); + let starts = PrimitiveArray::new(starts, Validity::NonNullable).into_array(); + let lengths = ConstantArray::new(length as u64, run_count).into_array(); + let multipliers = ConstantArray::new(1u64, run_count).into_array(); - Ok(unsafe { - FixedSizeListArray::new_unchecked(new_elements, array.list_size(), new_validity, new_len) - } - .into_array()) + // SAFETY: callers produced one start per output row after validating list indices against the + // source FSL length. `length` and multiplier 1 are represented as non-nullable unsigned + // constant arrays, and `output_len` was computed as `run_count * length`. + let indices = + unsafe { PiecewiseSequenceArray::new_unchecked(starts, lengths, multipliers, output_len) }; + elements.take(indices.into_array()) } diff --git a/vortex-array/src/arrays/piecewise_sequence/mod.rs b/vortex-array/src/arrays/piecewise_sequence/mod.rs index b914c5e9651..a5361567c7d 100644 --- a/vortex-array/src/arrays/piecewise_sequence/mod.rs +++ b/vortex-array/src/arrays/piecewise_sequence/mod.rs @@ -21,6 +21,7 @@ use crate::arrays::PrimitiveArray; use crate::arrays::piecewise_sequence::array::PiecewiseSequenceArraySlotsExt; use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; +use crate::scalar::PValue; pub mod array; mod vtable; @@ -65,6 +66,30 @@ pub(crate) fn execute_index_arrays( Ok((starts, lengths, multipliers)) } +pub(crate) fn execute_unit_multiplier_index_arrays( + array: ArrayView<'_, PiecewiseSequence>, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + if !is_constant_multiplier_one(array.multipliers()) { + return Ok(None); + } + + let starts = array.starts().clone().execute::(ctx)?; + let lengths = array.lengths().clone().execute::(ctx)?; + check_index_arrays(starts.as_ref(), lengths.as_ref(), array.multipliers())?; + Ok(Some((starts, lengths))) +} + +pub(crate) fn is_constant_multiplier_one(multipliers: &ArrayRef) -> bool { + let Some(scalar) = multipliers.as_constant() else { + return false; + }; + matches!( + scalar.as_primitive_opt().and_then(|scalar| scalar.pvalue()), + Some(PValue::U8(1) | PValue::U16(1) | PValue::U32(1) | PValue::U64(1)) + ) +} + fn check_index_array(name: &str, array: &ArrayRef) -> VortexResult<()> { vortex_ensure!( array.dtype().is_unsigned_int(), @@ -123,3 +148,36 @@ where } Ok(values) } + +pub(crate) fn validate_index_ranges( + source_len: usize, + starts: &[S], + lengths: &[L], + output_len: usize, +) -> VortexResult<()> +where + S: UnsignedPType, + L: UnsignedPType, +{ + let mut computed_len = 0usize; + for (&start, &length) in starts.iter().zip_eq(lengths) { + let start: usize = start.as_(); + let length: usize = length.as_(); + let end = start.checked_add(length).ok_or_else(|| { + vortex_err!("PiecewiseSequenceArray range overflows usize") + })?; + vortex_ensure!( + end <= source_len, + "PiecewiseSequenceArray range {start}..{end} exceeds source length {source_len}" + ); + computed_len = computed_len.checked_add(length).ok_or_else(|| { + vortex_err!("PiecewiseSequenceArray output length overflows usize") + })?; + } + + vortex_ensure!( + computed_len == output_len, + "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + ); + Ok(()) +} diff --git a/vortex-array/src/arrays/piecewise_sequence/tests.rs b/vortex-array/src/arrays/piecewise_sequence/tests.rs index ab201943e3d..1abbada7a92 100644 --- a/vortex-array/src/arrays/piecewise_sequence/tests.rs +++ b/vortex-array/src/arrays/piecewise_sequence/tests.rs @@ -7,16 +7,37 @@ use vortex_error::VortexResult; use vortex_session::registry::ReadContext; use crate::ArrayContext; +use crate::ArrayRef; use crate::IntoArray; use crate::VortexSessionExecute; use crate::array_session; +use crate::arrays::BoolArray; use crate::arrays::ConstantArray; +use crate::arrays::DecimalArray; +use crate::arrays::FixedSizeListArray; use crate::arrays::PiecewiseSequence; use crate::arrays::PiecewiseSequenceArray; use crate::arrays::PrimitiveArray; +use crate::arrays::VarBinArray; +use crate::arrays::VarBinViewArray; use crate::assert_arrays_eq; +use crate::dtype::DType; +use crate::dtype::DecimalDType; +use crate::dtype::Nullability; use crate::serde::SerializeOptions; use crate::serde::SerializedArray; +use crate::validity::Validity; + +fn piecewise_indices( + starts: impl IntoIterator, + lengths: &[u64], +) -> VortexResult { + let len = lengths.iter().map(|&length| length as usize).sum(); + let starts = PrimitiveArray::from_iter(starts).into_array(); + let lengths = PrimitiveArray::from_iter(lengths.iter().copied()).into_array(); + let multipliers = ConstantArray::new(1u64, lengths.len()).into_array(); + Ok(PiecewiseSequenceArray::try_new(starts, lengths, multipliers, len)?.into_array()) +} #[test] fn materializes_piecewise_indices() -> VortexResult<()> { @@ -152,3 +173,98 @@ fn serde_roundtrip_preserves_piecewise_indices() -> VortexResult<()> { ); Ok(()) } + +#[test] +fn primitive_take_consumes_piecewise_indices() -> VortexResult<()> { + let values = PrimitiveArray::from_iter(0i32..20).into_array(); + let taken = values.take(piecewise_indices([3, 10], &[2, 3])?)?; + + assert_arrays_eq!( + taken, + PrimitiveArray::from_iter([3i32, 4, 10, 11, 12]).into_array(), + &mut array_session().create_execution_ctx() + ); + Ok(()) +} + +#[test] +fn bool_take_consumes_piecewise_indices() -> VortexResult<()> { + let values = BoolArray::from_iter([true, false, true, true, false, false]).into_array(); + let taken = values.take(piecewise_indices([1, 4], &[2, 2])?)?; + + assert_arrays_eq!( + taken, + BoolArray::from_iter([false, true, false, false]).into_array(), + &mut array_session().create_execution_ctx() + ); + Ok(()) +} + +#[test] +fn decimal_take_consumes_piecewise_indices() -> VortexResult<()> { + let decimal_dtype = DecimalDType::new(19, 2); + let values = DecimalArray::from_iter([10i128, 20, 30, 40, 50, 60], decimal_dtype).into_array(); + let taken = values.take(piecewise_indices([1, 4], &[2, 1])?)?; + + assert_arrays_eq!( + taken, + DecimalArray::from_iter([20i128, 30, 50], decimal_dtype).into_array(), + &mut array_session().create_execution_ctx() + ); + Ok(()) +} + +#[test] +fn varbinview_take_consumes_piecewise_indices() -> VortexResult<()> { + let values = VarBinViewArray::from_iter( + ["a", "bb", "ccc", "dddd", "eeeee"].map(Some), + DType::Utf8(Nullability::NonNullable), + ) + .into_array(); + let taken = values.take(piecewise_indices([1, 3], &[2, 1])?)?; + + assert_arrays_eq!( + taken, + VarBinViewArray::from_iter( + ["bb", "ccc", "dddd"].map(Some), + DType::Utf8(Nullability::NonNullable) + ) + .into_array(), + &mut array_session().create_execution_ctx() + ); + Ok(()) +} + +#[test] +fn varbin_take_consumes_piecewise_indices() -> VortexResult<()> { + let values = VarBinArray::from_iter( + ["a", "bb", "ccc", "dddd", "eeeee"].map(Some), + DType::Utf8(Nullability::NonNullable), + ) + .into_array(); + let taken = values.take(piecewise_indices([1, 3], &[2, 1])?)?; + + assert_arrays_eq!( + taken, + VarBinArray::from_iter( + ["bb", "ccc", "dddd"].map(Some), + DType::Utf8(Nullability::NonNullable) + ) + .into_array(), + &mut array_session().create_execution_ctx() + ); + Ok(()) +} + +#[test] +fn fixed_size_list_take_builds_piecewise_element_indices() -> VortexResult<()> { + let elements = PrimitiveArray::from_iter(0i32..12).into_array(); + let array = FixedSizeListArray::new(elements, 3, Validity::NonNullable, 4).into_array(); + let taken = array.take(buffer![1u64, 3].into_array())?; + + let expected_elements = PrimitiveArray::from_iter([3i32, 4, 5, 9, 10, 11]).into_array(); + let expected = + FixedSizeListArray::new(expected_elements, 3, Validity::NonNullable, 2).into_array(); + assert_arrays_eq!(taken, expected, &mut array_session().create_execution_ctx()); + Ok(()) +} diff --git a/vortex-array/src/arrays/primitive/compute/take/mod.rs b/vortex-array/src/arrays/primitive/compute/take/mod.rs index dd562281608..a7b316a4c9b 100644 --- a/vortex-array/src/arrays/primitive/compute/take/mod.rs +++ b/vortex-array/src/arrays/primitive/compute/take/mod.rs @@ -6,6 +6,7 @@ mod avx2; use std::sync::LazyLock; +use itertools::Itertools as _; use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_error::VortexResult; @@ -16,15 +17,19 @@ use crate::ArrayRef; use crate::IntoArray; use crate::array::ArrayView; use crate::arrays::ConstantArray; +use crate::arrays::PiecewiseSequence; use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; use crate::arrays::dict::TakeExecute; +use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; +use crate::arrays::piecewise_sequence::validate_index_ranges; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::IntegerPType; use crate::executor::ExecutionCtx; use crate::match_each_integer_ptype; use crate::match_each_native_ptype; +use crate::match_each_unsigned_integer_ptype; use crate::scalar::Scalar; use crate::validity::Validity; @@ -79,6 +84,12 @@ impl TakeExecute for Primitive { indices: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { + if let Some(piecewise_indices) = indices.as_opt::() + && let Some(taken) = take_piecewise_sequence(array, piecewise_indices, indices, ctx)? + { + return Ok(Some(taken)); + } + let DType::Primitive(ptype, null) = indices.dtype() else { vortex_bail!("Invalid indices dtype: {}", indices.dtype()) }; @@ -123,6 +134,31 @@ impl TakeExecute for Primitive { } } +fn take_piecewise_sequence( + array: ArrayView<'_, Primitive>, + indices: ArrayView<'_, PiecewiseSequence>, + indices_ref: &ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { + return Ok(None); + }; + match_each_native_ptype!(array.ptype(), |T| { + match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { + let values = primitive_piecewise_values::( + array.as_slice::(), + starts.as_slice::(), + lengths.as_slice::(), + indices_ref.len(), + )?; + let validity = array.validity()?.take(indices_ref)?; + Ok(Some(PrimitiveArray::new(values, validity).into_array())) + }) + }) + }) +} + // Compiler may see this as unused based on enabled features #[inline(always)] fn take_primitive_scalar(buffer: &[T], indices: &[I]) -> Buffer { @@ -144,6 +180,29 @@ fn take_primitive_scalar(buffer: &[T], indices: &[I]) result.freeze() } +fn primitive_piecewise_values( + source: &[T], + starts: &[S], + lengths: &[L], + output_len: usize, +) -> VortexResult> +where + T: Copy, + S: crate::dtype::UnsignedPType, + L: crate::dtype::UnsignedPType, +{ + validate_index_ranges(source.len(), starts, lengths, output_len)?; + + let mut values = BufferMut::::with_capacity(output_len); + for (&start, &length) in starts.iter().zip_eq(lengths) { + let start = start.as_(); + let length = length.as_(); + values.extend_from_slice(&source[start..start + length]); + } + + Ok(values.freeze()) +} + #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] #[cfg(test)] mod test { diff --git a/vortex-array/src/arrays/varbin/compute/take.rs b/vortex-array/src/arrays/varbin/compute/take.rs index 6a6454d0603..f3c31bc9f1c 100644 --- a/vortex-array/src/arrays/varbin/compute/take.rs +++ b/vortex-array/src/arrays/varbin/compute/take.rs @@ -1,21 +1,27 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use itertools::Itertools as _; use vortex_buffer::BitBufferMut; use vortex_buffer::BufferMut; use vortex_buffer::ByteBufferMut; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; use vortex_error::vortex_panic; use vortex_mask::Mask; use crate::ArrayRef; use crate::IntoArray; use crate::array::ArrayView; +use crate::arrays::PiecewiseSequence; use crate::arrays::PrimitiveArray; use crate::arrays::VarBin; use crate::arrays::VarBinArray; use crate::arrays::dict::TakeExecute; +use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; +use crate::arrays::piecewise_sequence::validate_index_ranges; use crate::arrays::primitive::PrimitiveArrayExt; use crate::arrays::varbin::VarBinArrayExt; use crate::dtype::DType; @@ -43,6 +49,12 @@ impl TakeExecute for VarBin { indices: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { + if let Some(piecewise_indices) = indices.as_opt::() + && let Some(taken) = take_piecewise_sequence(array, piecewise_indices, indices, ctx)? + { + return Ok(Some(taken)); + } + // TODO(joe): Be lazy with execute let offsets = array.offsets().clone().execute::(ctx)?; let data = array.bytes(); @@ -113,6 +125,80 @@ impl TakeExecute for VarBin { } } +fn take_piecewise_sequence( + array: ArrayView<'_, VarBin>, + indices: ArrayView<'_, PiecewiseSequence>, + indices_ref: &ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { + return Ok(None); + }; + let offsets = array.offsets().clone().execute::(ctx)?; + let out_offset_ptype = taken_offset_ptype(offsets.ptype()); + let offsets = offsets.reinterpret_cast(offsets.ptype().to_unsigned()); + + let result = match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { + match offsets.ptype() { + PType::U8 => gather_piecewise_varbin::( + array.dtype().clone(), + offsets.as_slice::(), + array.bytes().as_slice(), + starts.as_slice::(), + lengths.as_slice::(), + indices_ref.len(), + out_offset_ptype, + ), + PType::U16 => gather_piecewise_varbin::( + array.dtype().clone(), + offsets.as_slice::(), + array.bytes().as_slice(), + starts.as_slice::(), + lengths.as_slice::(), + indices_ref.len(), + out_offset_ptype, + ), + PType::U32 => gather_piecewise_varbin::( + array.dtype().clone(), + offsets.as_slice::(), + array.bytes().as_slice(), + starts.as_slice::(), + lengths.as_slice::(), + indices_ref.len(), + out_offset_ptype, + ), + PType::U64 => gather_piecewise_varbin::( + array.dtype().clone(), + offsets.as_slice::(), + array.bytes().as_slice(), + starts.as_slice::(), + lengths.as_slice::(), + indices_ref.len(), + out_offset_ptype, + ), + _ => unreachable!("offsets were reinterpreted to an unsigned integer ptype"), + } + }) + })?; + + let validity = array.validity()?.take(indices_ref)?; + + // SAFETY: output offsets are built from valid input offsets, start at zero, are monotonically + // non-decreasing, and the copied data buffer has exactly the referenced byte length. + unsafe { + Ok(Some( + VarBinArray::new_unchecked( + result.offsets, + result.data.freeze(), + result.dtype, + validity, + ) + .into_array(), + )) + } +} + fn take( dtype: DType, offsets: &[Offset], @@ -183,6 +269,98 @@ fn take( } } +struct GatheredPiecewiseVarBin { + dtype: DType, + offsets: ArrayRef, + data: ByteBufferMut, +} + +fn gather_piecewise_varbin( + dtype: DType, + offsets: &[Offset], + data: &[u8], + starts: &[S], + lengths: &[L], + output_len: usize, + out_offset_ptype: PType, +) -> VortexResult +where + S: crate::dtype::UnsignedPType, + L: crate::dtype::UnsignedPType, + Offset: IntegerPType, + NewOffset: IntegerPType, +{ + validate_index_ranges(offsets.len() - 1, starts, lengths, output_len)?; + + let mut new_offsets = BufferMut::::with_capacity(output_len + 1); + new_offsets.push(NewOffset::zero()); + let mut output_bytes = 0usize; + + for (&start, &length) in starts.iter().zip_eq(lengths) { + let start = start.as_(); + let length = length.as_(); + let end = start + length; + if length == 0 { + continue; + } + + let byte_start = offsets[start].as_(); + let byte_end = offsets[end].as_(); + vortex_ensure!( + byte_start <= byte_end && byte_end <= data.len(), + "VarBin offsets range {byte_start}..{byte_end} exceeds data length {}", + data.len() + ); + + for &offset in &offsets[start + 1..=end] { + let offset = offset.as_(); + let relative = offset.checked_sub(byte_start).ok_or_else(|| { + vortex_err!("VarBin offsets are not monotonic at offset {offset}") + })?; + let output_offset = output_bytes.checked_add(relative).ok_or_else(|| { + vortex_err!("PiecewiseSequence VarBin output byte length overflow") + })?; + new_offsets.push(new_offset_value::(output_offset)?); + } + + output_bytes = output_bytes + .checked_add(byte_end - byte_start) + .ok_or_else(|| vortex_err!("PiecewiseSequence VarBin output byte length overflow"))?; + } + + let mut new_data = ByteBufferMut::with_capacity(output_bytes); + for (&start, &length) in starts.iter().zip_eq(lengths) { + let start = start.as_(); + let length = length.as_(); + let end = start + length; + if length == 0 { + continue; + } + + let byte_start = offsets[start].as_(); + let byte_end = offsets[end].as_(); + new_data.extend_from_slice(&data[byte_start..byte_end]); + } + + let offsets = PrimitiveArray::new(new_offsets.freeze(), Validity::NonNullable) + .reinterpret_cast(out_offset_ptype) + .into_array(); + Ok(GatheredPiecewiseVarBin { + dtype, + offsets, + data: new_data, + }) +} + +fn new_offset_value(value: usize) -> VortexResult { + T::from(value).ok_or_else(|| { + vortex_err!( + "PiecewiseSequence VarBin offset value {value} does not fit in {}", + T::PTYPE + ) + }) +} + fn take_nullable( dtype: DType, offsets: &[Offset], diff --git a/vortex-array/src/arrays/varbinview/compute/take.rs b/vortex-array/src/arrays/varbinview/compute/take.rs index ce10abda3d0..89206a17c9f 100644 --- a/vortex-array/src/arrays/varbinview/compute/take.rs +++ b/vortex-array/src/arrays/varbinview/compute/take.rs @@ -4,8 +4,10 @@ use std::iter; use std::sync::Arc; +use itertools::Itertools as _; use num_traits::AsPrimitive; use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; use vortex_error::VortexResult; use vortex_mask::AllOr; use vortex_mask::Mask; @@ -13,14 +15,18 @@ use vortex_mask::Mask; use crate::ArrayRef; use crate::IntoArray; use crate::array::ArrayView; +use crate::arrays::PiecewiseSequence; use crate::arrays::PrimitiveArray; use crate::arrays::VarBinView; use crate::arrays::VarBinViewArray; use crate::arrays::dict::TakeExecute; +use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; +use crate::arrays::piecewise_sequence::validate_index_ranges; use crate::arrays::varbinview::BinaryView; use crate::buffer::BufferHandle; use crate::executor::ExecutionCtx; use crate::match_each_integer_ptype; +use crate::match_each_unsigned_integer_ptype; impl TakeExecute for VarBinView { /// Take involves creating a new array that references the old array, just with the given set of views. @@ -29,6 +35,12 @@ impl TakeExecute for VarBinView { indices: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { + if let Some(piecewise_indices) = indices.as_opt::() + && let Some(taken) = take_piecewise_sequence(array, piecewise_indices, indices, ctx)? + { + return Ok(Some(taken)); + } + let validity = array.validity()?.take(indices)?; let indices = indices.clone().execute::(ctx)?; @@ -57,6 +69,40 @@ impl TakeExecute for VarBinView { } } +fn take_piecewise_sequence( + array: ArrayView<'_, VarBinView>, + indices: ArrayView<'_, PiecewiseSequence>, + indices_ref: &ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { + return Ok(None); + }; + let views = match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { + gather_piecewise_views( + array.views(), + starts.as_slice::(), + lengths.as_slice::(), + indices_ref.len(), + )? + }) + }); + let validity = array.validity()?.take(indices_ref)?; + + // SAFETY: ranges were validated against the source views, and copied views still reference the + // same backing data buffers. + unsafe { + Ok(Some(VarBinViewArray::new_handle_unchecked( + BufferHandle::new_host(views.into_byte_buffer()), + Arc::clone(array.data_buffers()), + array.dtype().clone(), + validity, + ) + .into_array())) + } +} + fn take_views>( views_ref: &[BinaryView], indices: &[I], @@ -85,6 +131,28 @@ fn take_views>( } } +fn gather_piecewise_views( + source: &[BinaryView], + starts: &[S], + lengths: &[L], + output_len: usize, +) -> VortexResult> +where + S: crate::dtype::UnsignedPType, + L: crate::dtype::UnsignedPType, +{ + validate_index_ranges(source.len(), starts, lengths, output_len)?; + + let mut views = BufferMut::::with_capacity(output_len); + for (&start, &length) in starts.iter().zip_eq(lengths) { + let start = start.as_(); + let length = length.as_(); + views.extend_from_slice(&source[start..start + length]); + } + + Ok(views.freeze()) +} + #[cfg(test)] mod tests { use rstest::rstest; From 297a42440864cf546a0668401783147349f5ff44 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Thu, 16 Jul 2026 14:38:00 -0400 Subject: [PATCH 02/20] Port FSL take benchmarks to PiecewiseSequential Signed-off-by: Daniel King --- Cargo.lock | 1 + vortex-array/benches/take_fsl.rs | 216 +++++++++++++++++++++++++++++-- vortex-bench/Cargo.toml | 1 + 3 files changed, 209 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e79211b5436..11a58bb49f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9783,6 +9783,7 @@ dependencies = [ "reqwest 0.13.4", "serde", "serde_json", + "sha2 0.11.0", "spatialbench", "spatialbench-arrow", "sysinfo", diff --git a/vortex-array/benches/take_fsl.rs b/vortex-array/benches/take_fsl.rs index 5dc491c28c5..a47896a7497 100644 --- a/vortex-array/benches/take_fsl.rs +++ b/vortex-array/benches/take_fsl.rs @@ -6,6 +6,7 @@ //! Parameterized over: //! - Number of indices to take //! - Fixed size list length (elements per list) +//! - Element byte width #![expect(clippy::cast_possible_truncation)] #![expect(clippy::unwrap_used)] @@ -13,16 +14,28 @@ use std::sync::LazyLock; use divan::Bencher; +use divan::counter::BytesCount; +use num_traits::FromPrimitive; use rand::RngExt; use rand::SeedableRng; use rand::rngs::StdRng; +use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::RecursiveCanonical; use vortex_array::VortexSessionExecute; use vortex_array::array_session; +use vortex_array::arrays::ConstantArray; use vortex_array::arrays::FixedSizeListArray; +use vortex_array::arrays::PiecewiseSequentialArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::fixed_size_list::FixedSizeListArrayExt; +use vortex_array::dtype::IntegerPType; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::half::f16; +use vortex_array::match_smallest_offset_type; use vortex_array::validity::Validity; use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; use vortex_session::VortexSession; fn main() { @@ -35,16 +48,25 @@ static SESSION: LazyLock = LazyLock::new(array_session); /// Number of lists in the source array. const NUM_LISTS: usize = 500; -/// Number of indices to take. -const NUM_INDICES: &[usize] = &[100, 1_000]; +/// Number of indices to take. This keeps even the widest, longest cases below one millisecond in +/// CodSpeed's instruction-count simulation. +const NUM_INDICES: &[usize] = &[10]; /// Fixed size list lengths (elements per list). -const LIST_SIZES: &[usize] = &[16, 64, 256, 1024, 4096]; +const LIST_SIZES: &[usize] = &[16, 64, 128, 256, 512, 1024, 2048, 4096]; + +/// F16 list lengths for isolating the per-index, piecewise, and manual range-copy strategies. +const F16_STRATEGY_LIST_SIZES: &[usize] = &[1, 2, 4, 8, 16, 64, 128, 256, 512, 1024, 2048, 4096]; /// Creates a FixedSizeListArray with the given list size and number of lists. -fn create_fsl(list_size: usize, num_lists: usize) -> FixedSizeListArray { +fn create_fsl(list_size: usize, num_lists: usize) -> FixedSizeListArray +where + T: NativePType + FromPrimitive, +{ let total_elements = list_size * num_lists; - let elements: Buffer = (0..total_elements as i64).collect(); + let elements: Buffer = (0..total_elements) + .map(|idx| T::from_u16((idx % 251) as u16).unwrap()) + .collect(); FixedSizeListArray::new( elements.into_array(), list_size as u32, @@ -62,12 +84,35 @@ fn create_random_indices(num_indices: usize, max_index: usize) -> Buffer { } #[divan::bench(args = NUM_INDICES, consts = LIST_SIZES)] -fn take_fsl_random(bencher: Bencher, num_indices: usize) { - let fsl = create_fsl(LIST_SIZE, NUM_LISTS); +fn take_fsl_f16_random(bencher: Bencher, num_indices: usize) { + take_fsl_random::(bencher, num_indices); +} + +#[divan::bench(args = NUM_INDICES, consts = LIST_SIZES)] +fn take_fsl_u8_random(bencher: Bencher, num_indices: usize) { + take_fsl_random::(bencher, num_indices); +} + +#[divan::bench(args = NUM_INDICES, consts = LIST_SIZES)] +fn take_fsl_u32_random(bencher: Bencher, num_indices: usize) { + take_fsl_random::(bencher, num_indices); +} + +#[divan::bench(args = NUM_INDICES, consts = LIST_SIZES)] +fn take_fsl_u64_random(bencher: Bencher, num_indices: usize) { + take_fsl_random::(bencher, num_indices); +} + +fn take_fsl_random(bencher: Bencher, num_indices: usize) +where + T: NativePType + FromPrimitive, +{ + let fsl = create_fsl::(LIST_SIZE, NUM_LISTS); let indices = create_random_indices(num_indices, NUM_LISTS); let indices_array = indices.into_array(); bencher + .counter(BytesCount::of_many::(num_indices * LIST_SIZE)) .with_inputs(|| (&fsl, &indices_array, SESSION.create_execution_ctx())) .bench_refs(|(array, indices, execution_ctx)| { array @@ -79,10 +124,162 @@ fn take_fsl_random(bencher: Bencher, num_indices: usize) }); } +#[divan::bench(args = NUM_INDICES, consts = F16_STRATEGY_LIST_SIZES)] +fn take_fsl_f16_force_per_index(bencher: Bencher, num_indices: usize) { + let fsl = create_fsl::(LIST_SIZE, NUM_LISTS); + let indices = create_random_indices(num_indices, NUM_LISTS); + + bencher + .counter(BytesCount::of_many::(num_indices * LIST_SIZE)) + .with_inputs(|| (&fsl, &indices, SESSION.create_execution_ctx())) + .bench_refs(|(array, indices, execution_ctx)| { + match_smallest_offset_type!(array.elements().len(), |E| { + take_fsl_f16_per_index_strategy::(array, indices) + }) + .into_array() + .execute::(execution_ctx) + .unwrap() + }); +} + +#[divan::bench(args = NUM_INDICES, consts = F16_STRATEGY_LIST_SIZES)] +fn take_fsl_f16_force_piecewise_sequential( + bencher: Bencher, + num_indices: usize, +) { + let fsl = create_fsl::(LIST_SIZE, NUM_LISTS); + let indices = create_random_indices(num_indices, NUM_LISTS); + + bencher + .counter(BytesCount::of_many::(num_indices * LIST_SIZE)) + .with_inputs(|| (&fsl, &indices, SESSION.create_execution_ctx())) + .bench_refs(|(array, indices, execution_ctx)| { + take_fsl_f16_piecewise_sequential_strategy::(array, indices) + .into_array() + .execute::(execution_ctx) + .unwrap() + }); +} + +#[divan::bench(args = NUM_INDICES, consts = F16_STRATEGY_LIST_SIZES)] +fn take_fsl_f16_force_manual_range_copy( + bencher: Bencher, + num_indices: usize, +) { + let fsl = create_fsl::(LIST_SIZE, NUM_LISTS); + let indices = create_random_indices(num_indices, NUM_LISTS); + + bencher + .counter(BytesCount::of_many::(num_indices * LIST_SIZE)) + .with_inputs(|| (&fsl, &indices, SESSION.create_execution_ctx())) + .bench_refs(|(array, indices, execution_ctx)| { + take_fsl_f16_manual_range_copy_strategy::(array, indices, execution_ctx) + .into_array() + .execute::(execution_ctx) + .unwrap() + }); +} + +fn take_fsl_f16_per_index_strategy( + array: &FixedSizeListArray, + indices: &Buffer, +) -> FixedSizeListArray { + let mut element_indices = BufferMut::::with_capacity(indices.len() * LIST_SIZE); + for &idx in indices.as_ref() { + let start = idx as usize * LIST_SIZE; + let end = start + LIST_SIZE; + for element_idx in start..end { + // SAFETY: capacity is exactly `indices.len() * LIST_SIZE`, and this loop appends + // exactly `LIST_SIZE` element indices for each input index. + unsafe { element_indices.push_unchecked(E::from_usize(element_idx).unwrap()) }; + } + } + + let element_indices = + PrimitiveArray::new(element_indices.freeze(), Validity::NonNullable).into_array(); + let elements = array.elements().take(element_indices).unwrap(); + + // SAFETY: `elements` was built by taking exactly `LIST_SIZE` elements per input index, so its + // length is `indices.len() * LIST_SIZE`; the output is non-nullable by construction. + unsafe { + FixedSizeListArray::new_unchecked( + elements, + LIST_SIZE as u32, + Validity::NonNullable, + indices.len(), + ) + } +} + +fn take_fsl_f16_piecewise_sequential_strategy( + array: &FixedSizeListArray, + indices: &Buffer, +) -> FixedSizeListArray { + let starts = indices + .as_ref() + .iter() + .map(|&idx| idx * LIST_SIZE as u64) + .collect::>(); + let run_count = starts.len(); + let starts = PrimitiveArray::from_iter(starts).into_array(); + let lengths = ConstantArray::new(LIST_SIZE as u64, run_count).into_array(); + + // SAFETY: benchmark indices are generated in-bounds, lengths is a non-nullable unsigned + // constant, and output length is exactly `indices.len() * LIST_SIZE`. + let element_indices = unsafe { + PiecewiseSequentialArray::new_unchecked(starts, lengths, indices.len() * LIST_SIZE) + } + .into_array(); + let elements = array.elements().take(element_indices).unwrap(); + + // SAFETY: each generated run has width `LIST_SIZE`, and there is one run per input index, + // so `elements.len() == indices.len() * LIST_SIZE`. + unsafe { + FixedSizeListArray::new_unchecked( + elements, + LIST_SIZE as u32, + Validity::NonNullable, + indices.len(), + ) + } +} + +fn take_fsl_f16_manual_range_copy_strategy( + array: &FixedSizeListArray, + indices: &Buffer, + execution_ctx: &mut ExecutionCtx, +) -> FixedSizeListArray { + let elements = array + .elements() + .clone() + .execute::(execution_ctx) + .unwrap(); + let source = elements.as_slice::(); + let mut values = BufferMut::::with_capacity(indices.len() * LIST_SIZE); + + for &idx in indices.as_ref() { + let start = idx as usize * LIST_SIZE; + values.extend_from_slice(&source[start..start + LIST_SIZE]); + } + + // SAFETY: the buffer was filled with exactly `LIST_SIZE` copied values per input index, so it + // has the element length required by the constructed FSL. + unsafe { + FixedSizeListArray::new_unchecked( + PrimitiveArray::new(values.freeze(), Validity::NonNullable).into_array(), + LIST_SIZE as u32, + Validity::NonNullable, + indices.len(), + ) + } +} + #[divan::bench(args = NUM_INDICES, consts = LIST_SIZES)] -fn take_fsl_nullable_random(bencher: Bencher, num_indices: usize) { +fn take_fsl_f16_nullable_random(bencher: Bencher, num_indices: usize) { let total_elements = LIST_SIZE * NUM_LISTS; - let elements: Buffer = (0..total_elements as i64).collect(); + let elements: Buffer = (0..total_elements) + .map(|idx| f16::from_u16((idx % 251) as u16).unwrap()) + .collect(); // Create validity with ~10% nulls let mut rng = StdRng::seed_from_u64(123); @@ -94,6 +291,7 @@ fn take_fsl_nullable_random(bencher: Bencher, num_indice let indices_array = indices.into_array(); bencher + .counter(BytesCount::of_many::(num_indices * LIST_SIZE)) .with_inputs(|| (&fsl, &indices_array, SESSION.create_execution_ctx())) .bench_refs(|(array, indices, execution_ctx)| { array diff --git a/vortex-bench/Cargo.toml b/vortex-bench/Cargo.toml index 02f043b8e68..d3a23c976f1 100644 --- a/vortex-bench/Cargo.toml +++ b/vortex-bench/Cargo.toml @@ -58,6 +58,7 @@ regex = { workspace = true } reqwest = { workspace = true, features = ["stream"] } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } +sha2 = { workspace = true } spatialbench = { workspace = true } spatialbench-arrow = { workspace = true } spatialbench-parquet = { workspace = true } From 6aae8012ad129ee151056e8c36ff4d5c4050077b Mon Sep 17 00:00:00 2001 From: Daniel King Date: Thu, 16 Jul 2026 16:24:01 -0400 Subject: [PATCH 03/20] Gate PiecewiseSequence take paths on unit multipliers Signed-off-by: Daniel King --- vortex-array/benches/take_fsl.rs | 20 ++++++++++++------- .../src/arrays/decimal/compute/take.rs | 10 ++++------ .../src/arrays/piecewise_sequence/mod.rs | 12 +++++------ .../src/arrays/piecewise_sequence/tests.rs | 20 +++++++++++++++++++ .../src/arrays/varbinview/compute/take.rs | 16 ++++++++------- 5 files changed, 52 insertions(+), 26 deletions(-) diff --git a/vortex-array/benches/take_fsl.rs b/vortex-array/benches/take_fsl.rs index a47896a7497..e02d9695b82 100644 --- a/vortex-array/benches/take_fsl.rs +++ b/vortex-array/benches/take_fsl.rs @@ -26,7 +26,7 @@ use vortex_array::VortexSessionExecute; use vortex_array::array_session; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::FixedSizeListArray; -use vortex_array::arrays::PiecewiseSequentialArray; +use vortex_array::arrays::PiecewiseSequenceArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::fixed_size_list::FixedSizeListArrayExt; use vortex_array::dtype::IntegerPType; @@ -143,7 +143,7 @@ fn take_fsl_f16_force_per_index(bencher: Bencher, num_in } #[divan::bench(args = NUM_INDICES, consts = F16_STRATEGY_LIST_SIZES)] -fn take_fsl_f16_force_piecewise_sequential( +fn take_fsl_f16_force_piecewise_sequence( bencher: Bencher, num_indices: usize, ) { @@ -154,7 +154,7 @@ fn take_fsl_f16_force_piecewise_sequential( .counter(BytesCount::of_many::(num_indices * LIST_SIZE)) .with_inputs(|| (&fsl, &indices, SESSION.create_execution_ctx())) .bench_refs(|(array, indices, execution_ctx)| { - take_fsl_f16_piecewise_sequential_strategy::(array, indices) + take_fsl_f16_piecewise_sequence_strategy::(array, indices) .into_array() .execute::(execution_ctx) .unwrap() @@ -211,7 +211,7 @@ fn take_fsl_f16_per_index_strategy( } } -fn take_fsl_f16_piecewise_sequential_strategy( +fn take_fsl_f16_piecewise_sequence_strategy( array: &FixedSizeListArray, indices: &Buffer, ) -> FixedSizeListArray { @@ -223,11 +223,17 @@ fn take_fsl_f16_piecewise_sequential_strategy( let run_count = starts.len(); let starts = PrimitiveArray::from_iter(starts).into_array(); let lengths = ConstantArray::new(LIST_SIZE as u64, run_count).into_array(); + let multipliers = ConstantArray::new(1u64, run_count).into_array(); - // SAFETY: benchmark indices are generated in-bounds, lengths is a non-nullable unsigned - // constant, and output length is exactly `indices.len() * LIST_SIZE`. + // SAFETY: benchmark indices are generated in-bounds; lengths and multiplier 1 are + // non-nullable unsigned constants; output length is exactly `indices.len() * LIST_SIZE`. let element_indices = unsafe { - PiecewiseSequentialArray::new_unchecked(starts, lengths, indices.len() * LIST_SIZE) + PiecewiseSequenceArray::new_unchecked( + starts, + lengths, + multipliers, + indices.len() * LIST_SIZE, + ) } .into_array(); let elements = array.elements().take(element_indices).unwrap(); diff --git a/vortex-array/src/arrays/decimal/compute/take.rs b/vortex-array/src/arrays/decimal/compute/take.rs index 213d6db39bf..0bd79299d5c 100644 --- a/vortex-array/src/arrays/decimal/compute/take.rs +++ b/vortex-array/src/arrays/decimal/compute/take.rs @@ -75,12 +75,10 @@ fn take_piecewise_sequence( let validity = array.validity()?.take(indices_ref)?; // SAFETY: contiguous gather preserves the decimal dtype and value representation. - Ok( - Some(unsafe { - DecimalArray::new_unchecked(values, array.decimal_dtype(), validity) - } - .into_array()), - ) + Ok(Some( + unsafe { DecimalArray::new_unchecked(values, array.decimal_dtype(), validity) } + .into_array(), + )) }) }) }) diff --git a/vortex-array/src/arrays/piecewise_sequence/mod.rs b/vortex-array/src/arrays/piecewise_sequence/mod.rs index a5361567c7d..37f009ca19f 100644 --- a/vortex-array/src/arrays/piecewise_sequence/mod.rs +++ b/vortex-array/src/arrays/piecewise_sequence/mod.rs @@ -163,16 +163,16 @@ where for (&start, &length) in starts.iter().zip_eq(lengths) { let start: usize = start.as_(); let length: usize = length.as_(); - let end = start.checked_add(length).ok_or_else(|| { - vortex_err!("PiecewiseSequenceArray range overflows usize") - })?; + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; vortex_ensure!( end <= source_len, "PiecewiseSequenceArray range {start}..{end} exceeds source length {source_len}" ); - computed_len = computed_len.checked_add(length).ok_or_else(|| { - vortex_err!("PiecewiseSequenceArray output length overflows usize") - })?; + computed_len = computed_len + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; } vortex_ensure!( diff --git a/vortex-array/src/arrays/piecewise_sequence/tests.rs b/vortex-array/src/arrays/piecewise_sequence/tests.rs index 1abbada7a92..bc11bb9dc69 100644 --- a/vortex-array/src/arrays/piecewise_sequence/tests.rs +++ b/vortex-array/src/arrays/piecewise_sequence/tests.rs @@ -187,6 +187,26 @@ fn primitive_take_consumes_piecewise_indices() -> VortexResult<()> { Ok(()) } +#[test] +fn primitive_take_handles_non_unit_multiplier() -> VortexResult<()> { + let values = PrimitiveArray::from_iter(0i32..20).into_array(); + let indices = PiecewiseSequenceArray::try_new( + buffer![3u64].into_array(), + buffer![3u64].into_array(), + buffer![2u64].into_array(), + 3, + )? + .into_array(); + let taken = values.take(indices)?; + + assert_arrays_eq!( + taken, + PrimitiveArray::from_iter([3i32, 5, 7]).into_array(), + &mut array_session().create_execution_ctx() + ); + Ok(()) +} + #[test] fn bool_take_consumes_piecewise_indices() -> VortexResult<()> { let values = BoolArray::from_iter([true, false, true, true, false, false]).into_array(); diff --git a/vortex-array/src/arrays/varbinview/compute/take.rs b/vortex-array/src/arrays/varbinview/compute/take.rs index 89206a17c9f..dadc3041a3c 100644 --- a/vortex-array/src/arrays/varbinview/compute/take.rs +++ b/vortex-array/src/arrays/varbinview/compute/take.rs @@ -93,13 +93,15 @@ fn take_piecewise_sequence( // SAFETY: ranges were validated against the source views, and copied views still reference the // same backing data buffers. unsafe { - Ok(Some(VarBinViewArray::new_handle_unchecked( - BufferHandle::new_host(views.into_byte_buffer()), - Arc::clone(array.data_buffers()), - array.dtype().clone(), - validity, - ) - .into_array())) + Ok(Some( + VarBinViewArray::new_handle_unchecked( + BufferHandle::new_host(views.into_byte_buffer()), + Arc::clone(array.data_buffers()), + array.dtype().clone(), + validity, + ) + .into_array(), + )) } } From c5a52c86bb9e0feaeaf4ca49b2d83b46a6e57ad7 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Thu, 16 Jul 2026 16:36:18 -0400 Subject: [PATCH 04/20] Preserve existing FSL take benchmarks Signed-off-by: Daniel King --- vortex-array/benches/take_fsl.rs | 106 ++++++++++++++++++++----------- 1 file changed, 69 insertions(+), 37 deletions(-) diff --git a/vortex-array/benches/take_fsl.rs b/vortex-array/benches/take_fsl.rs index e02d9695b82..cfd434b16c4 100644 --- a/vortex-array/benches/take_fsl.rs +++ b/vortex-array/benches/take_fsl.rs @@ -48,9 +48,8 @@ static SESSION: LazyLock = LazyLock::new(array_session); /// Number of lists in the source array. const NUM_LISTS: usize = 500; -/// Number of indices to take. This keeps even the widest, longest cases below one millisecond in -/// CodSpeed's instruction-count simulation. -const NUM_INDICES: &[usize] = &[10]; +/// Number of indices to take. +const NUM_INDICES: &[usize] = &[100, 1_000]; /// Fixed size list lengths (elements per list). const LIST_SIZES: &[usize] = &[16, 64, 128, 256, 512, 1024, 2048, 4096]; @@ -58,8 +57,22 @@ const LIST_SIZES: &[usize] = &[16, 64, 128, 256, 512, 1024, 2048, 4096]; /// F16 list lengths for isolating the per-index, piecewise, and manual range-copy strategies. const F16_STRATEGY_LIST_SIZES: &[usize] = &[1, 2, 4, 8, 16, 64, 128, 256, 512, 1024, 2048, 4096]; +/// F16 strategy benchmarks keep a smaller take width so the forced slow strategies stay cheap. +const F16_STRATEGY_NUM_INDICES: &[usize] = &[10]; + /// Creates a FixedSizeListArray with the given list size and number of lists. fn create_fsl(list_size: usize, num_lists: usize) -> FixedSizeListArray +where + T: NativePType + FromPrimitive, +{ + create_fsl_with_validity::(list_size, num_lists, Validity::NonNullable) +} + +fn create_fsl_with_validity( + list_size: usize, + num_lists: usize, + validity: Validity, +) -> FixedSizeListArray where T: NativePType + FromPrimitive, { @@ -67,12 +80,17 @@ where let elements: Buffer = (0..total_elements) .map(|idx| T::from_u16((idx % 251) as u16).unwrap()) .collect(); - FixedSizeListArray::new( - elements.into_array(), - list_size as u32, - Validity::NonNullable, - num_lists, - ) + FixedSizeListArray::new(elements.into_array(), list_size as u32, validity, num_lists) +} + +fn create_i64_fsl_with_validity( + list_size: usize, + num_lists: usize, + validity: Validity, +) -> FixedSizeListArray { + let total_elements = list_size * num_lists; + let elements: Buffer = (0..total_elements as i64).collect(); + FixedSizeListArray::new(elements.into_array(), list_size as u32, validity, num_lists) } /// Creates random indices for taking from the array. @@ -83,31 +101,47 @@ fn create_random_indices(num_indices: usize, max_index: usize) -> Buffer { .collect() } +#[divan::bench(args = NUM_INDICES, consts = LIST_SIZES)] +fn take_fsl_random(bencher: Bencher, num_indices: usize) { + let fsl = create_i64_fsl_with_validity(LIST_SIZE, NUM_LISTS, Validity::NonNullable); + bench_take_fsl_random::(bencher, num_indices, fsl); +} + #[divan::bench(args = NUM_INDICES, consts = LIST_SIZES)] fn take_fsl_f16_random(bencher: Bencher, num_indices: usize) { - take_fsl_random::(bencher, num_indices); + take_fsl_random_typed::(bencher, num_indices); } #[divan::bench(args = NUM_INDICES, consts = LIST_SIZES)] fn take_fsl_u8_random(bencher: Bencher, num_indices: usize) { - take_fsl_random::(bencher, num_indices); + take_fsl_random_typed::(bencher, num_indices); } #[divan::bench(args = NUM_INDICES, consts = LIST_SIZES)] fn take_fsl_u32_random(bencher: Bencher, num_indices: usize) { - take_fsl_random::(bencher, num_indices); + take_fsl_random_typed::(bencher, num_indices); } #[divan::bench(args = NUM_INDICES, consts = LIST_SIZES)] fn take_fsl_u64_random(bencher: Bencher, num_indices: usize) { - take_fsl_random::(bencher, num_indices); + take_fsl_random_typed::(bencher, num_indices); } -fn take_fsl_random(bencher: Bencher, num_indices: usize) +fn take_fsl_random_typed(bencher: Bencher, num_indices: usize) where T: NativePType + FromPrimitive, { let fsl = create_fsl::(LIST_SIZE, NUM_LISTS); + bench_take_fsl_random::(bencher, num_indices, fsl); +} + +fn bench_take_fsl_random( + bencher: Bencher, + num_indices: usize, + fsl: FixedSizeListArray, +) where + T: NativePType, +{ let indices = create_random_indices(num_indices, NUM_LISTS); let indices_array = indices.into_array(); @@ -124,7 +158,7 @@ where }); } -#[divan::bench(args = NUM_INDICES, consts = F16_STRATEGY_LIST_SIZES)] +#[divan::bench(args = F16_STRATEGY_NUM_INDICES, consts = F16_STRATEGY_LIST_SIZES)] fn take_fsl_f16_force_per_index(bencher: Bencher, num_indices: usize) { let fsl = create_fsl::(LIST_SIZE, NUM_LISTS); let indices = create_random_indices(num_indices, NUM_LISTS); @@ -142,7 +176,7 @@ fn take_fsl_f16_force_per_index(bencher: Bencher, num_in }); } -#[divan::bench(args = NUM_INDICES, consts = F16_STRATEGY_LIST_SIZES)] +#[divan::bench(args = F16_STRATEGY_NUM_INDICES, consts = F16_STRATEGY_LIST_SIZES)] fn take_fsl_f16_force_piecewise_sequence( bencher: Bencher, num_indices: usize, @@ -161,7 +195,7 @@ fn take_fsl_f16_force_piecewise_sequence( }); } -#[divan::bench(args = NUM_INDICES, consts = F16_STRATEGY_LIST_SIZES)] +#[divan::bench(args = F16_STRATEGY_NUM_INDICES, consts = F16_STRATEGY_LIST_SIZES)] fn take_fsl_f16_force_manual_range_copy( bencher: Bencher, num_indices: usize, @@ -281,30 +315,28 @@ fn take_fsl_f16_manual_range_copy_strategy( } #[divan::bench(args = NUM_INDICES, consts = LIST_SIZES)] -fn take_fsl_f16_nullable_random(bencher: Bencher, num_indices: usize) { - let total_elements = LIST_SIZE * NUM_LISTS; - let elements: Buffer = (0..total_elements) - .map(|idx| f16::from_u16((idx % 251) as u16).unwrap()) - .collect(); - +fn take_fsl_nullable_random(bencher: Bencher, num_indices: usize) { // Create validity with ~10% nulls let mut rng = StdRng::seed_from_u64(123); let validity = Validity::from_iter((0..NUM_LISTS).map(|_| rng.random_ratio(9, 10))); - let fsl = FixedSizeListArray::new(elements.into_array(), LIST_SIZE as u32, validity, NUM_LISTS); + let fsl = create_i64_fsl_with_validity(LIST_SIZE, NUM_LISTS, validity); + bench_take_fsl_random::(bencher, num_indices, fsl); +} - let indices = create_random_indices(num_indices, NUM_LISTS); - let indices_array = indices.into_array(); +#[divan::bench(args = NUM_INDICES, consts = LIST_SIZES)] +fn take_fsl_f16_nullable_random(bencher: Bencher, num_indices: usize) { + take_fsl_nullable_random_typed::(bencher, num_indices); +} - bencher - .counter(BytesCount::of_many::(num_indices * LIST_SIZE)) - .with_inputs(|| (&fsl, &indices_array, SESSION.create_execution_ctx())) - .bench_refs(|(array, indices, execution_ctx)| { - array - .clone() - .take(indices.clone()) - .unwrap() - .execute::(execution_ctx) - .unwrap() - }); +fn take_fsl_nullable_random_typed(bencher: Bencher, num_indices: usize) +where + T: NativePType + FromPrimitive, +{ + // Create validity with ~10% nulls + let mut rng = StdRng::seed_from_u64(123); + let validity = Validity::from_iter((0..NUM_LISTS).map(|_| rng.random_ratio(9, 10))); + + let fsl = create_fsl_with_validity::(LIST_SIZE, NUM_LISTS, validity); + bench_take_fsl_random::(bencher, num_indices, fsl); } From a0e052b063613c661bb8deb89463db888a5421af Mon Sep 17 00:00:00 2001 From: Daniel King Date: Thu, 16 Jul 2026 19:40:37 -0400 Subject: [PATCH 05/20] Split PiecewiseSequence take dispatch Signed-off-by: Daniel King --- .../src/arrays/decimal/compute/take.rs | 81 ++++++++++++++----- .../src/arrays/primitive/compute/take/mod.rs | 75 +++++++++++++---- 2 files changed, 121 insertions(+), 35 deletions(-) diff --git a/vortex-array/src/arrays/decimal/compute/take.rs b/vortex-array/src/arrays/decimal/compute/take.rs index 0bd79299d5c..ed479b42bbb 100644 --- a/vortex-array/src/arrays/decimal/compute/take.rs +++ b/vortex-array/src/arrays/decimal/compute/take.rs @@ -18,10 +18,12 @@ use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; use crate::arrays::piecewise_sequence::validate_index_ranges; use crate::dtype::IntegerPType; use crate::dtype::NativeDecimalType; +use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; use crate::match_each_decimal_value_type; use crate::match_each_integer_ptype; use crate::match_each_unsigned_integer_ptype; +use crate::validity::Validity; impl TakeExecute for Decimal { fn take( @@ -63,24 +65,65 @@ fn take_piecewise_sequence( let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { return Ok(None); }; + let validity = array.validity()?.take(indices_ref)?; + let output_len = indices_ref.len(); + let taken = take_piecewise_sequence_lengths(array, &starts, &lengths, validity, output_len)?; + Ok(Some(taken)) +} + +fn take_piecewise_sequence_lengths( + array: ArrayView<'_, Decimal>, + starts: &PrimitiveArray, + lengths: &PrimitiveArray, + validity: Validity, + output_len: usize, +) -> VortexResult { match_each_decimal_value_type!(array.values_type(), |D| { - match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { - let values = take_piecewise_to_buffer::( - starts.as_slice::(), - lengths.as_slice::(), - array.buffer::().as_slice(), - indices_ref.len(), - )?; - let validity = array.validity()?.take(indices_ref)?; - - // SAFETY: contiguous gather preserves the decimal dtype and value representation. - Ok(Some( - unsafe { DecimalArray::new_unchecked(values, array.decimal_dtype(), validity) } - .into_array(), - )) - }) - }) + take_piecewise_sequence_lengths_typed::(array, starts, lengths, validity, output_len) + }) +} + +fn take_piecewise_sequence_lengths_typed( + array: ArrayView<'_, Decimal>, + starts: &PrimitiveArray, + lengths: &PrimitiveArray, + validity: Validity, + output_len: usize, +) -> VortexResult +where + D: NativeDecimalType, +{ + match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + take_piecewise_sequence_lengths_start_typed::( + array, starts, lengths, validity, output_len, + ) + }) +} + +fn take_piecewise_sequence_lengths_start_typed( + array: ArrayView<'_, Decimal>, + starts: &PrimitiveArray, + lengths: &PrimitiveArray, + validity: Validity, + output_len: usize, +) -> VortexResult +where + D: NativeDecimalType, + S: UnsignedPType, +{ + match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { + let values = take_piecewise_to_buffer::( + starts.as_slice::(), + lengths.as_slice::(), + array.buffer::().as_slice(), + output_len, + )?; + + // SAFETY: contiguous gather preserves the decimal dtype and value representation. + Ok( + unsafe { DecimalArray::new_unchecked(values, array.decimal_dtype(), validity) } + .into_array(), + ) }) } @@ -95,8 +138,8 @@ fn take_piecewise_to_buffer( output_len: usize, ) -> VortexResult> where - S: crate::dtype::UnsignedPType, - L: crate::dtype::UnsignedPType, + S: UnsignedPType, + L: UnsignedPType, T: NativeDecimalType, { validate_index_ranges(values.len(), starts, lengths, output_len)?; diff --git a/vortex-array/src/arrays/primitive/compute/take/mod.rs b/vortex-array/src/arrays/primitive/compute/take/mod.rs index a7b316a4c9b..c67a2c5d725 100644 --- a/vortex-array/src/arrays/primitive/compute/take/mod.rs +++ b/vortex-array/src/arrays/primitive/compute/take/mod.rs @@ -26,6 +26,8 @@ use crate::arrays::piecewise_sequence::validate_index_ranges; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::IntegerPType; +use crate::dtype::NativePType; +use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; use crate::match_each_integer_ptype; use crate::match_each_native_ptype; @@ -143,20 +145,10 @@ fn take_piecewise_sequence( let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { return Ok(None); }; - match_each_native_ptype!(array.ptype(), |T| { - match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { - let values = primitive_piecewise_values::( - array.as_slice::(), - starts.as_slice::(), - lengths.as_slice::(), - indices_ref.len(), - )?; - let validity = array.validity()?.take(indices_ref)?; - Ok(Some(PrimitiveArray::new(values, validity).into_array())) - }) - }) - }) + let validity = array.validity()?.take(indices_ref)?; + let output_len = indices_ref.len(); + let taken = take_piecewise_sequence_lengths(array, &starts, &lengths, validity, output_len)?; + Ok(Some(taken)) } // Compiler may see this as unused based on enabled features @@ -180,6 +172,57 @@ fn take_primitive_scalar(buffer: &[T], indices: &[I]) result.freeze() } +fn take_piecewise_sequence_lengths( + array: ArrayView<'_, Primitive>, + starts: &PrimitiveArray, + lengths: &PrimitiveArray, + validity: Validity, + output_len: usize, +) -> VortexResult { + match_each_native_ptype!(array.ptype(), |T| { + take_piecewise_sequence_lengths_typed::(array, starts, lengths, validity, output_len) + }) +} + +fn take_piecewise_sequence_lengths_typed( + array: ArrayView<'_, Primitive>, + starts: &PrimitiveArray, + lengths: &PrimitiveArray, + validity: Validity, + output_len: usize, +) -> VortexResult +where + T: NativePType, +{ + match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + take_piecewise_sequence_lengths_start_typed::( + array, starts, lengths, validity, output_len, + ) + }) +} + +fn take_piecewise_sequence_lengths_start_typed( + array: ArrayView<'_, Primitive>, + starts: &PrimitiveArray, + lengths: &PrimitiveArray, + validity: Validity, + output_len: usize, +) -> VortexResult +where + T: NativePType, + S: UnsignedPType, +{ + match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { + let values = primitive_piecewise_values::( + array.as_slice::(), + starts.as_slice::(), + lengths.as_slice::(), + output_len, + )?; + Ok(PrimitiveArray::new(values, validity).into_array()) + }) +} + fn primitive_piecewise_values( source: &[T], starts: &[S], @@ -188,8 +231,8 @@ fn primitive_piecewise_values( ) -> VortexResult> where T: Copy, - S: crate::dtype::UnsignedPType, - L: crate::dtype::UnsignedPType, + S: UnsignedPType, + L: UnsignedPType, { validate_index_ranges(source.len(), starts, lengths, output_len)?; From 7e1bc718f11bfaf61f42f465c69640622e21c6fc Mon Sep 17 00:00:00 2001 From: Daniel King Date: Thu, 16 Jul 2026 19:41:48 -0400 Subject: [PATCH 06/20] Fix PiecewiseSequence test length cast Signed-off-by: Daniel King --- vortex-array/src/arrays/piecewise_sequence/tests.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/vortex-array/src/arrays/piecewise_sequence/tests.rs b/vortex-array/src/arrays/piecewise_sequence/tests.rs index bc11bb9dc69..1e4bb4329b2 100644 --- a/vortex-array/src/arrays/piecewise_sequence/tests.rs +++ b/vortex-array/src/arrays/piecewise_sequence/tests.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use num_traits::AsPrimitive; use vortex_buffer::ByteBufferMut; use vortex_buffer::buffer; use vortex_error::VortexResult; @@ -32,7 +33,10 @@ fn piecewise_indices( starts: impl IntoIterator, lengths: &[u64], ) -> VortexResult { - let len = lengths.iter().map(|&length| length as usize).sum(); + let len = lengths + .iter() + .map(|&length| -> usize { length.as_() }) + .sum(); let starts = PrimitiveArray::from_iter(starts).into_array(); let lengths = PrimitiveArray::from_iter(lengths.iter().copied()).into_array(); let multipliers = ConstantArray::new(1u64, lengths.len()).into_array(); From 43c330fc3a49dd77097d787a54108a1cdbc7a309 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Thu, 16 Jul 2026 20:15:07 -0400 Subject: [PATCH 07/20] Use imported UnsignedPType in take consumers Signed-off-by: Daniel King --- vortex-array/src/arrays/bool/compute/take.rs | 5 +++-- vortex-array/src/arrays/varbin/compute/take.rs | 5 +++-- vortex-array/src/arrays/varbinview/compute/take.rs | 5 +++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/vortex-array/src/arrays/bool/compute/take.rs b/vortex-array/src/arrays/bool/compute/take.rs index fe7955fbbae..2caca36e5df 100644 --- a/vortex-array/src/arrays/bool/compute/take.rs +++ b/vortex-array/src/arrays/bool/compute/take.rs @@ -23,6 +23,7 @@ use crate::arrays::dict::TakeExecute; use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; use crate::arrays::piecewise_sequence::validate_index_ranges; use crate::builtins::ArrayBuiltins; +use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; use crate::match_each_integer_ptype; use crate::match_each_unsigned_integer_ptype; @@ -125,8 +126,8 @@ fn take_piecewise_bits( output_len: usize, ) -> VortexResult where - S: crate::dtype::UnsignedPType, - L: crate::dtype::UnsignedPType, + S: UnsignedPType, + L: UnsignedPType, { validate_index_ranges(source.len(), starts, lengths, output_len)?; diff --git a/vortex-array/src/arrays/varbin/compute/take.rs b/vortex-array/src/arrays/varbin/compute/take.rs index f3c31bc9f1c..34d19863e20 100644 --- a/vortex-array/src/arrays/varbin/compute/take.rs +++ b/vortex-array/src/arrays/varbin/compute/take.rs @@ -27,6 +27,7 @@ use crate::arrays::varbin::VarBinArrayExt; use crate::dtype::DType; use crate::dtype::IntegerPType; use crate::dtype::PType; +use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; use crate::match_each_unsigned_integer_ptype; use crate::validity::Validity; @@ -285,8 +286,8 @@ fn gather_piecewise_varbin( out_offset_ptype: PType, ) -> VortexResult where - S: crate::dtype::UnsignedPType, - L: crate::dtype::UnsignedPType, + S: UnsignedPType, + L: UnsignedPType, Offset: IntegerPType, NewOffset: IntegerPType, { diff --git a/vortex-array/src/arrays/varbinview/compute/take.rs b/vortex-array/src/arrays/varbinview/compute/take.rs index dadc3041a3c..dd38b45929d 100644 --- a/vortex-array/src/arrays/varbinview/compute/take.rs +++ b/vortex-array/src/arrays/varbinview/compute/take.rs @@ -24,6 +24,7 @@ use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; use crate::arrays::piecewise_sequence::validate_index_ranges; use crate::arrays::varbinview::BinaryView; use crate::buffer::BufferHandle; +use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; use crate::match_each_integer_ptype; use crate::match_each_unsigned_integer_ptype; @@ -140,8 +141,8 @@ fn gather_piecewise_views( output_len: usize, ) -> VortexResult> where - S: crate::dtype::UnsignedPType, - L: crate::dtype::UnsignedPType, + S: UnsignedPType, + L: UnsignedPType, { validate_index_ranges(source.len(), starts, lengths, output_len)?; From c8571dafd6596ca143290f92b3a7600eb9bcf5c8 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Fri, 17 Jul 2026 11:28:32 -0400 Subject: [PATCH 08/20] Specialize constant PiecewiseSequence lengths Signed-off-by: Daniel King --- vortex-array/src/arrays/bool/compute/take.rs | 58 +++- .../src/arrays/decimal/compute/take.rs | 72 +++- .../src/arrays/piecewise_sequence/mod.rs | 66 +++- .../src/arrays/piecewise_sequence/tests.rs | 74 +++++ .../src/arrays/primitive/compute/take/mod.rs | 67 +++- .../src/arrays/varbin/compute/take.rs | 313 +++++++++++++++--- .../src/arrays/varbinview/compute/take.rs | 58 +++- 7 files changed, 630 insertions(+), 78 deletions(-) diff --git a/vortex-array/src/arrays/bool/compute/take.rs b/vortex-array/src/arrays/bool/compute/take.rs index 2caca36e5df..a467e19175f 100644 --- a/vortex-array/src/arrays/bool/compute/take.rs +++ b/vortex-array/src/arrays/bool/compute/take.rs @@ -20,8 +20,10 @@ use crate::arrays::PiecewiseSequence; use crate::arrays::PrimitiveArray; use crate::arrays::bool::BoolArrayExt; use crate::arrays::dict::TakeExecute; +use crate::arrays::piecewise_sequence::UnitMultiplierLengths; use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; use crate::arrays::piecewise_sequence::validate_index_ranges; +use crate::arrays::piecewise_sequence::validate_index_ranges_constant; use crate::builtins::ArrayBuiltins; use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; @@ -76,16 +78,32 @@ fn take_piecewise_sequence( let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { return Ok(None); }; - let buffer = match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { - take_piecewise_bits( - &array.to_bit_buffer(), - starts.as_slice::(), - lengths.as_slice::(), - indices_ref.len(), - )? - }) - }); + let source = array.to_bit_buffer(); + let output_len = indices_ref.len(); + let buffer = match &lengths { + UnitMultiplierLengths::Constant(length) => { + match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + take_piecewise_bits_constant_length( + &source, + starts.as_slice::(), + *length, + output_len, + )? + }) + } + UnitMultiplierLengths::Array(lengths) => { + match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { + take_piecewise_bits( + &source, + starts.as_slice::(), + lengths.as_slice::(), + output_len, + )? + }) + }) + } + }; Ok(Some( BoolArray::new(buffer, array.validity()?.take(indices_ref)?).into_array(), @@ -119,6 +137,26 @@ fn take_bool_impl>(bools: BitBufferView<'_>, indices: &[I] }) } +fn take_piecewise_bits_constant_length( + source: &BitBuffer, + starts: &[S], + length: usize, + output_len: usize, +) -> VortexResult +where + S: UnsignedPType, +{ + validate_index_ranges_constant(source.len(), starts, length, output_len)?; + + let mut values = BitBufferMut::with_capacity(output_len); + for &start in starts { + let start = start.as_(); + values.append_buffer(&source.slice(start..start + length)); + } + + Ok(values.freeze()) +} + fn take_piecewise_bits( source: &BitBuffer, starts: &[S], diff --git a/vortex-array/src/arrays/decimal/compute/take.rs b/vortex-array/src/arrays/decimal/compute/take.rs index ed479b42bbb..a2d508fd31e 100644 --- a/vortex-array/src/arrays/decimal/compute/take.rs +++ b/vortex-array/src/arrays/decimal/compute/take.rs @@ -14,8 +14,10 @@ use crate::arrays::DecimalArray; use crate::arrays::PiecewiseSequence; use crate::arrays::PrimitiveArray; use crate::arrays::dict::TakeExecute; +use crate::arrays::piecewise_sequence::UnitMultiplierLengths; use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; use crate::arrays::piecewise_sequence::validate_index_ranges; +use crate::arrays::piecewise_sequence::validate_index_ranges_constant; use crate::dtype::IntegerPType; use crate::dtype::NativeDecimalType; use crate::dtype::UnsignedPType; @@ -67,10 +69,57 @@ fn take_piecewise_sequence( }; let validity = array.validity()?.take(indices_ref)?; let output_len = indices_ref.len(); - let taken = take_piecewise_sequence_lengths(array, &starts, &lengths, validity, output_len)?; + let taken = match lengths { + UnitMultiplierLengths::Constant(length) => { + take_piecewise_sequence_constant_length(array, &starts, length, validity, output_len)? + } + UnitMultiplierLengths::Array(lengths) => { + take_piecewise_sequence_lengths(array, &starts, &lengths, validity, output_len)? + } + }; Ok(Some(taken)) } +fn take_piecewise_sequence_constant_length( + array: ArrayView<'_, Decimal>, + starts: &PrimitiveArray, + length: usize, + validity: Validity, + output_len: usize, +) -> VortexResult { + match_each_decimal_value_type!(array.values_type(), |D| { + take_piecewise_sequence_constant_length_typed::( + array, starts, length, validity, output_len, + ) + }) +} + +fn take_piecewise_sequence_constant_length_typed( + array: ArrayView<'_, Decimal>, + starts: &PrimitiveArray, + length: usize, + validity: Validity, + output_len: usize, +) -> VortexResult +where + D: NativeDecimalType, +{ + match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + let values = take_piecewise_constant_length_to_buffer::( + starts.as_slice::(), + length, + array.buffer::().as_slice(), + output_len, + )?; + + // SAFETY: contiguous gather preserves the decimal dtype and value representation. + Ok( + unsafe { DecimalArray::new_unchecked(values, array.decimal_dtype(), validity) } + .into_array(), + ) + }) +} + fn take_piecewise_sequence_lengths( array: ArrayView<'_, Decimal>, starts: &PrimitiveArray, @@ -131,6 +180,27 @@ fn take_to_buffer(indices: &[I], values: indices.iter().map(|idx| values[idx.as_()]).collect() } +fn take_piecewise_constant_length_to_buffer( + starts: &[S], + length: usize, + values: &[T], + output_len: usize, +) -> VortexResult> +where + S: UnsignedPType, + T: NativeDecimalType, +{ + validate_index_ranges_constant(values.len(), starts, length, output_len)?; + + let mut result = BufferMut::::with_capacity(output_len); + for &start in starts { + let start = start.as_(); + result.extend_from_slice(&values[start..start + length]); + } + + Ok(result.freeze()) +} + fn take_piecewise_to_buffer( starts: &[S], lengths: &[L], diff --git a/vortex-array/src/arrays/piecewise_sequence/mod.rs b/vortex-array/src/arrays/piecewise_sequence/mod.rs index 37f009ca19f..e5043e42e16 100644 --- a/vortex-array/src/arrays/piecewise_sequence/mod.rs +++ b/vortex-array/src/arrays/piecewise_sequence/mod.rs @@ -9,6 +9,7 @@ //! element. use itertools::Itertools; +use num_traits::AsPrimitive; use vortex_buffer::BufferMut; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -66,18 +67,29 @@ pub(crate) fn execute_index_arrays( Ok((starts, lengths, multipliers)) } +pub(crate) enum UnitMultiplierLengths { + Constant(usize), + Array(PrimitiveArray), +} + pub(crate) fn execute_unit_multiplier_index_arrays( array: ArrayView<'_, PiecewiseSequence>, ctx: &mut ExecutionCtx, -) -> VortexResult> { +) -> VortexResult> { if !is_constant_multiplier_one(array.multipliers()) { return Ok(None); } + check_index_arrays(array.starts(), array.lengths(), array.multipliers())?; let starts = array.starts().clone().execute::(ctx)?; + if let Some(length) = constant_unsigned_usize(array.lengths())? { + check_index_arrays(starts.as_ref(), array.lengths(), array.multipliers())?; + return Ok(Some((starts, UnitMultiplierLengths::Constant(length)))); + } + let lengths = array.lengths().clone().execute::(ctx)?; check_index_arrays(starts.as_ref(), lengths.as_ref(), array.multipliers())?; - Ok(Some((starts, lengths))) + Ok(Some((starts, UnitMultiplierLengths::Array(lengths)))) } pub(crate) fn is_constant_multiplier_one(multipliers: &ArrayRef) -> bool { @@ -90,6 +102,24 @@ pub(crate) fn is_constant_multiplier_one(multipliers: &ArrayRef) -> bool { ) } +fn constant_unsigned_usize(array: &ArrayRef) -> VortexResult> { + let Some(scalar) = array.as_constant() else { + return Ok(None); + }; + + let Some(pvalue) = scalar.as_primitive_opt().and_then(|scalar| scalar.pvalue()) else { + vortex_bail!("PiecewiseSequenceArray constant length must be an unsigned integer"); + }; + + Ok(Some(match pvalue { + PValue::U8(value) => value as usize, + PValue::U16(value) => value as usize, + PValue::U32(value) => value as usize, + PValue::U64(value) => value.as_(), + _ => vortex_bail!("PiecewiseSequenceArray constant length must be an unsigned integer"), + })) +} + fn check_index_array(name: &str, array: &ArrayRef) -> VortexResult<()> { vortex_ensure!( array.dtype().is_unsigned_int(), @@ -104,6 +134,38 @@ fn check_index_array(name: &str, array: &ArrayRef) -> VortexResult<()> { Ok(()) } +pub(crate) fn validate_index_ranges_constant( + source_len: usize, + starts: &[S], + length: usize, + output_len: usize, +) -> VortexResult<()> +where + S: UnsignedPType, +{ + let computed_len = starts + .len() + .checked_mul(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; + vortex_ensure!( + computed_len == output_len, + "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + ); + + for &start in starts { + let start: usize = start.as_(); + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; + vortex_ensure!( + end <= source_len, + "PiecewiseSequenceArray range {start}..{end} exceeds source length {source_len}" + ); + } + + Ok(()) +} + pub(crate) fn materialize_ranges( starts: &PrimitiveArray, lengths: &PrimitiveArray, diff --git a/vortex-array/src/arrays/piecewise_sequence/tests.rs b/vortex-array/src/arrays/piecewise_sequence/tests.rs index 1e4bb4329b2..82ead343f96 100644 --- a/vortex-array/src/arrays/piecewise_sequence/tests.rs +++ b/vortex-array/src/arrays/piecewise_sequence/tests.rs @@ -43,6 +43,20 @@ fn piecewise_indices( Ok(PiecewiseSequenceArray::try_new(starts, lengths, multipliers, len)?.into_array()) } +fn piecewise_indices_constant_length( + starts: impl IntoIterator, + length: u64, +) -> VortexResult { + let starts = starts.into_iter().collect::>(); + let length_usize: usize = length.as_(); + let len = starts.len() * length_usize; + let piece_count = starts.len(); + let starts = PrimitiveArray::from_iter(starts).into_array(); + let lengths = ConstantArray::new(length, piece_count).into_array(); + let multipliers = ConstantArray::new(1u64, piece_count).into_array(); + Ok(PiecewiseSequenceArray::try_new(starts, lengths, multipliers, len)?.into_array()) +} + #[test] fn materializes_piecewise_indices() -> VortexResult<()> { let starts = buffer![3u64, 15, 21].into_array(); @@ -280,6 +294,66 @@ fn varbin_take_consumes_piecewise_indices() -> VortexResult<()> { Ok(()) } +#[test] +fn contiguous_take_consumers_support_constant_piecewise_lengths() -> VortexResult<()> { + let mut ctx = array_session().create_execution_ctx(); + let indices = piecewise_indices_constant_length([1, 3], 2)?; + + let primitive = PrimitiveArray::from_iter(0i32..10).into_array(); + assert_arrays_eq!( + primitive.take(indices.clone())?, + PrimitiveArray::from_iter([1i32, 2, 3, 4]).into_array(), + &mut ctx + ); + + let bools = BoolArray::from_iter([false, true, false, true, false]).into_array(); + assert_arrays_eq!( + bools.take(indices.clone())?, + BoolArray::from_iter([true, false, true, false]).into_array(), + &mut ctx + ); + + let decimal_dtype = DecimalDType::new(19, 2); + let decimals = DecimalArray::from_iter([10i128, 20, 30, 40, 50], decimal_dtype).into_array(); + assert_arrays_eq!( + decimals.take(indices.clone())?, + DecimalArray::from_iter([20i128, 30, 40, 50], decimal_dtype).into_array(), + &mut ctx + ); + + let varbinview = VarBinViewArray::from_iter( + ["a", "bb", "ccc", "dddd", "eeeee"].map(Some), + DType::Utf8(Nullability::NonNullable), + ) + .into_array(); + assert_arrays_eq!( + varbinview.take(indices.clone())?, + VarBinViewArray::from_iter( + ["bb", "ccc", "dddd", "eeeee"].map(Some), + DType::Utf8(Nullability::NonNullable), + ) + .into_array(), + &mut ctx + ); + + let varbin = VarBinArray::from_iter( + ["a", "bb", "ccc", "dddd", "eeeee"].map(Some), + DType::Utf8(Nullability::NonNullable), + ) + .into_array(); + assert_arrays_eq!( + varbin.take(indices)?, + VarBinArray::from_iter( + ["bb", "ccc", "dddd", "eeeee"].map(Some), + DType::Utf8(Nullability::NonNullable), + ) + .into_array(), + &mut ctx + ); + + Ok(()) +} + #[test] fn fixed_size_list_take_builds_piecewise_element_indices() -> VortexResult<()> { let elements = PrimitiveArray::from_iter(0i32..12).into_array(); diff --git a/vortex-array/src/arrays/primitive/compute/take/mod.rs b/vortex-array/src/arrays/primitive/compute/take/mod.rs index c67a2c5d725..d0a49d971e5 100644 --- a/vortex-array/src/arrays/primitive/compute/take/mod.rs +++ b/vortex-array/src/arrays/primitive/compute/take/mod.rs @@ -21,8 +21,10 @@ use crate::arrays::PiecewiseSequence; use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; use crate::arrays::dict::TakeExecute; +use crate::arrays::piecewise_sequence::UnitMultiplierLengths; use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; use crate::arrays::piecewise_sequence::validate_index_ranges; +use crate::arrays::piecewise_sequence::validate_index_ranges_constant; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::IntegerPType; @@ -147,7 +149,14 @@ fn take_piecewise_sequence( }; let validity = array.validity()?.take(indices_ref)?; let output_len = indices_ref.len(); - let taken = take_piecewise_sequence_lengths(array, &starts, &lengths, validity, output_len)?; + let taken = match lengths { + UnitMultiplierLengths::Constant(length) => { + take_piecewise_sequence_constant_length(array, &starts, length, validity, output_len)? + } + UnitMultiplierLengths::Array(lengths) => { + take_piecewise_sequence_lengths(array, &starts, &lengths, validity, output_len)? + } + }; Ok(Some(taken)) } @@ -246,6 +255,62 @@ where Ok(values.freeze()) } +fn take_piecewise_sequence_constant_length( + array: ArrayView<'_, Primitive>, + starts: &PrimitiveArray, + length: usize, + validity: Validity, + output_len: usize, +) -> VortexResult { + match_each_native_ptype!(array.ptype(), |T| { + take_piecewise_sequence_constant_length_typed::( + array, starts, length, validity, output_len, + ) + }) +} + +fn take_piecewise_sequence_constant_length_typed( + array: ArrayView<'_, Primitive>, + starts: &PrimitiveArray, + length: usize, + validity: Validity, + output_len: usize, +) -> VortexResult +where + T: NativePType, +{ + match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + let values = primitive_piecewise_constant_length_values::( + array.as_slice::(), + starts.as_slice::(), + length, + output_len, + )?; + Ok(PrimitiveArray::new(values, validity).into_array()) + }) +} + +fn primitive_piecewise_constant_length_values( + source: &[T], + starts: &[S], + length: usize, + output_len: usize, +) -> VortexResult> +where + T: Copy, + S: UnsignedPType, +{ + validate_index_ranges_constant(source.len(), starts, length, output_len)?; + + let mut values = BufferMut::::with_capacity(output_len); + for &start in starts { + let start = start.as_(); + values.extend_from_slice(&source[start..start + length]); + } + + Ok(values.freeze()) +} + #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] #[cfg(test)] mod test { diff --git a/vortex-array/src/arrays/varbin/compute/take.rs b/vortex-array/src/arrays/varbin/compute/take.rs index 34d19863e20..a6326b6f61e 100644 --- a/vortex-array/src/arrays/varbin/compute/take.rs +++ b/vortex-array/src/arrays/varbin/compute/take.rs @@ -20,8 +20,10 @@ use crate::arrays::PrimitiveArray; use crate::arrays::VarBin; use crate::arrays::VarBinArray; use crate::arrays::dict::TakeExecute; +use crate::arrays::piecewise_sequence::UnitMultiplierLengths; use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; use crate::arrays::piecewise_sequence::validate_index_ranges; +use crate::arrays::piecewise_sequence::validate_index_ranges_constant; use crate::arrays::primitive::PrimitiveArrayExt; use crate::arrays::varbin::VarBinArrayExt; use crate::dtype::DType; @@ -138,50 +140,29 @@ fn take_piecewise_sequence( let offsets = array.offsets().clone().execute::(ctx)?; let out_offset_ptype = taken_offset_ptype(offsets.ptype()); let offsets = offsets.reinterpret_cast(offsets.ptype().to_unsigned()); - - let result = match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { - match offsets.ptype() { - PType::U8 => gather_piecewise_varbin::( - array.dtype().clone(), - offsets.as_slice::(), - array.bytes().as_slice(), - starts.as_slice::(), - lengths.as_slice::(), - indices_ref.len(), - out_offset_ptype, - ), - PType::U16 => gather_piecewise_varbin::( - array.dtype().clone(), - offsets.as_slice::(), - array.bytes().as_slice(), - starts.as_slice::(), - lengths.as_slice::(), - indices_ref.len(), - out_offset_ptype, - ), - PType::U32 => gather_piecewise_varbin::( - array.dtype().clone(), - offsets.as_slice::(), - array.bytes().as_slice(), - starts.as_slice::(), - lengths.as_slice::(), - indices_ref.len(), - out_offset_ptype, - ), - PType::U64 => gather_piecewise_varbin::( - array.dtype().clone(), - offsets.as_slice::(), - array.bytes().as_slice(), - starts.as_slice::(), - lengths.as_slice::(), - indices_ref.len(), - out_offset_ptype, - ), - _ => unreachable!("offsets were reinterpreted to an unsigned integer ptype"), - } - }) - })?; + let bytes = array.bytes(); + let data = bytes.as_slice(); + let dtype = array.dtype().clone(); + let output_len = indices_ref.len(); + + let result = match &lengths { + UnitMultiplierLengths::Constant(length) => gather_piecewise_varbin_constant_dispatch( + &starts, + *length, + &offsets, + data, + output_len, + out_offset_ptype, + )?, + UnitMultiplierLengths::Array(lengths) => gather_piecewise_varbin_dispatch( + &starts, + lengths, + &offsets, + data, + output_len, + out_offset_ptype, + )?, + }; let validity = array.validity()?.take(indices_ref)?; @@ -189,13 +170,8 @@ fn take_piecewise_sequence( // non-decreasing, and the copied data buffer has exactly the referenced byte length. unsafe { Ok(Some( - VarBinArray::new_unchecked( - result.offsets, - result.data.freeze(), - result.dtype, - validity, - ) - .into_array(), + VarBinArray::new_unchecked(result.offsets, result.data.freeze(), dtype, validity) + .into_array(), )) } } @@ -271,13 +247,243 @@ fn take( } struct GatheredPiecewiseVarBin { - dtype: DType, offsets: ArrayRef, data: ByteBufferMut, } +fn gather_piecewise_varbin_constant_dispatch( + starts: &PrimitiveArray, + length: usize, + offsets: &PrimitiveArray, + data: &[u8], + output_len: usize, + out_offset_ptype: PType, +) -> VortexResult { + match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + gather_piecewise_varbin_constant_start_dispatch::( + starts, + length, + offsets, + data, + output_len, + out_offset_ptype, + ) + }) +} + +fn gather_piecewise_varbin_constant_start_dispatch( + starts: &PrimitiveArray, + length: usize, + offsets: &PrimitiveArray, + data: &[u8], + output_len: usize, + out_offset_ptype: PType, +) -> VortexResult +where + S: UnsignedPType, +{ + match offsets.ptype() { + PType::U8 => gather_piecewise_varbin_constant_length::( + offsets.as_slice::(), + data, + starts.as_slice::(), + length, + output_len, + out_offset_ptype, + ), + PType::U16 => gather_piecewise_varbin_constant_length::( + offsets.as_slice::(), + data, + starts.as_slice::(), + length, + output_len, + out_offset_ptype, + ), + PType::U32 => gather_piecewise_varbin_constant_length::( + offsets.as_slice::(), + data, + starts.as_slice::(), + length, + output_len, + out_offset_ptype, + ), + PType::U64 => gather_piecewise_varbin_constant_length::( + offsets.as_slice::(), + data, + starts.as_slice::(), + length, + output_len, + out_offset_ptype, + ), + _ => unreachable!("offsets were reinterpreted to an unsigned integer ptype"), + } +} + +fn gather_piecewise_varbin_dispatch( + starts: &PrimitiveArray, + lengths: &PrimitiveArray, + offsets: &PrimitiveArray, + data: &[u8], + output_len: usize, + out_offset_ptype: PType, +) -> VortexResult { + match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + gather_piecewise_varbin_start_dispatch::( + starts, + lengths, + offsets, + data, + output_len, + out_offset_ptype, + ) + }) +} + +fn gather_piecewise_varbin_start_dispatch( + starts: &PrimitiveArray, + lengths: &PrimitiveArray, + offsets: &PrimitiveArray, + data: &[u8], + output_len: usize, + out_offset_ptype: PType, +) -> VortexResult +where + S: UnsignedPType, +{ + match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { + gather_piecewise_varbin_start_length_dispatch::( + starts, + lengths, + offsets, + data, + output_len, + out_offset_ptype, + ) + }) +} + +fn gather_piecewise_varbin_start_length_dispatch( + starts: &PrimitiveArray, + lengths: &PrimitiveArray, + offsets: &PrimitiveArray, + data: &[u8], + output_len: usize, + out_offset_ptype: PType, +) -> VortexResult +where + S: UnsignedPType, + L: UnsignedPType, +{ + match offsets.ptype() { + PType::U8 => gather_piecewise_varbin::( + offsets.as_slice::(), + data, + starts.as_slice::(), + lengths.as_slice::(), + output_len, + out_offset_ptype, + ), + PType::U16 => gather_piecewise_varbin::( + offsets.as_slice::(), + data, + starts.as_slice::(), + lengths.as_slice::(), + output_len, + out_offset_ptype, + ), + PType::U32 => gather_piecewise_varbin::( + offsets.as_slice::(), + data, + starts.as_slice::(), + lengths.as_slice::(), + output_len, + out_offset_ptype, + ), + PType::U64 => gather_piecewise_varbin::( + offsets.as_slice::(), + data, + starts.as_slice::(), + lengths.as_slice::(), + output_len, + out_offset_ptype, + ), + _ => unreachable!("offsets were reinterpreted to an unsigned integer ptype"), + } +} + +fn gather_piecewise_varbin_constant_length( + offsets: &[Offset], + data: &[u8], + starts: &[S], + length: usize, + output_len: usize, + out_offset_ptype: PType, +) -> VortexResult +where + S: UnsignedPType, + Offset: IntegerPType, + NewOffset: IntegerPType, +{ + validate_index_ranges_constant(offsets.len() - 1, starts, length, output_len)?; + + let mut new_offsets = BufferMut::::with_capacity(output_len + 1); + new_offsets.push(NewOffset::zero()); + let mut output_bytes = 0usize; + + for &start in starts { + let start = start.as_(); + let end = start + length; + if length == 0 { + continue; + } + + let byte_start = offsets[start].as_(); + let byte_end = offsets[end].as_(); + vortex_ensure!( + byte_start <= byte_end && byte_end <= data.len(), + "VarBin offsets range {byte_start}..{byte_end} exceeds data length {}", + data.len() + ); + + for &offset in &offsets[start + 1..=end] { + let offset = offset.as_(); + let relative = offset.checked_sub(byte_start).ok_or_else(|| { + vortex_err!("VarBin offsets are not monotonic at offset {offset}") + })?; + let output_offset = output_bytes.checked_add(relative).ok_or_else(|| { + vortex_err!("PiecewiseSequence VarBin output byte length overflow") + })?; + new_offsets.push(new_offset_value::(output_offset)?); + } + + output_bytes = output_bytes + .checked_add(byte_end - byte_start) + .ok_or_else(|| vortex_err!("PiecewiseSequence VarBin output byte length overflow"))?; + } + + let mut new_data = ByteBufferMut::with_capacity(output_bytes); + for &start in starts { + let start = start.as_(); + let end = start + length; + if length == 0 { + continue; + } + + let byte_start = offsets[start].as_(); + let byte_end = offsets[end].as_(); + new_data.extend_from_slice(&data[byte_start..byte_end]); + } + + let offsets = PrimitiveArray::new(new_offsets.freeze(), Validity::NonNullable) + .reinterpret_cast(out_offset_ptype) + .into_array(); + Ok(GatheredPiecewiseVarBin { + offsets, + data: new_data, + }) +} + fn gather_piecewise_varbin( - dtype: DType, offsets: &[Offset], data: &[u8], starts: &[S], @@ -347,7 +553,6 @@ where .reinterpret_cast(out_offset_ptype) .into_array(); Ok(GatheredPiecewiseVarBin { - dtype, offsets, data: new_data, }) diff --git a/vortex-array/src/arrays/varbinview/compute/take.rs b/vortex-array/src/arrays/varbinview/compute/take.rs index dd38b45929d..0197a47722a 100644 --- a/vortex-array/src/arrays/varbinview/compute/take.rs +++ b/vortex-array/src/arrays/varbinview/compute/take.rs @@ -20,8 +20,10 @@ use crate::arrays::PrimitiveArray; use crate::arrays::VarBinView; use crate::arrays::VarBinViewArray; use crate::arrays::dict::TakeExecute; +use crate::arrays::piecewise_sequence::UnitMultiplierLengths; use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; use crate::arrays::piecewise_sequence::validate_index_ranges; +use crate::arrays::piecewise_sequence::validate_index_ranges_constant; use crate::arrays::varbinview::BinaryView; use crate::buffer::BufferHandle; use crate::dtype::UnsignedPType; @@ -79,16 +81,32 @@ fn take_piecewise_sequence( let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { return Ok(None); }; - let views = match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { - gather_piecewise_views( - array.views(), - starts.as_slice::(), - lengths.as_slice::(), - indices_ref.len(), - )? - }) - }); + let source = array.views(); + let output_len = indices_ref.len(); + let views = match &lengths { + UnitMultiplierLengths::Constant(length) => { + match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + gather_piecewise_views_constant_length( + source, + starts.as_slice::(), + *length, + output_len, + )? + }) + } + UnitMultiplierLengths::Array(lengths) => { + match_each_unsigned_integer_ptype!(starts.ptype(), |S| { + match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { + gather_piecewise_views( + source, + starts.as_slice::(), + lengths.as_slice::(), + output_len, + )? + }) + }) + } + }; let validity = array.validity()?.take(indices_ref)?; // SAFETY: ranges were validated against the source views, and copied views still reference the @@ -134,6 +152,26 @@ fn take_views>( } } +fn gather_piecewise_views_constant_length( + source: &[BinaryView], + starts: &[S], + length: usize, + output_len: usize, +) -> VortexResult> +where + S: UnsignedPType, +{ + validate_index_ranges_constant(source.len(), starts, length, output_len)?; + + let mut views = BufferMut::::with_capacity(output_len); + for &start in starts { + let start = start.as_(); + views.extend_from_slice(&source[start..start + length]); + } + + Ok(views.freeze()) +} + fn gather_piecewise_views( source: &[BinaryView], starts: &[S], From fc9b6407211013c45d0692bc32077f17fea247c8 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Fri, 17 Jul 2026 11:35:29 -0400 Subject: [PATCH 09/20] Rename contiguous range take helpers Signed-off-by: Daniel King --- vortex-array/src/arrays/bool/compute/take.rs | 12 ++--- .../src/arrays/decimal/compute/take.rs | 36 +++++++-------- .../src/arrays/primitive/compute/take/mod.rs | 36 +++++++-------- .../src/arrays/varbin/compute/take.rs | 44 +++++++++---------- .../src/arrays/varbinview/compute/take.rs | 12 ++--- 5 files changed, 66 insertions(+), 74 deletions(-) diff --git a/vortex-array/src/arrays/bool/compute/take.rs b/vortex-array/src/arrays/bool/compute/take.rs index a467e19175f..2accc52be42 100644 --- a/vortex-array/src/arrays/bool/compute/take.rs +++ b/vortex-array/src/arrays/bool/compute/take.rs @@ -38,7 +38,7 @@ impl TakeExecute for Bool { ctx: &mut ExecutionCtx, ) -> VortexResult> { if let Some(piecewise_indices) = indices.as_opt::() - && let Some(taken) = take_piecewise_sequence(array, piecewise_indices, indices, ctx)? + && let Some(taken) = take_contiguous_ranges(array, piecewise_indices, indices, ctx)? { return Ok(Some(taken)); } @@ -69,7 +69,7 @@ impl TakeExecute for Bool { } } -fn take_piecewise_sequence( +fn take_contiguous_ranges( array: ArrayView<'_, Bool>, indices: ArrayView<'_, PiecewiseSequence>, indices_ref: &ArrayRef, @@ -83,7 +83,7 @@ fn take_piecewise_sequence( let buffer = match &lengths { UnitMultiplierLengths::Constant(length) => { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - take_piecewise_bits_constant_length( + take_bit_slices_constant_length( &source, starts.as_slice::(), *length, @@ -94,7 +94,7 @@ fn take_piecewise_sequence( UnitMultiplierLengths::Array(lengths) => { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { - take_piecewise_bits( + take_bit_slices( &source, starts.as_slice::(), lengths.as_slice::(), @@ -137,7 +137,7 @@ fn take_bool_impl>(bools: BitBufferView<'_>, indices: &[I] }) } -fn take_piecewise_bits_constant_length( +fn take_bit_slices_constant_length( source: &BitBuffer, starts: &[S], length: usize, @@ -157,7 +157,7 @@ where Ok(values.freeze()) } -fn take_piecewise_bits( +fn take_bit_slices( source: &BitBuffer, starts: &[S], lengths: &[L], diff --git a/vortex-array/src/arrays/decimal/compute/take.rs b/vortex-array/src/arrays/decimal/compute/take.rs index a2d508fd31e..fb4518fdc85 100644 --- a/vortex-array/src/arrays/decimal/compute/take.rs +++ b/vortex-array/src/arrays/decimal/compute/take.rs @@ -34,7 +34,7 @@ impl TakeExecute for Decimal { ctx: &mut ExecutionCtx, ) -> VortexResult> { if let Some(piecewise_indices) = indices.as_opt::() - && let Some(taken) = take_piecewise_sequence(array, piecewise_indices, indices, ctx)? + && let Some(taken) = take_contiguous_ranges(array, piecewise_indices, indices, ctx)? { return Ok(Some(taken)); } @@ -58,7 +58,7 @@ impl TakeExecute for Decimal { } } -fn take_piecewise_sequence( +fn take_contiguous_ranges( array: ArrayView<'_, Decimal>, indices: ArrayView<'_, PiecewiseSequence>, indices_ref: &ArrayRef, @@ -71,16 +71,16 @@ fn take_piecewise_sequence( let output_len = indices_ref.len(); let taken = match lengths { UnitMultiplierLengths::Constant(length) => { - take_piecewise_sequence_constant_length(array, &starts, length, validity, output_len)? + take_slices_constant_length(array, &starts, length, validity, output_len)? } UnitMultiplierLengths::Array(lengths) => { - take_piecewise_sequence_lengths(array, &starts, &lengths, validity, output_len)? + take_slices(array, &starts, &lengths, validity, output_len)? } }; Ok(Some(taken)) } -fn take_piecewise_sequence_constant_length( +fn take_slices_constant_length( array: ArrayView<'_, Decimal>, starts: &PrimitiveArray, length: usize, @@ -88,13 +88,11 @@ fn take_piecewise_sequence_constant_length( output_len: usize, ) -> VortexResult { match_each_decimal_value_type!(array.values_type(), |D| { - take_piecewise_sequence_constant_length_typed::( - array, starts, length, validity, output_len, - ) + take_slices_constant_length_typed::(array, starts, length, validity, output_len) }) } -fn take_piecewise_sequence_constant_length_typed( +fn take_slices_constant_length_typed( array: ArrayView<'_, Decimal>, starts: &PrimitiveArray, length: usize, @@ -105,7 +103,7 @@ where D: NativeDecimalType, { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - let values = take_piecewise_constant_length_to_buffer::( + let values = take_slices_constant_length_to_buffer::( starts.as_slice::(), length, array.buffer::().as_slice(), @@ -120,7 +118,7 @@ where }) } -fn take_piecewise_sequence_lengths( +fn take_slices( array: ArrayView<'_, Decimal>, starts: &PrimitiveArray, lengths: &PrimitiveArray, @@ -128,11 +126,11 @@ fn take_piecewise_sequence_lengths( output_len: usize, ) -> VortexResult { match_each_decimal_value_type!(array.values_type(), |D| { - take_piecewise_sequence_lengths_typed::(array, starts, lengths, validity, output_len) + take_slices_typed::(array, starts, lengths, validity, output_len) }) } -fn take_piecewise_sequence_lengths_typed( +fn take_slices_typed( array: ArrayView<'_, Decimal>, starts: &PrimitiveArray, lengths: &PrimitiveArray, @@ -143,13 +141,11 @@ where D: NativeDecimalType, { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - take_piecewise_sequence_lengths_start_typed::( - array, starts, lengths, validity, output_len, - ) + take_slices_start_typed::(array, starts, lengths, validity, output_len) }) } -fn take_piecewise_sequence_lengths_start_typed( +fn take_slices_start_typed( array: ArrayView<'_, Decimal>, starts: &PrimitiveArray, lengths: &PrimitiveArray, @@ -161,7 +157,7 @@ where S: UnsignedPType, { match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { - let values = take_piecewise_to_buffer::( + let values = take_slices_to_buffer::( starts.as_slice::(), lengths.as_slice::(), array.buffer::().as_slice(), @@ -180,7 +176,7 @@ fn take_to_buffer(indices: &[I], values: indices.iter().map(|idx| values[idx.as_()]).collect() } -fn take_piecewise_constant_length_to_buffer( +fn take_slices_constant_length_to_buffer( starts: &[S], length: usize, values: &[T], @@ -201,7 +197,7 @@ where Ok(result.freeze()) } -fn take_piecewise_to_buffer( +fn take_slices_to_buffer( starts: &[S], lengths: &[L], values: &[T], diff --git a/vortex-array/src/arrays/primitive/compute/take/mod.rs b/vortex-array/src/arrays/primitive/compute/take/mod.rs index d0a49d971e5..2e2aa0e2397 100644 --- a/vortex-array/src/arrays/primitive/compute/take/mod.rs +++ b/vortex-array/src/arrays/primitive/compute/take/mod.rs @@ -89,7 +89,7 @@ impl TakeExecute for Primitive { ctx: &mut ExecutionCtx, ) -> VortexResult> { if let Some(piecewise_indices) = indices.as_opt::() - && let Some(taken) = take_piecewise_sequence(array, piecewise_indices, indices, ctx)? + && let Some(taken) = take_contiguous_ranges(array, piecewise_indices, indices, ctx)? { return Ok(Some(taken)); } @@ -138,7 +138,7 @@ impl TakeExecute for Primitive { } } -fn take_piecewise_sequence( +fn take_contiguous_ranges( array: ArrayView<'_, Primitive>, indices: ArrayView<'_, PiecewiseSequence>, indices_ref: &ArrayRef, @@ -151,10 +151,10 @@ fn take_piecewise_sequence( let output_len = indices_ref.len(); let taken = match lengths { UnitMultiplierLengths::Constant(length) => { - take_piecewise_sequence_constant_length(array, &starts, length, validity, output_len)? + take_slices_constant_length(array, &starts, length, validity, output_len)? } UnitMultiplierLengths::Array(lengths) => { - take_piecewise_sequence_lengths(array, &starts, &lengths, validity, output_len)? + take_slices(array, &starts, &lengths, validity, output_len)? } }; Ok(Some(taken)) @@ -181,7 +181,7 @@ fn take_primitive_scalar(buffer: &[T], indices: &[I]) result.freeze() } -fn take_piecewise_sequence_lengths( +fn take_slices( array: ArrayView<'_, Primitive>, starts: &PrimitiveArray, lengths: &PrimitiveArray, @@ -189,11 +189,11 @@ fn take_piecewise_sequence_lengths( output_len: usize, ) -> VortexResult { match_each_native_ptype!(array.ptype(), |T| { - take_piecewise_sequence_lengths_typed::(array, starts, lengths, validity, output_len) + take_slices_typed::(array, starts, lengths, validity, output_len) }) } -fn take_piecewise_sequence_lengths_typed( +fn take_slices_typed( array: ArrayView<'_, Primitive>, starts: &PrimitiveArray, lengths: &PrimitiveArray, @@ -204,13 +204,11 @@ where T: NativePType, { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - take_piecewise_sequence_lengths_start_typed::( - array, starts, lengths, validity, output_len, - ) + take_slices_start_typed::(array, starts, lengths, validity, output_len) }) } -fn take_piecewise_sequence_lengths_start_typed( +fn take_slices_start_typed( array: ArrayView<'_, Primitive>, starts: &PrimitiveArray, lengths: &PrimitiveArray, @@ -222,7 +220,7 @@ where S: UnsignedPType, { match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { - let values = primitive_piecewise_values::( + let values = take_slices_to_buffer::( array.as_slice::(), starts.as_slice::(), lengths.as_slice::(), @@ -232,7 +230,7 @@ where }) } -fn primitive_piecewise_values( +fn take_slices_to_buffer( source: &[T], starts: &[S], lengths: &[L], @@ -255,7 +253,7 @@ where Ok(values.freeze()) } -fn take_piecewise_sequence_constant_length( +fn take_slices_constant_length( array: ArrayView<'_, Primitive>, starts: &PrimitiveArray, length: usize, @@ -263,13 +261,11 @@ fn take_piecewise_sequence_constant_length( output_len: usize, ) -> VortexResult { match_each_native_ptype!(array.ptype(), |T| { - take_piecewise_sequence_constant_length_typed::( - array, starts, length, validity, output_len, - ) + take_slices_constant_length_typed::(array, starts, length, validity, output_len) }) } -fn take_piecewise_sequence_constant_length_typed( +fn take_slices_constant_length_typed( array: ArrayView<'_, Primitive>, starts: &PrimitiveArray, length: usize, @@ -280,7 +276,7 @@ where T: NativePType, { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - let values = primitive_piecewise_constant_length_values::( + let values = take_slices_constant_length_to_buffer::( array.as_slice::(), starts.as_slice::(), length, @@ -290,7 +286,7 @@ where }) } -fn primitive_piecewise_constant_length_values( +fn take_slices_constant_length_to_buffer( source: &[T], starts: &[S], length: usize, diff --git a/vortex-array/src/arrays/varbin/compute/take.rs b/vortex-array/src/arrays/varbin/compute/take.rs index a6326b6f61e..b24ab319598 100644 --- a/vortex-array/src/arrays/varbin/compute/take.rs +++ b/vortex-array/src/arrays/varbin/compute/take.rs @@ -53,7 +53,7 @@ impl TakeExecute for VarBin { ctx: &mut ExecutionCtx, ) -> VortexResult> { if let Some(piecewise_indices) = indices.as_opt::() - && let Some(taken) = take_piecewise_sequence(array, piecewise_indices, indices, ctx)? + && let Some(taken) = take_contiguous_ranges(array, piecewise_indices, indices, ctx)? { return Ok(Some(taken)); } @@ -128,7 +128,7 @@ impl TakeExecute for VarBin { } } -fn take_piecewise_sequence( +fn take_contiguous_ranges( array: ArrayView<'_, VarBin>, indices: ArrayView<'_, PiecewiseSequence>, indices_ref: &ArrayRef, @@ -146,7 +146,7 @@ fn take_piecewise_sequence( let output_len = indices_ref.len(); let result = match &lengths { - UnitMultiplierLengths::Constant(length) => gather_piecewise_varbin_constant_dispatch( + UnitMultiplierLengths::Constant(length) => gather_slices_constant_dispatch( &starts, *length, &offsets, @@ -154,7 +154,7 @@ fn take_piecewise_sequence( output_len, out_offset_ptype, )?, - UnitMultiplierLengths::Array(lengths) => gather_piecewise_varbin_dispatch( + UnitMultiplierLengths::Array(lengths) => gather_slices_dispatch( &starts, lengths, &offsets, @@ -251,7 +251,7 @@ struct GatheredPiecewiseVarBin { data: ByteBufferMut, } -fn gather_piecewise_varbin_constant_dispatch( +fn gather_slices_constant_dispatch( starts: &PrimitiveArray, length: usize, offsets: &PrimitiveArray, @@ -260,7 +260,7 @@ fn gather_piecewise_varbin_constant_dispatch( out_offset_ptype: PType, ) -> VortexResult { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - gather_piecewise_varbin_constant_start_dispatch::( + gather_slices_constant_start_dispatch::( starts, length, offsets, @@ -271,7 +271,7 @@ fn gather_piecewise_varbin_constant_dispatch( }) } -fn gather_piecewise_varbin_constant_start_dispatch( +fn gather_slices_constant_start_dispatch( starts: &PrimitiveArray, length: usize, offsets: &PrimitiveArray, @@ -283,7 +283,7 @@ where S: UnsignedPType, { match offsets.ptype() { - PType::U8 => gather_piecewise_varbin_constant_length::( + PType::U8 => gather_slices_constant_length::( offsets.as_slice::(), data, starts.as_slice::(), @@ -291,7 +291,7 @@ where output_len, out_offset_ptype, ), - PType::U16 => gather_piecewise_varbin_constant_length::( + PType::U16 => gather_slices_constant_length::( offsets.as_slice::(), data, starts.as_slice::(), @@ -299,7 +299,7 @@ where output_len, out_offset_ptype, ), - PType::U32 => gather_piecewise_varbin_constant_length::( + PType::U32 => gather_slices_constant_length::( offsets.as_slice::(), data, starts.as_slice::(), @@ -307,7 +307,7 @@ where output_len, out_offset_ptype, ), - PType::U64 => gather_piecewise_varbin_constant_length::( + PType::U64 => gather_slices_constant_length::( offsets.as_slice::(), data, starts.as_slice::(), @@ -319,7 +319,7 @@ where } } -fn gather_piecewise_varbin_dispatch( +fn gather_slices_dispatch( starts: &PrimitiveArray, lengths: &PrimitiveArray, offsets: &PrimitiveArray, @@ -328,7 +328,7 @@ fn gather_piecewise_varbin_dispatch( out_offset_ptype: PType, ) -> VortexResult { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - gather_piecewise_varbin_start_dispatch::( + gather_slices_start_dispatch::( starts, lengths, offsets, @@ -339,7 +339,7 @@ fn gather_piecewise_varbin_dispatch( }) } -fn gather_piecewise_varbin_start_dispatch( +fn gather_slices_start_dispatch( starts: &PrimitiveArray, lengths: &PrimitiveArray, offsets: &PrimitiveArray, @@ -351,7 +351,7 @@ where S: UnsignedPType, { match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { - gather_piecewise_varbin_start_length_dispatch::( + gather_slices_start_length_dispatch::( starts, lengths, offsets, @@ -362,7 +362,7 @@ where }) } -fn gather_piecewise_varbin_start_length_dispatch( +fn gather_slices_start_length_dispatch( starts: &PrimitiveArray, lengths: &PrimitiveArray, offsets: &PrimitiveArray, @@ -375,7 +375,7 @@ where L: UnsignedPType, { match offsets.ptype() { - PType::U8 => gather_piecewise_varbin::( + PType::U8 => gather_slices::( offsets.as_slice::(), data, starts.as_slice::(), @@ -383,7 +383,7 @@ where output_len, out_offset_ptype, ), - PType::U16 => gather_piecewise_varbin::( + PType::U16 => gather_slices::( offsets.as_slice::(), data, starts.as_slice::(), @@ -391,7 +391,7 @@ where output_len, out_offset_ptype, ), - PType::U32 => gather_piecewise_varbin::( + PType::U32 => gather_slices::( offsets.as_slice::(), data, starts.as_slice::(), @@ -399,7 +399,7 @@ where output_len, out_offset_ptype, ), - PType::U64 => gather_piecewise_varbin::( + PType::U64 => gather_slices::( offsets.as_slice::(), data, starts.as_slice::(), @@ -411,7 +411,7 @@ where } } -fn gather_piecewise_varbin_constant_length( +fn gather_slices_constant_length( offsets: &[Offset], data: &[u8], starts: &[S], @@ -483,7 +483,7 @@ where }) } -fn gather_piecewise_varbin( +fn gather_slices( offsets: &[Offset], data: &[u8], starts: &[S], diff --git a/vortex-array/src/arrays/varbinview/compute/take.rs b/vortex-array/src/arrays/varbinview/compute/take.rs index 0197a47722a..d347a72ee4b 100644 --- a/vortex-array/src/arrays/varbinview/compute/take.rs +++ b/vortex-array/src/arrays/varbinview/compute/take.rs @@ -39,7 +39,7 @@ impl TakeExecute for VarBinView { ctx: &mut ExecutionCtx, ) -> VortexResult> { if let Some(piecewise_indices) = indices.as_opt::() - && let Some(taken) = take_piecewise_sequence(array, piecewise_indices, indices, ctx)? + && let Some(taken) = take_contiguous_ranges(array, piecewise_indices, indices, ctx)? { return Ok(Some(taken)); } @@ -72,7 +72,7 @@ impl TakeExecute for VarBinView { } } -fn take_piecewise_sequence( +fn take_contiguous_ranges( array: ArrayView<'_, VarBinView>, indices: ArrayView<'_, PiecewiseSequence>, indices_ref: &ArrayRef, @@ -86,7 +86,7 @@ fn take_piecewise_sequence( let views = match &lengths { UnitMultiplierLengths::Constant(length) => { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - gather_piecewise_views_constant_length( + gather_view_slices_constant_length( source, starts.as_slice::(), *length, @@ -97,7 +97,7 @@ fn take_piecewise_sequence( UnitMultiplierLengths::Array(lengths) => { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { - gather_piecewise_views( + gather_view_slices( source, starts.as_slice::(), lengths.as_slice::(), @@ -152,7 +152,7 @@ fn take_views>( } } -fn gather_piecewise_views_constant_length( +fn gather_view_slices_constant_length( source: &[BinaryView], starts: &[S], length: usize, @@ -172,7 +172,7 @@ where Ok(views.freeze()) } -fn gather_piecewise_views( +fn gather_view_slices( source: &[BinaryView], starts: &[S], lengths: &[L], From 2e4d1c84b8167abd659ba9be37453e09d64ce0a6 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Thu, 16 Jul 2026 16:48:53 -0400 Subject: [PATCH 10/20] Optimize FixedSizeList take results Signed-off-by: Daniel King --- .../src/arrays/fixed_size_list/compute/take.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/vortex-array/src/arrays/fixed_size_list/compute/take.rs b/vortex-array/src/arrays/fixed_size_list/compute/take.rs index b2533d132b9..9a8cc63ec2d 100644 --- a/vortex-array/src/arrays/fixed_size_list/compute/take.rs +++ b/vortex-array/src/arrays/fixed_size_list/compute/take.rs @@ -27,6 +27,7 @@ use crate::dtype::IntegerPType; use crate::dtype::Nullability; use crate::executor::ExecutionCtx; use crate::match_each_integer_ptype; +use crate::optimizer::ArrayOptimizer; use crate::validity::Validity; /// Take implementation for [`FixedSizeListArray`]. @@ -79,10 +80,11 @@ fn take_empty_fsl( // SAFETY: empty output needs no child values; otherwise the index validity mask proves every // output row is null. Placeholder child elements have the exact length required by FSL. - Ok(unsafe { + unsafe { FixedSizeListArray::new_unchecked(new_elements, array.list_size(), new_validity, new_len) } - .into_array()) + .into_array() + .optimize_ctx(ctx.session()) } fn take_non_empty_fsl( @@ -136,7 +138,7 @@ fn take_non_empty_degenerate_fsl( // SAFETY: degenerate FSL inputs have no elements, valid index payloads were checked against // the source length, and `Validity::take` produces validity for `new_len`. - Ok(unsafe { + unsafe { FixedSizeListArray::new_unchecked( array.elements().clone(), array.list_size(), @@ -144,7 +146,8 @@ fn take_non_empty_degenerate_fsl( new_len, ) } - .into_array()) + .into_array() + .optimize_ctx(ctx.session()) } fn take_non_empty_non_degenerate_fsl( @@ -167,10 +170,11 @@ fn take_non_empty_non_degenerate_fsl( // SAFETY: `new_elements` has `new_len * list_size` elements. `new_validity` is either // non-nullable or was produced by `Validity::take` for `new_len`. - Ok(unsafe { + unsafe { FixedSizeListArray::new_unchecked(new_elements, array.list_size(), new_validity, new_len) } - .into_array()) + .into_array() + .optimize_ctx(ctx.session()) } fn take_non_empty_non_degenerate_elements( From 1096c84002ffc19e57fa98167a18b35bd68ef40f Mon Sep 17 00:00:00 2001 From: Daniel King Date: Fri, 17 Jul 2026 14:39:07 -0400 Subject: [PATCH 11/20] Inline PiecewiseSequence range length checks Signed-off-by: Daniel King --- vortex-array/src/arrays/bool/compute/take.rs | 33 ++++++++-- .../src/arrays/decimal/compute/take.rs | 33 ++++++++-- .../src/arrays/piecewise_sequence/mod.rs | 65 ------------------- .../src/arrays/primitive/compute/take/mod.rs | 33 ++++++++-- .../src/arrays/varbin/compute/take.rs | 37 ++++++++--- .../src/arrays/varbinview/compute/take.rs | 33 ++++++++-- 6 files changed, 132 insertions(+), 102 deletions(-) diff --git a/vortex-array/src/arrays/bool/compute/take.rs b/vortex-array/src/arrays/bool/compute/take.rs index 2accc52be42..8e43a1a1e0b 100644 --- a/vortex-array/src/arrays/bool/compute/take.rs +++ b/vortex-array/src/arrays/bool/compute/take.rs @@ -8,6 +8,8 @@ use vortex_buffer::BitBufferMut; use vortex_buffer::BitBufferView; use vortex_buffer::get_bit; use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; use vortex_mask::Mask; use crate::ArrayRef; @@ -22,8 +24,6 @@ use crate::arrays::bool::BoolArrayExt; use crate::arrays::dict::TakeExecute; use crate::arrays::piecewise_sequence::UnitMultiplierLengths; use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; -use crate::arrays::piecewise_sequence::validate_index_ranges; -use crate::arrays::piecewise_sequence::validate_index_ranges_constant; use crate::builtins::ArrayBuiltins; use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; @@ -146,12 +146,22 @@ fn take_bit_slices_constant_length( where S: UnsignedPType, { - validate_index_ranges_constant(source.len(), starts, length, output_len)?; + let computed_len = starts + .len() + .checked_mul(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; + vortex_ensure!( + computed_len == output_len, + "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + ); let mut values = BitBufferMut::with_capacity(output_len); for &start in starts { let start = start.as_(); - values.append_buffer(&source.slice(start..start + length)); + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; + values.append_buffer(&source.slice(start..end)); } Ok(values.freeze()) @@ -167,15 +177,24 @@ where S: UnsignedPType, L: UnsignedPType, { - validate_index_ranges(source.len(), starts, lengths, output_len)?; - let mut values = BitBufferMut::with_capacity(output_len); + let mut computed_len = 0usize; for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - values.append_buffer(&source.slice(start..start + length)); + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; + computed_len = computed_len + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; + values.append_buffer(&source.slice(start..end)); } + vortex_ensure!( + computed_len == output_len, + "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + ); Ok(values.freeze()) } diff --git a/vortex-array/src/arrays/decimal/compute/take.rs b/vortex-array/src/arrays/decimal/compute/take.rs index fb4518fdc85..0bb354b4a6a 100644 --- a/vortex-array/src/arrays/decimal/compute/take.rs +++ b/vortex-array/src/arrays/decimal/compute/take.rs @@ -5,6 +5,8 @@ use itertools::Itertools as _; use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; use crate::ArrayRef; use crate::IntoArray; @@ -16,8 +18,6 @@ use crate::arrays::PrimitiveArray; use crate::arrays::dict::TakeExecute; use crate::arrays::piecewise_sequence::UnitMultiplierLengths; use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; -use crate::arrays::piecewise_sequence::validate_index_ranges; -use crate::arrays::piecewise_sequence::validate_index_ranges_constant; use crate::dtype::IntegerPType; use crate::dtype::NativeDecimalType; use crate::dtype::UnsignedPType; @@ -186,12 +186,22 @@ where S: UnsignedPType, T: NativeDecimalType, { - validate_index_ranges_constant(values.len(), starts, length, output_len)?; + let computed_len = starts + .len() + .checked_mul(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; + vortex_ensure!( + computed_len == output_len, + "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + ); let mut result = BufferMut::::with_capacity(output_len); for &start in starts { let start = start.as_(); - result.extend_from_slice(&values[start..start + length]); + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; + result.extend_from_slice(&values[start..end]); } Ok(result.freeze()) @@ -208,15 +218,24 @@ where L: UnsignedPType, T: NativeDecimalType, { - validate_index_ranges(values.len(), starts, lengths, output_len)?; - let mut result = BufferMut::::with_capacity(output_len); + let mut computed_len = 0usize; for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - result.extend_from_slice(&values[start..start + length]); + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; + computed_len = computed_len + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; + result.extend_from_slice(&values[start..end]); } + vortex_ensure!( + computed_len == output_len, + "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + ); Ok(result.freeze()) } diff --git a/vortex-array/src/arrays/piecewise_sequence/mod.rs b/vortex-array/src/arrays/piecewise_sequence/mod.rs index e5043e42e16..cdc5649c9f2 100644 --- a/vortex-array/src/arrays/piecewise_sequence/mod.rs +++ b/vortex-array/src/arrays/piecewise_sequence/mod.rs @@ -134,38 +134,6 @@ fn check_index_array(name: &str, array: &ArrayRef) -> VortexResult<()> { Ok(()) } -pub(crate) fn validate_index_ranges_constant( - source_len: usize, - starts: &[S], - length: usize, - output_len: usize, -) -> VortexResult<()> -where - S: UnsignedPType, -{ - let computed_len = starts - .len() - .checked_mul(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; - vortex_ensure!( - computed_len == output_len, - "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" - ); - - for &start in starts { - let start: usize = start.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; - vortex_ensure!( - end <= source_len, - "PiecewiseSequenceArray range {start}..{end} exceeds source length {source_len}" - ); - } - - Ok(()) -} - pub(crate) fn materialize_ranges( starts: &PrimitiveArray, lengths: &PrimitiveArray, @@ -210,36 +178,3 @@ where } Ok(values) } - -pub(crate) fn validate_index_ranges( - source_len: usize, - starts: &[S], - lengths: &[L], - output_len: usize, -) -> VortexResult<()> -where - S: UnsignedPType, - L: UnsignedPType, -{ - let mut computed_len = 0usize; - for (&start, &length) in starts.iter().zip_eq(lengths) { - let start: usize = start.as_(); - let length: usize = length.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; - vortex_ensure!( - end <= source_len, - "PiecewiseSequenceArray range {start}..{end} exceeds source length {source_len}" - ); - computed_len = computed_len - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; - } - - vortex_ensure!( - computed_len == output_len, - "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" - ); - Ok(()) -} diff --git a/vortex-array/src/arrays/primitive/compute/take/mod.rs b/vortex-array/src/arrays/primitive/compute/take/mod.rs index 2e2aa0e2397..58c9d271cff 100644 --- a/vortex-array/src/arrays/primitive/compute/take/mod.rs +++ b/vortex-array/src/arrays/primitive/compute/take/mod.rs @@ -11,6 +11,8 @@ use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_error::VortexResult; use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; use vortex_mask::Mask; use crate::ArrayRef; @@ -23,8 +25,6 @@ use crate::arrays::PrimitiveArray; use crate::arrays::dict::TakeExecute; use crate::arrays::piecewise_sequence::UnitMultiplierLengths; use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; -use crate::arrays::piecewise_sequence::validate_index_ranges; -use crate::arrays::piecewise_sequence::validate_index_ranges_constant; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::IntegerPType; @@ -241,15 +241,24 @@ where S: UnsignedPType, L: UnsignedPType, { - validate_index_ranges(source.len(), starts, lengths, output_len)?; - let mut values = BufferMut::::with_capacity(output_len); + let mut computed_len = 0usize; for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - values.extend_from_slice(&source[start..start + length]); + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; + computed_len = computed_len + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; + values.extend_from_slice(&source[start..end]); } + vortex_ensure!( + computed_len == output_len, + "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + ); Ok(values.freeze()) } @@ -296,12 +305,22 @@ where T: Copy, S: UnsignedPType, { - validate_index_ranges_constant(source.len(), starts, length, output_len)?; + let computed_len = starts + .len() + .checked_mul(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; + vortex_ensure!( + computed_len == output_len, + "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + ); let mut values = BufferMut::::with_capacity(output_len); for &start in starts { let start = start.as_(); - values.extend_from_slice(&source[start..start + length]); + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; + values.extend_from_slice(&source[start..end]); } Ok(values.freeze()) diff --git a/vortex-array/src/arrays/varbin/compute/take.rs b/vortex-array/src/arrays/varbin/compute/take.rs index b24ab319598..416a194397a 100644 --- a/vortex-array/src/arrays/varbin/compute/take.rs +++ b/vortex-array/src/arrays/varbin/compute/take.rs @@ -22,8 +22,6 @@ use crate::arrays::VarBinArray; use crate::arrays::dict::TakeExecute; use crate::arrays::piecewise_sequence::UnitMultiplierLengths; use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; -use crate::arrays::piecewise_sequence::validate_index_ranges; -use crate::arrays::piecewise_sequence::validate_index_ranges_constant; use crate::arrays::primitive::PrimitiveArrayExt; use crate::arrays::varbin::VarBinArrayExt; use crate::dtype::DType; @@ -424,7 +422,14 @@ where Offset: IntegerPType, NewOffset: IntegerPType, { - validate_index_ranges_constant(offsets.len() - 1, starts, length, output_len)?; + let computed_len = starts + .len() + .checked_mul(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; + vortex_ensure!( + computed_len == output_len, + "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + ); let mut new_offsets = BufferMut::::with_capacity(output_len + 1); new_offsets.push(NewOffset::zero()); @@ -432,7 +437,9 @@ where for &start in starts { let start = start.as_(); - let end = start + length; + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; if length == 0 { continue; } @@ -464,7 +471,9 @@ where let mut new_data = ByteBufferMut::with_capacity(output_bytes); for &start in starts { let start = start.as_(); - let end = start + length; + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; if length == 0 { continue; } @@ -497,16 +506,20 @@ where Offset: IntegerPType, NewOffset: IntegerPType, { - validate_index_ranges(offsets.len() - 1, starts, lengths, output_len)?; - let mut new_offsets = BufferMut::::with_capacity(output_len + 1); new_offsets.push(NewOffset::zero()); let mut output_bytes = 0usize; + let mut computed_len = 0usize; for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - let end = start + length; + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; + computed_len = computed_len + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; if length == 0 { continue; } @@ -534,12 +547,18 @@ where .checked_add(byte_end - byte_start) .ok_or_else(|| vortex_err!("PiecewiseSequence VarBin output byte length overflow"))?; } + vortex_ensure!( + computed_len == output_len, + "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + ); let mut new_data = ByteBufferMut::with_capacity(output_bytes); for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - let end = start + length; + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; if length == 0 { continue; } diff --git a/vortex-array/src/arrays/varbinview/compute/take.rs b/vortex-array/src/arrays/varbinview/compute/take.rs index d347a72ee4b..a7e565df02f 100644 --- a/vortex-array/src/arrays/varbinview/compute/take.rs +++ b/vortex-array/src/arrays/varbinview/compute/take.rs @@ -9,6 +9,8 @@ use num_traits::AsPrimitive; use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; use vortex_mask::AllOr; use vortex_mask::Mask; @@ -22,8 +24,6 @@ use crate::arrays::VarBinViewArray; use crate::arrays::dict::TakeExecute; use crate::arrays::piecewise_sequence::UnitMultiplierLengths; use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; -use crate::arrays::piecewise_sequence::validate_index_ranges; -use crate::arrays::piecewise_sequence::validate_index_ranges_constant; use crate::arrays::varbinview::BinaryView; use crate::buffer::BufferHandle; use crate::dtype::UnsignedPType; @@ -161,12 +161,22 @@ fn gather_view_slices_constant_length( where S: UnsignedPType, { - validate_index_ranges_constant(source.len(), starts, length, output_len)?; + let computed_len = starts + .len() + .checked_mul(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; + vortex_ensure!( + computed_len == output_len, + "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + ); let mut views = BufferMut::::with_capacity(output_len); for &start in starts { let start = start.as_(); - views.extend_from_slice(&source[start..start + length]); + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; + views.extend_from_slice(&source[start..end]); } Ok(views.freeze()) @@ -182,15 +192,24 @@ where S: UnsignedPType, L: UnsignedPType, { - validate_index_ranges(source.len(), starts, lengths, output_len)?; - let mut views = BufferMut::::with_capacity(output_len); + let mut computed_len = 0usize; for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - views.extend_from_slice(&source[start..start + length]); + let end = start + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; + computed_len = computed_len + .checked_add(length) + .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; + views.extend_from_slice(&source[start..end]); } + vortex_ensure!( + computed_len == output_len, + "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + ); Ok(views.freeze()) } From c6c53f9adfd6c5478f8945c4d3f1855d2d1739ee Mon Sep 17 00:00:00 2001 From: Daniel King Date: Fri, 17 Jul 2026 14:48:33 -0400 Subject: [PATCH 12/20] Simplify PiecewiseSequence take range handling Signed-off-by: Daniel King --- vortex-array/src/arrays/bool/compute/take.rs | 10 +---- .../src/arrays/decimal/compute/take.rs | 10 +---- .../arrays/fixed_size_list/compute/take.rs | 22 +++------- .../src/arrays/primitive/compute/take/mod.rs | 10 +---- .../src/arrays/varbin/compute/take.rs | 40 ++++++++----------- .../src/arrays/varbinview/compute/take.rs | 10 +---- 6 files changed, 29 insertions(+), 73 deletions(-) diff --git a/vortex-array/src/arrays/bool/compute/take.rs b/vortex-array/src/arrays/bool/compute/take.rs index 8e43a1a1e0b..4e2596249e3 100644 --- a/vortex-array/src/arrays/bool/compute/take.rs +++ b/vortex-array/src/arrays/bool/compute/take.rs @@ -158,10 +158,7 @@ where let mut values = BitBufferMut::with_capacity(output_len); for &start in starts { let start = start.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; - values.append_buffer(&source.slice(start..end)); + values.append_buffer(&source.slice(start..).slice(..length)); } Ok(values.freeze()) @@ -182,13 +179,10 @@ where for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; computed_len = computed_len .checked_add(length) .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; - values.append_buffer(&source.slice(start..end)); + values.append_buffer(&source.slice(start..).slice(..length)); } vortex_ensure!( diff --git a/vortex-array/src/arrays/decimal/compute/take.rs b/vortex-array/src/arrays/decimal/compute/take.rs index 0bb354b4a6a..6542c77ccd2 100644 --- a/vortex-array/src/arrays/decimal/compute/take.rs +++ b/vortex-array/src/arrays/decimal/compute/take.rs @@ -198,10 +198,7 @@ where let mut result = BufferMut::::with_capacity(output_len); for &start in starts { let start = start.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; - result.extend_from_slice(&values[start..end]); + result.extend_from_slice(&values[start..][..length]); } Ok(result.freeze()) @@ -223,13 +220,10 @@ where for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; computed_len = computed_len .checked_add(length) .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; - result.extend_from_slice(&values[start..end]); + result.extend_from_slice(&values[start..][..length]); } vortex_ensure!( diff --git a/vortex-array/src/arrays/fixed_size_list/compute/take.rs b/vortex-array/src/arrays/fixed_size_list/compute/take.rs index 9a8cc63ec2d..5f2e0a50835 100644 --- a/vortex-array/src/arrays/fixed_size_list/compute/take.rs +++ b/vortex-array/src/arrays/fixed_size_list/compute/take.rs @@ -24,7 +24,6 @@ use crate::arrays::primitive::PrimitiveArrayExt; use crate::builders::builder_with_capacity; use crate::dtype::DType; use crate::dtype::IntegerPType; -use crate::dtype::Nullability; use crate::executor::ExecutionCtx; use crate::match_each_integer_ptype; use crate::optimizer::ArrayOptimizer; @@ -94,7 +93,7 @@ fn take_non_empty_fsl( ) -> VortexResult { debug_assert!(!array.is_empty()); - let DType::Primitive(ptype, nullability) = indices.dtype() else { + let DType::Primitive(ptype, _) = indices.dtype() else { vortex_bail!("Invalid indices dtype: {}", indices.dtype()) }; if !ptype.is_int() { @@ -107,13 +106,7 @@ fn take_non_empty_fsl( let indices_array = indices.clone().execute::(ctx)?; match_each_integer_ptype!(indices_array.ptype(), |I| { - take_non_empty_non_degenerate_fsl::( - array, - indices, - indices_array.as_view(), - *nullability, - ctx, - ) + take_non_empty_non_degenerate_fsl::(array, indices, indices_array.as_view(), ctx) }) } @@ -154,7 +147,6 @@ fn take_non_empty_non_degenerate_fsl( array: ArrayView<'_, FixedSizeList>, indices: &ArrayRef, indices_array: ArrayView<'_, Primitive>, - indices_nullability: Nullability, ctx: &mut ExecutionCtx, ) -> VortexResult { debug_assert!(!array.is_empty()); @@ -162,14 +154,10 @@ fn take_non_empty_non_degenerate_fsl( let (new_elements, new_len) = take_non_empty_non_degenerate_elements::(array, indices_array, ctx)?; - let new_validity = if array.dtype().is_nullable() || indices_nullability.is_nullable() { - array.validity()?.take(indices)? - } else { - Validity::NonNullable - }; + let new_validity = array.validity()?.take(indices)?; - // SAFETY: `new_elements` has `new_len * list_size` elements. `new_validity` is either - // non-nullable or was produced by `Validity::take` for `new_len`. + // SAFETY: `new_elements` has `new_len * list_size` elements, and `Validity::take` produces + // validity for `new_len`. unsafe { FixedSizeListArray::new_unchecked(new_elements, array.list_size(), new_validity, new_len) } diff --git a/vortex-array/src/arrays/primitive/compute/take/mod.rs b/vortex-array/src/arrays/primitive/compute/take/mod.rs index 58c9d271cff..25dba1c3b53 100644 --- a/vortex-array/src/arrays/primitive/compute/take/mod.rs +++ b/vortex-array/src/arrays/primitive/compute/take/mod.rs @@ -246,13 +246,10 @@ where for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; computed_len = computed_len .checked_add(length) .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; - values.extend_from_slice(&source[start..end]); + values.extend_from_slice(&source[start..][..length]); } vortex_ensure!( @@ -317,10 +314,7 @@ where let mut values = BufferMut::::with_capacity(output_len); for &start in starts { let start = start.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; - values.extend_from_slice(&source[start..end]); + values.extend_from_slice(&source[start..][..length]); } Ok(values.freeze()) diff --git a/vortex-array/src/arrays/varbin/compute/take.rs b/vortex-array/src/arrays/varbin/compute/take.rs index 416a194397a..cc0aeb1d896 100644 --- a/vortex-array/src/arrays/varbin/compute/take.rs +++ b/vortex-array/src/arrays/varbin/compute/take.rs @@ -437,22 +437,20 @@ where for &start in starts { let start = start.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; if length == 0 { continue; } - let byte_start = offsets[start].as_(); - let byte_end = offsets[end].as_(); + let offset_range = &offsets[start..][..=length]; + let byte_start = offset_range[0].as_(); + let byte_end = offset_range[length].as_(); vortex_ensure!( byte_start <= byte_end && byte_end <= data.len(), "VarBin offsets range {byte_start}..{byte_end} exceeds data length {}", data.len() ); - for &offset in &offsets[start + 1..=end] { + for &offset in &offset_range[1..] { let offset = offset.as_(); let relative = offset.checked_sub(byte_start).ok_or_else(|| { vortex_err!("VarBin offsets are not monotonic at offset {offset}") @@ -471,16 +469,14 @@ where let mut new_data = ByteBufferMut::with_capacity(output_bytes); for &start in starts { let start = start.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; if length == 0 { continue; } - let byte_start = offsets[start].as_(); - let byte_end = offsets[end].as_(); - new_data.extend_from_slice(&data[byte_start..byte_end]); + let offset_range = &offsets[start..][..=length]; + let byte_start = offset_range[0].as_(); + let byte_end = offset_range[length].as_(); + new_data.extend_from_slice(&data[byte_start..][..byte_end - byte_start]); } let offsets = PrimitiveArray::new(new_offsets.freeze(), Validity::NonNullable) @@ -514,9 +510,6 @@ where for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; computed_len = computed_len .checked_add(length) .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; @@ -524,15 +517,16 @@ where continue; } - let byte_start = offsets[start].as_(); - let byte_end = offsets[end].as_(); + let offset_range = &offsets[start..][..=length]; + let byte_start = offset_range[0].as_(); + let byte_end = offset_range[length].as_(); vortex_ensure!( byte_start <= byte_end && byte_end <= data.len(), "VarBin offsets range {byte_start}..{byte_end} exceeds data length {}", data.len() ); - for &offset in &offsets[start + 1..=end] { + for &offset in &offset_range[1..] { let offset = offset.as_(); let relative = offset.checked_sub(byte_start).ok_or_else(|| { vortex_err!("VarBin offsets are not monotonic at offset {offset}") @@ -556,16 +550,14 @@ where for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; if length == 0 { continue; } - let byte_start = offsets[start].as_(); - let byte_end = offsets[end].as_(); - new_data.extend_from_slice(&data[byte_start..byte_end]); + let offset_range = &offsets[start..][..=length]; + let byte_start = offset_range[0].as_(); + let byte_end = offset_range[length].as_(); + new_data.extend_from_slice(&data[byte_start..][..byte_end - byte_start]); } let offsets = PrimitiveArray::new(new_offsets.freeze(), Validity::NonNullable) diff --git a/vortex-array/src/arrays/varbinview/compute/take.rs b/vortex-array/src/arrays/varbinview/compute/take.rs index a7e565df02f..f91354d8be6 100644 --- a/vortex-array/src/arrays/varbinview/compute/take.rs +++ b/vortex-array/src/arrays/varbinview/compute/take.rs @@ -173,10 +173,7 @@ where let mut views = BufferMut::::with_capacity(output_len); for &start in starts { let start = start.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; - views.extend_from_slice(&source[start..end]); + views.extend_from_slice(&source[start..][..length]); } Ok(views.freeze()) @@ -197,13 +194,10 @@ where for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - let end = start - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?; computed_len = computed_len .checked_add(length) .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; - views.extend_from_slice(&source[start..end]); + views.extend_from_slice(&source[start..][..length]); } vortex_ensure!( From 42fd91d30130a51a28845049235b44c93b3f62dd Mon Sep 17 00:00:00 2001 From: Daniel King Date: Fri, 17 Jul 2026 15:10:45 -0400 Subject: [PATCH 13/20] Validate PiecewiseSequence buffer lengths after copy Signed-off-by: Daniel King --- vortex-array/src/arrays/bool/compute/take.rs | 9 +++------ vortex-array/src/arrays/decimal/compute/take.rs | 9 +++------ vortex-array/src/arrays/primitive/compute/take/mod.rs | 9 +++------ vortex-array/src/arrays/varbin/compute/take.rs | 9 +++------ vortex-array/src/arrays/varbinview/compute/take.rs | 9 +++------ 5 files changed, 15 insertions(+), 30 deletions(-) diff --git a/vortex-array/src/arrays/bool/compute/take.rs b/vortex-array/src/arrays/bool/compute/take.rs index 4e2596249e3..410382f57a4 100644 --- a/vortex-array/src/arrays/bool/compute/take.rs +++ b/vortex-array/src/arrays/bool/compute/take.rs @@ -175,19 +175,16 @@ where L: UnsignedPType, { let mut values = BitBufferMut::with_capacity(output_len); - let mut computed_len = 0usize; for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - computed_len = computed_len - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; values.append_buffer(&source.slice(start..).slice(..length)); } vortex_ensure!( - computed_len == output_len, - "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + values.len() == output_len, + "PiecewiseSequenceArray expanded length {} does not match declared length {output_len}", + values.len() ); Ok(values.freeze()) } diff --git a/vortex-array/src/arrays/decimal/compute/take.rs b/vortex-array/src/arrays/decimal/compute/take.rs index 6542c77ccd2..a4ddd287ee3 100644 --- a/vortex-array/src/arrays/decimal/compute/take.rs +++ b/vortex-array/src/arrays/decimal/compute/take.rs @@ -216,19 +216,16 @@ where T: NativeDecimalType, { let mut result = BufferMut::::with_capacity(output_len); - let mut computed_len = 0usize; for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - computed_len = computed_len - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; result.extend_from_slice(&values[start..][..length]); } vortex_ensure!( - computed_len == output_len, - "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + result.len() == output_len, + "PiecewiseSequenceArray expanded length {} does not match declared length {output_len}", + result.len() ); Ok(result.freeze()) } diff --git a/vortex-array/src/arrays/primitive/compute/take/mod.rs b/vortex-array/src/arrays/primitive/compute/take/mod.rs index 25dba1c3b53..207f5cbdefc 100644 --- a/vortex-array/src/arrays/primitive/compute/take/mod.rs +++ b/vortex-array/src/arrays/primitive/compute/take/mod.rs @@ -242,19 +242,16 @@ where L: UnsignedPType, { let mut values = BufferMut::::with_capacity(output_len); - let mut computed_len = 0usize; for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - computed_len = computed_len - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; values.extend_from_slice(&source[start..][..length]); } vortex_ensure!( - computed_len == output_len, - "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + values.len() == output_len, + "PiecewiseSequenceArray expanded length {} does not match declared length {output_len}", + values.len() ); Ok(values.freeze()) } diff --git a/vortex-array/src/arrays/varbin/compute/take.rs b/vortex-array/src/arrays/varbin/compute/take.rs index cc0aeb1d896..e3bbb7d98ca 100644 --- a/vortex-array/src/arrays/varbin/compute/take.rs +++ b/vortex-array/src/arrays/varbin/compute/take.rs @@ -505,14 +505,10 @@ where let mut new_offsets = BufferMut::::with_capacity(output_len + 1); new_offsets.push(NewOffset::zero()); let mut output_bytes = 0usize; - let mut computed_len = 0usize; for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - computed_len = computed_len - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; if length == 0 { continue; } @@ -542,8 +538,9 @@ where .ok_or_else(|| vortex_err!("PiecewiseSequence VarBin output byte length overflow"))?; } vortex_ensure!( - computed_len == output_len, - "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + new_offsets.len() == output_len + 1, + "PiecewiseSequenceArray expanded length {} does not match declared length {output_len}", + new_offsets.len() - 1 ); let mut new_data = ByteBufferMut::with_capacity(output_bytes); diff --git a/vortex-array/src/arrays/varbinview/compute/take.rs b/vortex-array/src/arrays/varbinview/compute/take.rs index f91354d8be6..41636e87a8f 100644 --- a/vortex-array/src/arrays/varbinview/compute/take.rs +++ b/vortex-array/src/arrays/varbinview/compute/take.rs @@ -190,19 +190,16 @@ where L: UnsignedPType, { let mut views = BufferMut::::with_capacity(output_len); - let mut computed_len = 0usize; for (&start, &length) in starts.iter().zip_eq(lengths) { let start = start.as_(); let length = length.as_(); - computed_len = computed_len - .checked_add(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; views.extend_from_slice(&source[start..][..length]); } vortex_ensure!( - computed_len == output_len, - "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" + views.len() == output_len, + "PiecewiseSequenceArray expanded length {} does not match declared length {output_len}", + views.len() ); Ok(views.freeze()) } From 2b47f4ffc01c86bd96c2af4d877b6014f67c36a1 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Fri, 17 Jul 2026 16:02:53 -0400 Subject: [PATCH 14/20] Cover null FSL take placeholder indices Signed-off-by: Daniel King --- .../src/arrays/fixed_size_list/tests/take.rs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/vortex-array/src/arrays/fixed_size_list/tests/take.rs b/vortex-array/src/arrays/fixed_size_list/tests/take.rs index af8f94f2d5f..93262a74b37 100644 --- a/vortex-array/src/arrays/fixed_size_list/tests/take.rs +++ b/vortex-array/src/arrays/fixed_size_list/tests/take.rs @@ -147,6 +147,28 @@ fn test_take_fsl_with_null_indices_preserves_elements() { assert_arrays_eq!(expected, result, &mut ctx); } +#[test] +fn test_take_fsl_null_index_ignores_out_of_bounds_payload() { + let mut ctx = array_session().create_execution_ctx(); + let elements = buffer![1i32, 2, 3, 4, 5, 6].into_array(); + let fsl = FixedSizeListArray::new(elements.into_array(), 2, Validity::NonNullable, 3); + + let indices = PrimitiveArray::new( + buffer![1u32, 99, 2], + Validity::from_iter([true, false, true]), + ) + .into_array(); + let result = fsl.take(indices).unwrap(); + + let expected = FixedSizeListArray::new( + buffer![3i32, 4, 0, 0, 5, 6].into_array(), + 2, + Validity::from_iter([true, false, true]), + 3, + ); + assert_arrays_eq!(expected, result, &mut ctx); +} + // Element index overflow: with u8 indices and list_size=16, data_idx=16 produces element index // 16*16=256 which overflows u8. The take kernel must widen the element index type. #[rstest] From 363d9073344a5f4fe593b59ab8af75a3736658f9 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Fri, 17 Jul 2026 16:17:34 -0400 Subject: [PATCH 15/20] Rename contiguous PiecewiseSequence helpers Signed-off-by: Daniel King --- vortex-array/src/arrays/bool/compute/take.rs | 10 +++++----- vortex-array/src/arrays/decimal/compute/take.rs | 10 +++++----- vortex-array/src/arrays/piecewise_sequence/mod.rs | 10 +++++----- vortex-array/src/arrays/primitive/compute/take/mod.rs | 10 +++++----- vortex-array/src/arrays/varbin/compute/take.rs | 10 +++++----- vortex-array/src/arrays/varbinview/compute/take.rs | 10 +++++----- 6 files changed, 30 insertions(+), 30 deletions(-) diff --git a/vortex-array/src/arrays/bool/compute/take.rs b/vortex-array/src/arrays/bool/compute/take.rs index 410382f57a4..1297a0a18e7 100644 --- a/vortex-array/src/arrays/bool/compute/take.rs +++ b/vortex-array/src/arrays/bool/compute/take.rs @@ -22,8 +22,8 @@ use crate::arrays::PiecewiseSequence; use crate::arrays::PrimitiveArray; use crate::arrays::bool::BoolArrayExt; use crate::arrays::dict::TakeExecute; -use crate::arrays::piecewise_sequence::UnitMultiplierLengths; -use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; +use crate::arrays::piecewise_sequence::ConstantOrArray; +use crate::arrays::piecewise_sequence::maybe_contiguous_slices; use crate::builtins::ArrayBuiltins; use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; @@ -75,13 +75,13 @@ fn take_contiguous_ranges( indices_ref: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { - let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { + let Some((starts, lengths)) = maybe_contiguous_slices(indices, ctx)? else { return Ok(None); }; let source = array.to_bit_buffer(); let output_len = indices_ref.len(); let buffer = match &lengths { - UnitMultiplierLengths::Constant(length) => { + ConstantOrArray::Constant(length) => { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { take_bit_slices_constant_length( &source, @@ -91,7 +91,7 @@ fn take_contiguous_ranges( )? }) } - UnitMultiplierLengths::Array(lengths) => { + ConstantOrArray::Array(lengths) => { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { take_bit_slices( diff --git a/vortex-array/src/arrays/decimal/compute/take.rs b/vortex-array/src/arrays/decimal/compute/take.rs index a4ddd287ee3..ef34f47ffc7 100644 --- a/vortex-array/src/arrays/decimal/compute/take.rs +++ b/vortex-array/src/arrays/decimal/compute/take.rs @@ -16,8 +16,8 @@ use crate::arrays::DecimalArray; use crate::arrays::PiecewiseSequence; use crate::arrays::PrimitiveArray; use crate::arrays::dict::TakeExecute; -use crate::arrays::piecewise_sequence::UnitMultiplierLengths; -use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; +use crate::arrays::piecewise_sequence::ConstantOrArray; +use crate::arrays::piecewise_sequence::maybe_contiguous_slices; use crate::dtype::IntegerPType; use crate::dtype::NativeDecimalType; use crate::dtype::UnsignedPType; @@ -64,16 +64,16 @@ fn take_contiguous_ranges( indices_ref: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { - let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { + let Some((starts, lengths)) = maybe_contiguous_slices(indices, ctx)? else { return Ok(None); }; let validity = array.validity()?.take(indices_ref)?; let output_len = indices_ref.len(); let taken = match lengths { - UnitMultiplierLengths::Constant(length) => { + ConstantOrArray::Constant(length) => { take_slices_constant_length(array, &starts, length, validity, output_len)? } - UnitMultiplierLengths::Array(lengths) => { + ConstantOrArray::Array(lengths) => { take_slices(array, &starts, &lengths, validity, output_len)? } }; diff --git a/vortex-array/src/arrays/piecewise_sequence/mod.rs b/vortex-array/src/arrays/piecewise_sequence/mod.rs index cdc5649c9f2..18ce7debec1 100644 --- a/vortex-array/src/arrays/piecewise_sequence/mod.rs +++ b/vortex-array/src/arrays/piecewise_sequence/mod.rs @@ -67,15 +67,15 @@ pub(crate) fn execute_index_arrays( Ok((starts, lengths, multipliers)) } -pub(crate) enum UnitMultiplierLengths { +pub(crate) enum ConstantOrArray { Constant(usize), Array(PrimitiveArray), } -pub(crate) fn execute_unit_multiplier_index_arrays( +pub(crate) fn maybe_contiguous_slices( array: ArrayView<'_, PiecewiseSequence>, ctx: &mut ExecutionCtx, -) -> VortexResult> { +) -> VortexResult> { if !is_constant_multiplier_one(array.multipliers()) { return Ok(None); } @@ -84,12 +84,12 @@ pub(crate) fn execute_unit_multiplier_index_arrays( let starts = array.starts().clone().execute::(ctx)?; if let Some(length) = constant_unsigned_usize(array.lengths())? { check_index_arrays(starts.as_ref(), array.lengths(), array.multipliers())?; - return Ok(Some((starts, UnitMultiplierLengths::Constant(length)))); + return Ok(Some((starts, ConstantOrArray::Constant(length)))); } let lengths = array.lengths().clone().execute::(ctx)?; check_index_arrays(starts.as_ref(), lengths.as_ref(), array.multipliers())?; - Ok(Some((starts, UnitMultiplierLengths::Array(lengths)))) + Ok(Some((starts, ConstantOrArray::Array(lengths)))) } pub(crate) fn is_constant_multiplier_one(multipliers: &ArrayRef) -> bool { diff --git a/vortex-array/src/arrays/primitive/compute/take/mod.rs b/vortex-array/src/arrays/primitive/compute/take/mod.rs index 207f5cbdefc..a301cf99b29 100644 --- a/vortex-array/src/arrays/primitive/compute/take/mod.rs +++ b/vortex-array/src/arrays/primitive/compute/take/mod.rs @@ -23,8 +23,8 @@ use crate::arrays::PiecewiseSequence; use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; use crate::arrays::dict::TakeExecute; -use crate::arrays::piecewise_sequence::UnitMultiplierLengths; -use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; +use crate::arrays::piecewise_sequence::ConstantOrArray; +use crate::arrays::piecewise_sequence::maybe_contiguous_slices; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::IntegerPType; @@ -144,16 +144,16 @@ fn take_contiguous_ranges( indices_ref: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { - let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { + let Some((starts, lengths)) = maybe_contiguous_slices(indices, ctx)? else { return Ok(None); }; let validity = array.validity()?.take(indices_ref)?; let output_len = indices_ref.len(); let taken = match lengths { - UnitMultiplierLengths::Constant(length) => { + ConstantOrArray::Constant(length) => { take_slices_constant_length(array, &starts, length, validity, output_len)? } - UnitMultiplierLengths::Array(lengths) => { + ConstantOrArray::Array(lengths) => { take_slices(array, &starts, &lengths, validity, output_len)? } }; diff --git a/vortex-array/src/arrays/varbin/compute/take.rs b/vortex-array/src/arrays/varbin/compute/take.rs index e3bbb7d98ca..b956359ef0b 100644 --- a/vortex-array/src/arrays/varbin/compute/take.rs +++ b/vortex-array/src/arrays/varbin/compute/take.rs @@ -20,8 +20,8 @@ use crate::arrays::PrimitiveArray; use crate::arrays::VarBin; use crate::arrays::VarBinArray; use crate::arrays::dict::TakeExecute; -use crate::arrays::piecewise_sequence::UnitMultiplierLengths; -use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; +use crate::arrays::piecewise_sequence::ConstantOrArray; +use crate::arrays::piecewise_sequence::maybe_contiguous_slices; use crate::arrays::primitive::PrimitiveArrayExt; use crate::arrays::varbin::VarBinArrayExt; use crate::dtype::DType; @@ -132,7 +132,7 @@ fn take_contiguous_ranges( indices_ref: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { - let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { + let Some((starts, lengths)) = maybe_contiguous_slices(indices, ctx)? else { return Ok(None); }; let offsets = array.offsets().clone().execute::(ctx)?; @@ -144,7 +144,7 @@ fn take_contiguous_ranges( let output_len = indices_ref.len(); let result = match &lengths { - UnitMultiplierLengths::Constant(length) => gather_slices_constant_dispatch( + ConstantOrArray::Constant(length) => gather_slices_constant_dispatch( &starts, *length, &offsets, @@ -152,7 +152,7 @@ fn take_contiguous_ranges( output_len, out_offset_ptype, )?, - UnitMultiplierLengths::Array(lengths) => gather_slices_dispatch( + ConstantOrArray::Array(lengths) => gather_slices_dispatch( &starts, lengths, &offsets, diff --git a/vortex-array/src/arrays/varbinview/compute/take.rs b/vortex-array/src/arrays/varbinview/compute/take.rs index 41636e87a8f..40e05e08737 100644 --- a/vortex-array/src/arrays/varbinview/compute/take.rs +++ b/vortex-array/src/arrays/varbinview/compute/take.rs @@ -22,8 +22,8 @@ use crate::arrays::PrimitiveArray; use crate::arrays::VarBinView; use crate::arrays::VarBinViewArray; use crate::arrays::dict::TakeExecute; -use crate::arrays::piecewise_sequence::UnitMultiplierLengths; -use crate::arrays::piecewise_sequence::execute_unit_multiplier_index_arrays; +use crate::arrays::piecewise_sequence::ConstantOrArray; +use crate::arrays::piecewise_sequence::maybe_contiguous_slices; use crate::arrays::varbinview::BinaryView; use crate::buffer::BufferHandle; use crate::dtype::UnsignedPType; @@ -78,13 +78,13 @@ fn take_contiguous_ranges( indices_ref: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { - let Some((starts, lengths)) = execute_unit_multiplier_index_arrays(indices, ctx)? else { + let Some((starts, lengths)) = maybe_contiguous_slices(indices, ctx)? else { return Ok(None); }; let source = array.views(); let output_len = indices_ref.len(); let views = match &lengths { - UnitMultiplierLengths::Constant(length) => { + ConstantOrArray::Constant(length) => { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { gather_view_slices_constant_length( source, @@ -94,7 +94,7 @@ fn take_contiguous_ranges( )? }) } - UnitMultiplierLengths::Array(lengths) => { + ConstantOrArray::Array(lengths) => { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { gather_view_slices( From 54650fdca61a9284311d843375a3acbb6fd626b1 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Fri, 17 Jul 2026 16:23:07 -0400 Subject: [PATCH 16/20] Move VarBin PiecewiseSequence takes out of base PR Signed-off-by: Daniel King --- .../src/arrays/varbin/compute/take.rs | 397 +----------------- .../src/arrays/varbinview/compute/take.rs | 124 +----- 2 files changed, 2 insertions(+), 519 deletions(-) diff --git a/vortex-array/src/arrays/varbin/compute/take.rs b/vortex-array/src/arrays/varbin/compute/take.rs index b956359ef0b..74e0bd6af9d 100644 --- a/vortex-array/src/arrays/varbin/compute/take.rs +++ b/vortex-array/src/arrays/varbin/compute/take.rs @@ -1,33 +1,26 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use itertools::Itertools as _; use vortex_buffer::BitBufferMut; use vortex_buffer::BufferMut; use vortex_buffer::ByteBufferMut; use vortex_error::VortexExpect; use vortex_error::VortexResult; -use vortex_error::vortex_ensure; -use vortex_error::vortex_err; use vortex_error::vortex_panic; use vortex_mask::Mask; use crate::ArrayRef; use crate::IntoArray; use crate::array::ArrayView; -use crate::arrays::PiecewiseSequence; use crate::arrays::PrimitiveArray; use crate::arrays::VarBin; use crate::arrays::VarBinArray; use crate::arrays::dict::TakeExecute; -use crate::arrays::piecewise_sequence::ConstantOrArray; -use crate::arrays::piecewise_sequence::maybe_contiguous_slices; use crate::arrays::primitive::PrimitiveArrayExt; use crate::arrays::varbin::VarBinArrayExt; use crate::dtype::DType; use crate::dtype::IntegerPType; use crate::dtype::PType; -use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; use crate::match_each_unsigned_integer_ptype; use crate::validity::Validity; @@ -50,12 +43,6 @@ impl TakeExecute for VarBin { indices: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { - if let Some(piecewise_indices) = indices.as_opt::() - && let Some(taken) = take_contiguous_ranges(array, piecewise_indices, indices, ctx)? - { - return Ok(Some(taken)); - } - // TODO(joe): Be lazy with execute let offsets = array.offsets().clone().execute::(ctx)?; let data = array.bytes(); @@ -126,54 +113,6 @@ impl TakeExecute for VarBin { } } -fn take_contiguous_ranges( - array: ArrayView<'_, VarBin>, - indices: ArrayView<'_, PiecewiseSequence>, - indices_ref: &ArrayRef, - ctx: &mut ExecutionCtx, -) -> VortexResult> { - let Some((starts, lengths)) = maybe_contiguous_slices(indices, ctx)? else { - return Ok(None); - }; - let offsets = array.offsets().clone().execute::(ctx)?; - let out_offset_ptype = taken_offset_ptype(offsets.ptype()); - let offsets = offsets.reinterpret_cast(offsets.ptype().to_unsigned()); - let bytes = array.bytes(); - let data = bytes.as_slice(); - let dtype = array.dtype().clone(); - let output_len = indices_ref.len(); - - let result = match &lengths { - ConstantOrArray::Constant(length) => gather_slices_constant_dispatch( - &starts, - *length, - &offsets, - data, - output_len, - out_offset_ptype, - )?, - ConstantOrArray::Array(lengths) => gather_slices_dispatch( - &starts, - lengths, - &offsets, - data, - output_len, - out_offset_ptype, - )?, - }; - - let validity = array.validity()?.take(indices_ref)?; - - // SAFETY: output offsets are built from valid input offsets, start at zero, are monotonically - // non-decreasing, and the copied data buffer has exactly the referenced byte length. - unsafe { - Ok(Some( - VarBinArray::new_unchecked(result.offsets, result.data.freeze(), dtype, validity) - .into_array(), - )) - } -} - fn take( dtype: DType, offsets: &[Offset], @@ -244,337 +183,6 @@ fn take( } } -struct GatheredPiecewiseVarBin { - offsets: ArrayRef, - data: ByteBufferMut, -} - -fn gather_slices_constant_dispatch( - starts: &PrimitiveArray, - length: usize, - offsets: &PrimitiveArray, - data: &[u8], - output_len: usize, - out_offset_ptype: PType, -) -> VortexResult { - match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - gather_slices_constant_start_dispatch::( - starts, - length, - offsets, - data, - output_len, - out_offset_ptype, - ) - }) -} - -fn gather_slices_constant_start_dispatch( - starts: &PrimitiveArray, - length: usize, - offsets: &PrimitiveArray, - data: &[u8], - output_len: usize, - out_offset_ptype: PType, -) -> VortexResult -where - S: UnsignedPType, -{ - match offsets.ptype() { - PType::U8 => gather_slices_constant_length::( - offsets.as_slice::(), - data, - starts.as_slice::(), - length, - output_len, - out_offset_ptype, - ), - PType::U16 => gather_slices_constant_length::( - offsets.as_slice::(), - data, - starts.as_slice::(), - length, - output_len, - out_offset_ptype, - ), - PType::U32 => gather_slices_constant_length::( - offsets.as_slice::(), - data, - starts.as_slice::(), - length, - output_len, - out_offset_ptype, - ), - PType::U64 => gather_slices_constant_length::( - offsets.as_slice::(), - data, - starts.as_slice::(), - length, - output_len, - out_offset_ptype, - ), - _ => unreachable!("offsets were reinterpreted to an unsigned integer ptype"), - } -} - -fn gather_slices_dispatch( - starts: &PrimitiveArray, - lengths: &PrimitiveArray, - offsets: &PrimitiveArray, - data: &[u8], - output_len: usize, - out_offset_ptype: PType, -) -> VortexResult { - match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - gather_slices_start_dispatch::( - starts, - lengths, - offsets, - data, - output_len, - out_offset_ptype, - ) - }) -} - -fn gather_slices_start_dispatch( - starts: &PrimitiveArray, - lengths: &PrimitiveArray, - offsets: &PrimitiveArray, - data: &[u8], - output_len: usize, - out_offset_ptype: PType, -) -> VortexResult -where - S: UnsignedPType, -{ - match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { - gather_slices_start_length_dispatch::( - starts, - lengths, - offsets, - data, - output_len, - out_offset_ptype, - ) - }) -} - -fn gather_slices_start_length_dispatch( - starts: &PrimitiveArray, - lengths: &PrimitiveArray, - offsets: &PrimitiveArray, - data: &[u8], - output_len: usize, - out_offset_ptype: PType, -) -> VortexResult -where - S: UnsignedPType, - L: UnsignedPType, -{ - match offsets.ptype() { - PType::U8 => gather_slices::( - offsets.as_slice::(), - data, - starts.as_slice::(), - lengths.as_slice::(), - output_len, - out_offset_ptype, - ), - PType::U16 => gather_slices::( - offsets.as_slice::(), - data, - starts.as_slice::(), - lengths.as_slice::(), - output_len, - out_offset_ptype, - ), - PType::U32 => gather_slices::( - offsets.as_slice::(), - data, - starts.as_slice::(), - lengths.as_slice::(), - output_len, - out_offset_ptype, - ), - PType::U64 => gather_slices::( - offsets.as_slice::(), - data, - starts.as_slice::(), - lengths.as_slice::(), - output_len, - out_offset_ptype, - ), - _ => unreachable!("offsets were reinterpreted to an unsigned integer ptype"), - } -} - -fn gather_slices_constant_length( - offsets: &[Offset], - data: &[u8], - starts: &[S], - length: usize, - output_len: usize, - out_offset_ptype: PType, -) -> VortexResult -where - S: UnsignedPType, - Offset: IntegerPType, - NewOffset: IntegerPType, -{ - let computed_len = starts - .len() - .checked_mul(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; - vortex_ensure!( - computed_len == output_len, - "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" - ); - - let mut new_offsets = BufferMut::::with_capacity(output_len + 1); - new_offsets.push(NewOffset::zero()); - let mut output_bytes = 0usize; - - for &start in starts { - let start = start.as_(); - if length == 0 { - continue; - } - - let offset_range = &offsets[start..][..=length]; - let byte_start = offset_range[0].as_(); - let byte_end = offset_range[length].as_(); - vortex_ensure!( - byte_start <= byte_end && byte_end <= data.len(), - "VarBin offsets range {byte_start}..{byte_end} exceeds data length {}", - data.len() - ); - - for &offset in &offset_range[1..] { - let offset = offset.as_(); - let relative = offset.checked_sub(byte_start).ok_or_else(|| { - vortex_err!("VarBin offsets are not monotonic at offset {offset}") - })?; - let output_offset = output_bytes.checked_add(relative).ok_or_else(|| { - vortex_err!("PiecewiseSequence VarBin output byte length overflow") - })?; - new_offsets.push(new_offset_value::(output_offset)?); - } - - output_bytes = output_bytes - .checked_add(byte_end - byte_start) - .ok_or_else(|| vortex_err!("PiecewiseSequence VarBin output byte length overflow"))?; - } - - let mut new_data = ByteBufferMut::with_capacity(output_bytes); - for &start in starts { - let start = start.as_(); - if length == 0 { - continue; - } - - let offset_range = &offsets[start..][..=length]; - let byte_start = offset_range[0].as_(); - let byte_end = offset_range[length].as_(); - new_data.extend_from_slice(&data[byte_start..][..byte_end - byte_start]); - } - - let offsets = PrimitiveArray::new(new_offsets.freeze(), Validity::NonNullable) - .reinterpret_cast(out_offset_ptype) - .into_array(); - Ok(GatheredPiecewiseVarBin { - offsets, - data: new_data, - }) -} - -fn gather_slices( - offsets: &[Offset], - data: &[u8], - starts: &[S], - lengths: &[L], - output_len: usize, - out_offset_ptype: PType, -) -> VortexResult -where - S: UnsignedPType, - L: UnsignedPType, - Offset: IntegerPType, - NewOffset: IntegerPType, -{ - let mut new_offsets = BufferMut::::with_capacity(output_len + 1); - new_offsets.push(NewOffset::zero()); - let mut output_bytes = 0usize; - - for (&start, &length) in starts.iter().zip_eq(lengths) { - let start = start.as_(); - let length = length.as_(); - if length == 0 { - continue; - } - - let offset_range = &offsets[start..][..=length]; - let byte_start = offset_range[0].as_(); - let byte_end = offset_range[length].as_(); - vortex_ensure!( - byte_start <= byte_end && byte_end <= data.len(), - "VarBin offsets range {byte_start}..{byte_end} exceeds data length {}", - data.len() - ); - - for &offset in &offset_range[1..] { - let offset = offset.as_(); - let relative = offset.checked_sub(byte_start).ok_or_else(|| { - vortex_err!("VarBin offsets are not monotonic at offset {offset}") - })?; - let output_offset = output_bytes.checked_add(relative).ok_or_else(|| { - vortex_err!("PiecewiseSequence VarBin output byte length overflow") - })?; - new_offsets.push(new_offset_value::(output_offset)?); - } - - output_bytes = output_bytes - .checked_add(byte_end - byte_start) - .ok_or_else(|| vortex_err!("PiecewiseSequence VarBin output byte length overflow"))?; - } - vortex_ensure!( - new_offsets.len() == output_len + 1, - "PiecewiseSequenceArray expanded length {} does not match declared length {output_len}", - new_offsets.len() - 1 - ); - - let mut new_data = ByteBufferMut::with_capacity(output_bytes); - for (&start, &length) in starts.iter().zip_eq(lengths) { - let start = start.as_(); - let length = length.as_(); - if length == 0 { - continue; - } - - let offset_range = &offsets[start..][..=length]; - let byte_start = offset_range[0].as_(); - let byte_end = offset_range[length].as_(); - new_data.extend_from_slice(&data[byte_start..][..byte_end - byte_start]); - } - - let offsets = PrimitiveArray::new(new_offsets.freeze(), Validity::NonNullable) - .reinterpret_cast(out_offset_ptype) - .into_array(); - Ok(GatheredPiecewiseVarBin { - offsets, - data: new_data, - }) -} - -fn new_offset_value(value: usize) -> VortexResult { - T::from(value).ok_or_else(|| { - vortex_err!( - "PiecewiseSequence VarBin offset value {value} does not fit in {}", - T::PTYPE - ) - }) -} - fn take_nullable( dtype: DType, offsets: &[Offset], @@ -695,10 +303,7 @@ mod tests { ))] #[case(VarBinArray::from_iter(["single"].map(Some), DType::Utf8(Nullability::NonNullable)))] fn test_take_varbin_conformance(#[case] array: VarBinArray) { - test_take_conformance( - &array.into_array(), - &mut array_session().create_execution_ctx(), - ); + test_take_conformance(&array.into_array()); } #[test] diff --git a/vortex-array/src/arrays/varbinview/compute/take.rs b/vortex-array/src/arrays/varbinview/compute/take.rs index 40e05e08737..1b7435729f1 100644 --- a/vortex-array/src/arrays/varbinview/compute/take.rs +++ b/vortex-array/src/arrays/varbinview/compute/take.rs @@ -4,32 +4,23 @@ use std::iter; use std::sync::Arc; -use itertools::Itertools as _; use num_traits::AsPrimitive; use vortex_buffer::Buffer; -use vortex_buffer::BufferMut; use vortex_error::VortexResult; -use vortex_error::vortex_ensure; -use vortex_error::vortex_err; use vortex_mask::AllOr; use vortex_mask::Mask; use crate::ArrayRef; use crate::IntoArray; use crate::array::ArrayView; -use crate::arrays::PiecewiseSequence; use crate::arrays::PrimitiveArray; use crate::arrays::VarBinView; use crate::arrays::VarBinViewArray; use crate::arrays::dict::TakeExecute; -use crate::arrays::piecewise_sequence::ConstantOrArray; -use crate::arrays::piecewise_sequence::maybe_contiguous_slices; use crate::arrays::varbinview::BinaryView; use crate::buffer::BufferHandle; -use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; use crate::match_each_integer_ptype; -use crate::match_each_unsigned_integer_ptype; impl TakeExecute for VarBinView { /// Take involves creating a new array that references the old array, just with the given set of views. @@ -38,12 +29,6 @@ impl TakeExecute for VarBinView { indices: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { - if let Some(piecewise_indices) = indices.as_opt::() - && let Some(taken) = take_contiguous_ranges(array, piecewise_indices, indices, ctx)? - { - return Ok(Some(taken)); - } - let validity = array.validity()?.take(indices)?; let indices = indices.clone().execute::(ctx)?; @@ -72,58 +57,6 @@ impl TakeExecute for VarBinView { } } -fn take_contiguous_ranges( - array: ArrayView<'_, VarBinView>, - indices: ArrayView<'_, PiecewiseSequence>, - indices_ref: &ArrayRef, - ctx: &mut ExecutionCtx, -) -> VortexResult> { - let Some((starts, lengths)) = maybe_contiguous_slices(indices, ctx)? else { - return Ok(None); - }; - let source = array.views(); - let output_len = indices_ref.len(); - let views = match &lengths { - ConstantOrArray::Constant(length) => { - match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - gather_view_slices_constant_length( - source, - starts.as_slice::(), - *length, - output_len, - )? - }) - } - ConstantOrArray::Array(lengths) => { - match_each_unsigned_integer_ptype!(starts.ptype(), |S| { - match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { - gather_view_slices( - source, - starts.as_slice::(), - lengths.as_slice::(), - output_len, - )? - }) - }) - } - }; - let validity = array.validity()?.take(indices_ref)?; - - // SAFETY: ranges were validated against the source views, and copied views still reference the - // same backing data buffers. - unsafe { - Ok(Some( - VarBinViewArray::new_handle_unchecked( - BufferHandle::new_host(views.into_byte_buffer()), - Arc::clone(array.data_buffers()), - array.dtype().clone(), - validity, - ) - .into_array(), - )) - } -} - fn take_views>( views_ref: &[BinaryView], indices: &[I], @@ -152,58 +85,6 @@ fn take_views>( } } -fn gather_view_slices_constant_length( - source: &[BinaryView], - starts: &[S], - length: usize, - output_len: usize, -) -> VortexResult> -where - S: UnsignedPType, -{ - let computed_len = starts - .len() - .checked_mul(length) - .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?; - vortex_ensure!( - computed_len == output_len, - "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}" - ); - - let mut views = BufferMut::::with_capacity(output_len); - for &start in starts { - let start = start.as_(); - views.extend_from_slice(&source[start..][..length]); - } - - Ok(views.freeze()) -} - -fn gather_view_slices( - source: &[BinaryView], - starts: &[S], - lengths: &[L], - output_len: usize, -) -> VortexResult> -where - S: UnsignedPType, - L: UnsignedPType, -{ - let mut views = BufferMut::::with_capacity(output_len); - for (&start, &length) in starts.iter().zip_eq(lengths) { - let start = start.as_(); - let length = length.as_(); - views.extend_from_slice(&source[start..][..length]); - } - - vortex_ensure!( - views.len() == output_len, - "PiecewiseSequenceArray expanded length {} does not match declared length {output_len}", - views.len() - ); - Ok(views.freeze()) -} - #[cfg(test)] mod tests { use rstest::rstest; @@ -292,9 +173,6 @@ mod tests { ))] #[case(VarBinViewArray::from_iter(["single"].map(Some), DType::Utf8(NonNullable)))] fn test_take_varbinview_conformance(#[case] array: VarBinViewArray) { - test_take_conformance( - &array.into_array(), - &mut array_session().create_execution_ctx(), - ); + test_take_conformance(&array.into_array()); } } From 01d14f5b6c38f9719cff4e4b64b7a78df6f1df4f Mon Sep 17 00:00:00 2001 From: Daniel King Date: Fri, 17 Jul 2026 16:36:23 -0400 Subject: [PATCH 17/20] Fix VarBin take conformance tests Signed-off-by: Daniel King --- vortex-array/src/arrays/varbin/compute/take.rs | 5 ++++- vortex-array/src/arrays/varbinview/compute/take.rs | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/vortex-array/src/arrays/varbin/compute/take.rs b/vortex-array/src/arrays/varbin/compute/take.rs index 74e0bd6af9d..6a6454d0603 100644 --- a/vortex-array/src/arrays/varbin/compute/take.rs +++ b/vortex-array/src/arrays/varbin/compute/take.rs @@ -303,7 +303,10 @@ mod tests { ))] #[case(VarBinArray::from_iter(["single"].map(Some), DType::Utf8(Nullability::NonNullable)))] fn test_take_varbin_conformance(#[case] array: VarBinArray) { - test_take_conformance(&array.into_array()); + test_take_conformance( + &array.into_array(), + &mut array_session().create_execution_ctx(), + ); } #[test] diff --git a/vortex-array/src/arrays/varbinview/compute/take.rs b/vortex-array/src/arrays/varbinview/compute/take.rs index 1b7435729f1..ce10abda3d0 100644 --- a/vortex-array/src/arrays/varbinview/compute/take.rs +++ b/vortex-array/src/arrays/varbinview/compute/take.rs @@ -173,6 +173,9 @@ mod tests { ))] #[case(VarBinViewArray::from_iter(["single"].map(Some), DType::Utf8(NonNullable)))] fn test_take_varbinview_conformance(#[case] array: VarBinViewArray) { - test_take_conformance(&array.into_array()); + test_take_conformance( + &array.into_array(), + &mut array_session().create_execution_ctx(), + ); } } From 1fdda1cb963e3e79d4c6726b6e7fbf65ef90a377 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Fri, 17 Jul 2026 17:00:47 -0400 Subject: [PATCH 18/20] Rename PiecewiseSequence constant helper Signed-off-by: Daniel King --- vortex-array/src/arrays/piecewise_sequence/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vortex-array/src/arrays/piecewise_sequence/mod.rs b/vortex-array/src/arrays/piecewise_sequence/mod.rs index 18ce7debec1..ba01c9c57e4 100644 --- a/vortex-array/src/arrays/piecewise_sequence/mod.rs +++ b/vortex-array/src/arrays/piecewise_sequence/mod.rs @@ -76,7 +76,7 @@ pub(crate) fn maybe_contiguous_slices( array: ArrayView<'_, PiecewiseSequence>, ctx: &mut ExecutionCtx, ) -> VortexResult> { - if !is_constant_multiplier_one(array.multipliers()) { + if !is_constant_one(array.multipliers()) { return Ok(None); } @@ -92,7 +92,7 @@ pub(crate) fn maybe_contiguous_slices( Ok(Some((starts, ConstantOrArray::Array(lengths)))) } -pub(crate) fn is_constant_multiplier_one(multipliers: &ArrayRef) -> bool { +pub(crate) fn is_constant_one(multipliers: &ArrayRef) -> bool { let Some(scalar) = multipliers.as_constant() else { return false; }; From 210edda778e01e4cc3307c9cd30a7a584172ce57 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Mon, 20 Jul 2026 12:31:09 -0400 Subject: [PATCH 19/20] Use Columnar for PiecewiseSequence lengths Signed-off-by: Daniel King --- vortex-array/src/arrays/bool/compute/take.rs | 20 +++++-- .../src/arrays/decimal/compute/take.rs | 16 +++++- .../src/arrays/piecewise_sequence/mod.rs | 55 ++++++++++--------- .../src/arrays/primitive/compute/take/mod.rs | 15 ++++- 4 files changed, 70 insertions(+), 36 deletions(-) diff --git a/vortex-array/src/arrays/bool/compute/take.rs b/vortex-array/src/arrays/bool/compute/take.rs index 1297a0a18e7..c9b101b0f8a 100644 --- a/vortex-array/src/arrays/bool/compute/take.rs +++ b/vortex-array/src/arrays/bool/compute/take.rs @@ -8,11 +8,14 @@ use vortex_buffer::BitBufferMut; use vortex_buffer::BitBufferView; use vortex_buffer::get_bit; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_error::vortex_err; use vortex_mask::Mask; use crate::ArrayRef; +use crate::Canonical; +use crate::Columnar; use crate::IntoArray; use crate::array::ArrayView; use crate::arrays::Bool; @@ -22,7 +25,7 @@ use crate::arrays::PiecewiseSequence; use crate::arrays::PrimitiveArray; use crate::arrays::bool::BoolArrayExt; use crate::arrays::dict::TakeExecute; -use crate::arrays::piecewise_sequence::ConstantOrArray; +use crate::arrays::piecewise_sequence::constant_unsigned_usize; use crate::arrays::piecewise_sequence::maybe_contiguous_slices; use crate::builtins::ArrayBuiltins; use crate::dtype::UnsignedPType; @@ -80,18 +83,19 @@ fn take_contiguous_ranges( }; let source = array.to_bit_buffer(); let output_len = indices_ref.len(); - let buffer = match &lengths { - ConstantOrArray::Constant(length) => { + let buffer = match lengths { + Columnar::Constant(lengths) => { + let length = constant_unsigned_usize(&lengths)?; match_each_unsigned_integer_ptype!(starts.ptype(), |S| { take_bit_slices_constant_length( &source, starts.as_slice::(), - *length, + length, output_len, )? }) } - ConstantOrArray::Array(lengths) => { + Columnar::Canonical(Canonical::Primitive(lengths)) => { match_each_unsigned_integer_ptype!(starts.ptype(), |S| { match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { take_bit_slices( @@ -103,6 +107,12 @@ fn take_contiguous_ranges( }) }) } + Columnar::Canonical(lengths) => { + vortex_bail!( + "PiecewiseSequenceArray lengths must be primitive or constant, got {}", + lengths.dtype() + ) + } }; Ok(Some( diff --git a/vortex-array/src/arrays/decimal/compute/take.rs b/vortex-array/src/arrays/decimal/compute/take.rs index ef34f47ffc7..3ff63bf901e 100644 --- a/vortex-array/src/arrays/decimal/compute/take.rs +++ b/vortex-array/src/arrays/decimal/compute/take.rs @@ -5,10 +5,13 @@ use itertools::Itertools as _; use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_error::vortex_err; use crate::ArrayRef; +use crate::Canonical; +use crate::Columnar; use crate::IntoArray; use crate::array::ArrayView; use crate::arrays::Decimal; @@ -16,7 +19,7 @@ use crate::arrays::DecimalArray; use crate::arrays::PiecewiseSequence; use crate::arrays::PrimitiveArray; use crate::arrays::dict::TakeExecute; -use crate::arrays::piecewise_sequence::ConstantOrArray; +use crate::arrays::piecewise_sequence::constant_unsigned_usize; use crate::arrays::piecewise_sequence::maybe_contiguous_slices; use crate::dtype::IntegerPType; use crate::dtype::NativeDecimalType; @@ -70,12 +73,19 @@ fn take_contiguous_ranges( let validity = array.validity()?.take(indices_ref)?; let output_len = indices_ref.len(); let taken = match lengths { - ConstantOrArray::Constant(length) => { + Columnar::Constant(lengths) => { + let length = constant_unsigned_usize(&lengths)?; take_slices_constant_length(array, &starts, length, validity, output_len)? } - ConstantOrArray::Array(lengths) => { + Columnar::Canonical(Canonical::Primitive(lengths)) => { take_slices(array, &starts, &lengths, validity, output_len)? } + Columnar::Canonical(lengths) => { + vortex_bail!( + "PiecewiseSequenceArray lengths must be primitive or constant, got {}", + lengths.dtype() + ) + } }; Ok(Some(taken)) } diff --git a/vortex-array/src/arrays/piecewise_sequence/mod.rs b/vortex-array/src/arrays/piecewise_sequence/mod.rs index ba01c9c57e4..5ad9f60ca6e 100644 --- a/vortex-array/src/arrays/piecewise_sequence/mod.rs +++ b/vortex-array/src/arrays/piecewise_sequence/mod.rs @@ -17,9 +17,12 @@ use vortex_error::vortex_ensure; use vortex_error::vortex_err; use crate::ArrayRef; +use crate::Columnar; use crate::array::ArrayView; +use crate::arrays::ConstantArray; use crate::arrays::PrimitiveArray; use crate::arrays::piecewise_sequence::array::PiecewiseSequenceArraySlotsExt; +use crate::dtype::DType; use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; use crate::scalar::PValue; @@ -67,29 +70,26 @@ pub(crate) fn execute_index_arrays( Ok((starts, lengths, multipliers)) } -pub(crate) enum ConstantOrArray { - Constant(usize), - Array(PrimitiveArray), -} - pub(crate) fn maybe_contiguous_slices( array: ArrayView<'_, PiecewiseSequence>, ctx: &mut ExecutionCtx, -) -> VortexResult> { +) -> VortexResult> { if !is_constant_one(array.multipliers()) { return Ok(None); } check_index_arrays(array.starts(), array.lengths(), array.multipliers())?; let starts = array.starts().clone().execute::(ctx)?; - if let Some(length) = constant_unsigned_usize(array.lengths())? { - check_index_arrays(starts.as_ref(), array.lengths(), array.multipliers())?; - return Ok(Some((starts, ConstantOrArray::Constant(length)))); - } - - let lengths = array.lengths().clone().execute::(ctx)?; - check_index_arrays(starts.as_ref(), lengths.as_ref(), array.multipliers())?; - Ok(Some((starts, ConstantOrArray::Array(lengths)))) + let lengths = array.lengths().clone().execute::(ctx)?; + check_index_array("starts", starts.as_ref())?; + check_index_columnar("lengths", &lengths)?; + vortex_ensure!( + starts.len() == lengths.len(), + "PiecewiseSequenceArray starts length {} does not match lengths length {}", + starts.len(), + lengths.len() + ); + Ok(Some((starts, lengths))) } pub(crate) fn is_constant_one(multipliers: &ArrayRef) -> bool { @@ -102,34 +102,39 @@ pub(crate) fn is_constant_one(multipliers: &ArrayRef) -> bool { ) } -fn constant_unsigned_usize(array: &ArrayRef) -> VortexResult> { - let Some(scalar) = array.as_constant() else { - return Ok(None); - }; - +pub(crate) fn constant_unsigned_usize(array: &ConstantArray) -> VortexResult { + let scalar = array.scalar(); let Some(pvalue) = scalar.as_primitive_opt().and_then(|scalar| scalar.pvalue()) else { vortex_bail!("PiecewiseSequenceArray constant length must be an unsigned integer"); }; - Ok(Some(match pvalue { + Ok(match pvalue { PValue::U8(value) => value as usize, PValue::U16(value) => value as usize, PValue::U32(value) => value as usize, PValue::U64(value) => value.as_(), _ => vortex_bail!("PiecewiseSequenceArray constant length must be an unsigned integer"), - })) + }) } fn check_index_array(name: &str, array: &ArrayRef) -> VortexResult<()> { + check_index_dtype(name, array.dtype()) +} + +fn check_index_columnar(name: &str, columnar: &Columnar) -> VortexResult<()> { + check_index_dtype(name, columnar.dtype()) +} + +fn check_index_dtype(name: &str, dtype: &DType) -> VortexResult<()> { vortex_ensure!( - array.dtype().is_unsigned_int(), + dtype.is_unsigned_int(), "PiecewiseSequenceArray {name} must have unsigned integer dtype, got {}", - array.dtype() + dtype ); vortex_ensure!( - !array.dtype().is_nullable(), + !dtype.is_nullable(), "PiecewiseSequenceArray {name} must be non-nullable, got {}", - array.dtype() + dtype ); Ok(()) } diff --git a/vortex-array/src/arrays/primitive/compute/take/mod.rs b/vortex-array/src/arrays/primitive/compute/take/mod.rs index a301cf99b29..d80b0e5127c 100644 --- a/vortex-array/src/arrays/primitive/compute/take/mod.rs +++ b/vortex-array/src/arrays/primitive/compute/take/mod.rs @@ -16,6 +16,8 @@ use vortex_error::vortex_err; use vortex_mask::Mask; use crate::ArrayRef; +use crate::Canonical; +use crate::Columnar; use crate::IntoArray; use crate::array::ArrayView; use crate::arrays::ConstantArray; @@ -23,7 +25,7 @@ use crate::arrays::PiecewiseSequence; use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; use crate::arrays::dict::TakeExecute; -use crate::arrays::piecewise_sequence::ConstantOrArray; +use crate::arrays::piecewise_sequence::constant_unsigned_usize; use crate::arrays::piecewise_sequence::maybe_contiguous_slices; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; @@ -150,12 +152,19 @@ fn take_contiguous_ranges( let validity = array.validity()?.take(indices_ref)?; let output_len = indices_ref.len(); let taken = match lengths { - ConstantOrArray::Constant(length) => { + Columnar::Constant(lengths) => { + let length = constant_unsigned_usize(&lengths)?; take_slices_constant_length(array, &starts, length, validity, output_len)? } - ConstantOrArray::Array(lengths) => { + Columnar::Canonical(Canonical::Primitive(lengths)) => { take_slices(array, &starts, &lengths, validity, output_len)? } + Columnar::Canonical(lengths) => { + vortex_bail!( + "PiecewiseSequenceArray lengths must be primitive or constant, got {}", + lengths.dtype() + ) + } }; Ok(Some(taken)) } From de798add422b02362ccbfd51afcb8d8e3b7ce42c Mon Sep 17 00:00:00 2001 From: Daniel King Date: Mon, 20 Jul 2026 12:46:23 -0400 Subject: [PATCH 20/20] Rely on PiecewiseSequence validation Signed-off-by: Daniel King --- vortex-array/src/arrays/bool/compute/take.rs | 13 ++---- .../src/arrays/decimal/compute/take.rs | 13 ++---- .../src/arrays/piecewise_sequence/mod.rs | 45 ++++++------------- .../src/arrays/primitive/compute/take/mod.rs | 12 ++--- 4 files changed, 23 insertions(+), 60 deletions(-) diff --git a/vortex-array/src/arrays/bool/compute/take.rs b/vortex-array/src/arrays/bool/compute/take.rs index c9b101b0f8a..14d90a5e7b1 100644 --- a/vortex-array/src/arrays/bool/compute/take.rs +++ b/vortex-array/src/arrays/bool/compute/take.rs @@ -8,13 +8,11 @@ use vortex_buffer::BitBufferMut; use vortex_buffer::BitBufferView; use vortex_buffer::get_bit; use vortex_error::VortexResult; -use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_error::vortex_err; use vortex_mask::Mask; use crate::ArrayRef; -use crate::Canonical; use crate::Columnar; use crate::IntoArray; use crate::array::ArrayView; @@ -85,7 +83,7 @@ fn take_contiguous_ranges( let output_len = indices_ref.len(); let buffer = match lengths { Columnar::Constant(lengths) => { - let length = constant_unsigned_usize(&lengths)?; + let length = constant_unsigned_usize(&lengths); match_each_unsigned_integer_ptype!(starts.ptype(), |S| { take_bit_slices_constant_length( &source, @@ -95,7 +93,8 @@ fn take_contiguous_ranges( )? }) } - Columnar::Canonical(Canonical::Primitive(lengths)) => { + Columnar::Canonical(lengths) => { + let lengths = lengths.into_primitive(); match_each_unsigned_integer_ptype!(starts.ptype(), |S| { match_each_unsigned_integer_ptype!(lengths.ptype(), |L| { take_bit_slices( @@ -107,12 +106,6 @@ fn take_contiguous_ranges( }) }) } - Columnar::Canonical(lengths) => { - vortex_bail!( - "PiecewiseSequenceArray lengths must be primitive or constant, got {}", - lengths.dtype() - ) - } }; Ok(Some( diff --git a/vortex-array/src/arrays/decimal/compute/take.rs b/vortex-array/src/arrays/decimal/compute/take.rs index 3ff63bf901e..31523c02a8a 100644 --- a/vortex-array/src/arrays/decimal/compute/take.rs +++ b/vortex-array/src/arrays/decimal/compute/take.rs @@ -5,12 +5,10 @@ use itertools::Itertools as _; use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_error::VortexResult; -use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_error::vortex_err; use crate::ArrayRef; -use crate::Canonical; use crate::Columnar; use crate::IntoArray; use crate::array::ArrayView; @@ -74,17 +72,12 @@ fn take_contiguous_ranges( let output_len = indices_ref.len(); let taken = match lengths { Columnar::Constant(lengths) => { - let length = constant_unsigned_usize(&lengths)?; + let length = constant_unsigned_usize(&lengths); take_slices_constant_length(array, &starts, length, validity, output_len)? } - Columnar::Canonical(Canonical::Primitive(lengths)) => { - take_slices(array, &starts, &lengths, validity, output_len)? - } Columnar::Canonical(lengths) => { - vortex_bail!( - "PiecewiseSequenceArray lengths must be primitive or constant, got {}", - lengths.dtype() - ) + let lengths = lengths.into_primitive(); + take_slices(array, &starts, &lengths, validity, output_len)? } }; Ok(Some(taken)) diff --git a/vortex-array/src/arrays/piecewise_sequence/mod.rs b/vortex-array/src/arrays/piecewise_sequence/mod.rs index 5ad9f60ca6e..05b7b13edf4 100644 --- a/vortex-array/src/arrays/piecewise_sequence/mod.rs +++ b/vortex-array/src/arrays/piecewise_sequence/mod.rs @@ -11,6 +11,7 @@ use itertools::Itertools; use num_traits::AsPrimitive; use vortex_buffer::BufferMut; +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; @@ -22,7 +23,6 @@ use crate::array::ArrayView; use crate::arrays::ConstantArray; use crate::arrays::PrimitiveArray; use crate::arrays::piecewise_sequence::array::PiecewiseSequenceArraySlotsExt; -use crate::dtype::DType; use crate::dtype::UnsignedPType; use crate::executor::ExecutionCtx; use crate::scalar::PValue; @@ -66,7 +66,6 @@ pub(crate) fn execute_index_arrays( let starts = array.starts().clone().execute::(ctx)?; let lengths = array.lengths().clone().execute::(ctx)?; let multipliers = array.multipliers().clone().execute::(ctx)?; - check_index_arrays(starts.as_ref(), lengths.as_ref(), multipliers.as_ref())?; Ok((starts, lengths, multipliers)) } @@ -78,17 +77,8 @@ pub(crate) fn maybe_contiguous_slices( return Ok(None); } - check_index_arrays(array.starts(), array.lengths(), array.multipliers())?; let starts = array.starts().clone().execute::(ctx)?; let lengths = array.lengths().clone().execute::(ctx)?; - check_index_array("starts", starts.as_ref())?; - check_index_columnar("lengths", &lengths)?; - vortex_ensure!( - starts.len() == lengths.len(), - "PiecewiseSequenceArray starts length {} does not match lengths length {}", - starts.len(), - lengths.len() - ); Ok(Some((starts, lengths))) } @@ -102,39 +92,32 @@ pub(crate) fn is_constant_one(multipliers: &ArrayRef) -> bool { ) } -pub(crate) fn constant_unsigned_usize(array: &ConstantArray) -> VortexResult { - let scalar = array.scalar(); - let Some(pvalue) = scalar.as_primitive_opt().and_then(|scalar| scalar.pvalue()) else { - vortex_bail!("PiecewiseSequenceArray constant length must be an unsigned integer"); - }; +pub(crate) fn constant_unsigned_usize(array: &ConstantArray) -> usize { + let pvalue = array + .scalar() + .as_primitive_opt() + .and_then(|scalar| scalar.pvalue()) + .vortex_expect("validated PiecewiseSequence length constants are primitive"); - Ok(match pvalue { + match pvalue { PValue::U8(value) => value as usize, PValue::U16(value) => value as usize, PValue::U32(value) => value as usize, PValue::U64(value) => value.as_(), - _ => vortex_bail!("PiecewiseSequenceArray constant length must be an unsigned integer"), - }) + _ => unreachable!("validated PiecewiseSequence length constants are unsigned"), + } } fn check_index_array(name: &str, array: &ArrayRef) -> VortexResult<()> { - check_index_dtype(name, array.dtype()) -} - -fn check_index_columnar(name: &str, columnar: &Columnar) -> VortexResult<()> { - check_index_dtype(name, columnar.dtype()) -} - -fn check_index_dtype(name: &str, dtype: &DType) -> VortexResult<()> { vortex_ensure!( - dtype.is_unsigned_int(), + array.dtype().is_unsigned_int(), "PiecewiseSequenceArray {name} must have unsigned integer dtype, got {}", - dtype + array.dtype() ); vortex_ensure!( - !dtype.is_nullable(), + !array.dtype().is_nullable(), "PiecewiseSequenceArray {name} must be non-nullable, got {}", - dtype + array.dtype() ); Ok(()) } diff --git a/vortex-array/src/arrays/primitive/compute/take/mod.rs b/vortex-array/src/arrays/primitive/compute/take/mod.rs index d80b0e5127c..70401fcd367 100644 --- a/vortex-array/src/arrays/primitive/compute/take/mod.rs +++ b/vortex-array/src/arrays/primitive/compute/take/mod.rs @@ -16,7 +16,6 @@ use vortex_error::vortex_err; use vortex_mask::Mask; use crate::ArrayRef; -use crate::Canonical; use crate::Columnar; use crate::IntoArray; use crate::array::ArrayView; @@ -153,17 +152,12 @@ fn take_contiguous_ranges( let output_len = indices_ref.len(); let taken = match lengths { Columnar::Constant(lengths) => { - let length = constant_unsigned_usize(&lengths)?; + let length = constant_unsigned_usize(&lengths); take_slices_constant_length(array, &starts, length, validity, output_len)? } - Columnar::Canonical(Canonical::Primitive(lengths)) => { - take_slices(array, &starts, &lengths, validity, output_len)? - } Columnar::Canonical(lengths) => { - vortex_bail!( - "PiecewiseSequenceArray lengths must be primitive or constant, got {}", - lengths.dtype() - ) + let lengths = lengths.into_primitive(); + take_slices(array, &starts, &lengths, validity, output_len)? } }; Ok(Some(taken))