Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 35 additions & 10 deletions vortex-array/src/arrays/chunked/vtable/canonical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use num_traits::AsPrimitive;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_ensure_eq;
use vortex_error::vortex_err;

use crate::ArrayRef;
Expand All @@ -25,11 +26,13 @@ use crate::arrays::chunked::ChunkedArrayExt;
use crate::arrays::chunked::array::ChunkedSlots;
use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt;
use crate::arrays::list::ListArraySlotsExt;
use crate::arrays::list::validate_offset_slice_values;
use crate::arrays::listview::ListViewArraySlotsExt;
use crate::arrays::struct_::StructArrayExt;
use crate::builders::ArrayBuilder;
use crate::builders::VariantBuilder;
use crate::dtype::DType;
use crate::dtype::IntegerPType;
use crate::match_each_integer_ptype;
use crate::matcher::Matcher;
use crate::validity::Validity;
Expand Down Expand Up @@ -181,17 +184,19 @@ fn list_window(
ctx: &mut ExecutionCtx,
) -> VortexResult<ElementWindow> {
let chunk_offsets = list.offsets().clone().execute::<PrimitiveArray>(ctx)?;
vortex_ensure_eq!(
chunk_offsets.len(),
list.len() + 1,
"ListArray must have one more offset than lists"
);
let elements_len = list.elements().len();
match_each_integer_ptype!(chunk_offsets.ptype(), |O| {
for ((out, size), pair) in offsets_out
.iter_mut()
.zip(sizes_out.iter_mut())
.zip(chunk_offsets.as_slice::<O>().windows(2))
{
let start: u64 = pair[0].as_();
let end: u64 = pair[1].as_();
*out = start;
*size = end - start;
}
fill_list_window(
chunk_offsets.as_slice::<O>(),
elements_len,
offsets_out,
sizes_out,
)?
});

let last = offsets_out.len() - 1;
Expand All @@ -203,6 +208,26 @@ fn list_window(
})
}

fn fill_list_window<O: IntegerPType + AsPrimitive<u64>>(
offsets: &[O],
elements_len: usize,
offsets_out: &mut [u64],
sizes_out: &mut [u64],
) -> VortexResult<()> {
validate_offset_slice_values(offsets, elements_len)?;
for ((out, size), pair) in offsets_out
.iter_mut()
.zip(sizes_out.iter_mut())
.zip(offsets.windows(2))
{
let start: u64 = pair[0].as_();
let end: u64 = pair[1].as_();
*out = start;
*size = end - start;
}
Ok(())
}

/// Writes the `u64` offsets and sizes of a [`ListView`] chunk and returns its element window.
fn list_view_window(
list: ArrayView<'_, ListView>,
Expand Down
187 changes: 147 additions & 40 deletions vortex-array/src/arrays/list/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ use std::fmt::Display;
use std::fmt::Formatter;
use std::sync::Arc;

use num_traits::AsPrimitive;
use num_traits::ToPrimitive;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure;
use vortex_error::vortex_ensure_eq;
use vortex_error::vortex_err;

use crate::ArrayRef;
use crate::ArraySlots;
Expand All @@ -33,7 +33,6 @@ use crate::builtins::ArrayBuiltins;
use crate::dtype::DType;
use crate::dtype::IntegerPType;
use crate::match_each_integer_ptype;
use crate::match_each_native_ptype;
use crate::optimizer::ArrayOptimizer;
use crate::scalar::NumericOperator;
use crate::scalar::ScalarValue;
Expand Down Expand Up @@ -98,7 +97,14 @@ pub struct ListSlots {
/// - Offsets must be non-nullable integers (i32, i64, etc.)
/// - Offsets array has length `n+1` where `n` is the number of lists
/// - List `i` contains elements from `elements[offsets[i]..offsets[i+1]]`
/// - Offsets must be monotonically increasing
/// - Valid offsets are non-negative, monotonically increasing, and bounded by `elements.len()`
///
/// [`ListArray::try_new`] eagerly validates all offset values on host-resident arrays. File readers
/// such as `ListReader` may instead construct a [`ListArray`] with [`ListArray::new_unchecked`]
/// after validating structural invariants (`offsets` dtype and length, validity length) in `O(1)`,
/// leaving offset values untrusted until read. Consumers that read offset values must therefore
/// validate them on consumption and return a [`vortex_error::VortexError`] on negative,
/// non-monotonic, or out-of-bounds offsets rather than assuming they are valid for memory safety.
///
/// # Examples
///
Expand Down Expand Up @@ -206,14 +212,17 @@ impl ListData {
///
/// # Safety
///
/// The caller must ensure all of the following invariants are satisfied:
/// The caller must ensure all structural invariants are satisfied:
///
/// - `offsets` must be a non-nullable integer array.
/// - `offsets` must have at least one element (even for empty lists, it should contain `[0]`).
/// - If `validity` is an array, its length must equal `offsets.len() - 1`.
///
/// - Offsets must be a non-nullable integer array.
/// - Offsets must have at least one element (even for empty lists, it should contain \[0\]).
/// - Offsets must be sorted (monotonically increasing).
/// - All offset values must be non-negative.
/// - The maximum offset must not exceed `elements.len()`.
/// - If validity is an array, its length must equal `offsets.len() - 1`.
/// Offset *values* (`0 <= offsets[i] <= offsets[i + 1] <= elements.len()`) are not required
/// for memory safety here: file readers may construct a `ListArray` in `O(1)` without scanning
/// offsets, and every consumer that reads offset values must validate them and return an error
/// on malformed offsets. Callers constructing in-memory lists from untrusted offsets that want
Comment on lines +221 to +224

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Retain value invariants until all offset consumers validate

A corrupt list returned by a full ListReader read can still panic when it is later canonicalized as part of a ChunkedArray: vortex-array/src/arrays/chunked/vtable/canonical.rs::list_window converts each offset with as_() and evaluates end - start without validation, so offsets such as [0, 3, 1, 4] underflow and negative signed offsets become huge unsigned values. The weakened safety contract is therefore unsound for this existing consumer; validate its offsets before arithmetic (and audit other direct offset readers) or keep these value invariants in the constructor contract.

Useful? React with 👍 / 👎.

/// eager validation should use [`ListArray::try_new`].
pub unsafe fn new_unchecked() -> Self {
Self
}
Expand Down Expand Up @@ -278,31 +287,11 @@ impl ListData {
where
P: IntegerPType + TryFrom<usize> + Into<ScalarValue>,
{
// Offsets must be sorted (but not strictly sorted, zero-length lists are allowed).
if let Some(idx) = offsets_slice.windows(2).position(|w| w[0] > w[1]) {
vortex_bail!(
"offsets must be sorted, but offset {} at index {idx} is greater than \
offset {} at index {}",
offsets_slice[idx],
offsets_slice[idx + 1],
idx + 1
);
}
validate_offset_slice_values(offsets_slice, elements_len)?;

// The offsets are sorted, thus the first offset is the minimum and the last
// offset is the maximum.
if let (Some(&min), Some(&max)) = (offsets_slice.first(), offsets_slice.last()) {
vortex_ensure!(
min >= P::zero(),
"offsets minimum {min} outside valid range [0, {max}]"
);

// An offset type too narrow for the elements length cannot exceed it.
vortex_ensure!(
P::try_from(elements_len).ok().is_none_or(|len| max <= len),
"Max offset {max} is beyond the length of the elements array {elements_len}"
);

// The checked values are exact, so keep them as statistics. This
// replaces any untrusted statistics on `offsets` and saves later scans.
let stats = offsets.statistics();
Expand All @@ -319,6 +308,103 @@ impl ListData {
// the offset type and manual subtraction.
}

/// Converts a single list offset to `usize`, rejecting negative values and values that do not fit.
#[inline]
pub(crate) fn checked_offset_to_usize<P: IntegerPType>(offset: P) -> VortexResult<usize> {
offset
.to_usize()
.ok_or_else(|| vortex_err!("List offset {offset} must be non-negative and fit in usize"))
}

/// Validates a single list's `[start, end)` offset pair against `elements_len`, returning
/// `(start, end)` guaranteed to satisfy `start <= end <= elements_len`.
#[inline]
pub(crate) fn checked_list_range<P: IntegerPType>(
start: P,
end: P,
elements_len: usize,
) -> VortexResult<(usize, usize)> {
let start_usize = checked_offset_to_usize(start)?;
let end_usize = checked_offset_to_usize(end)?;
vortex_ensure!(
start_usize <= end_usize,
"List offsets must be sorted, but start offset {start} exceeds end offset {end}"
);
vortex_ensure!(
end_usize <= elements_len,
"List offset {end} exceeds elements length {elements_len}"
);
Ok((start_usize, end_usize))
}

/// Validates that `offsets_slice` is non-empty, monotonically non-decreasing, non-negative,
/// and bounded by `elements_len`.
pub(crate) fn validate_offset_slice_values<P: IntegerPType>(
offsets_slice: &[P],
elements_len: usize,
) -> VortexResult<()> {
vortex_ensure!(
!offsets_slice.is_empty(),
"Offsets must have at least one element, [0] for an empty list"
);

// Check sortedness in fixed-size branchless chunks so LLVM auto-vectorizes the scan,
// and only search for the exact failing index on the cold error path.
if !is_sorted_chunked(offsets_slice)
&& let Some(idx) = offsets_slice.windows(2).position(|w| w[0] > w[1])
{
vortex_bail!(
"offsets must be sorted, but offset {} at index {idx} is greater than \
offset {} at index {}",
offsets_slice[idx],
offsets_slice[idx + 1],
idx + 1
);
}

// The offsets are sorted, thus the first offset is the minimum and the last
// offset is the maximum.
if let (Some(&min), Some(&max)) = (offsets_slice.first(), offsets_slice.last()) {
vortex_ensure!(
min >= P::zero(),
"offsets minimum {min} outside valid range [0, {max}]"
);

let max_usize = checked_offset_to_usize(max)?;
vortex_ensure!(
max_usize <= elements_len,
"Max offset {max} is beyond the length of the elements array {elements_len}"
);
}

Ok(())
}

/// Checks that `slice` is monotonically non-decreasing in fixed-size branchless chunks so LLVM
/// auto-vectorizes the comparison loop.
fn is_sorted_chunked<P: IntegerPType>(slice: &[P]) -> bool {
const CHUNK: usize = 64;
if slice.len() < 2 {
return true;
}
let (lhs_chunks, lhs_rem) = slice[..slice.len() - 1].as_chunks::<CHUNK>();
let (rhs_chunks, rhs_rem) = slice[1..].as_chunks::<CHUNK>();
for (a, b) in lhs_chunks.iter().zip(rhs_chunks.iter()) {
let mut sorted = true;
for i in 0..CHUNK {
sorted &= a[i] <= b[i];
}
if !sorted {
return false;
}
}
lhs_rem.iter().zip(rhs_rem).all(|(a, b)| a <= b)
}

fn primitive_offset_at<P: IntegerPType>(slice: &[P], index: usize) -> VortexResult<usize> {
checked_offset_to_usize(slice[index])
}

pub trait ListArrayExt: TypedArrayRef<List> {
fn nullability(&self) -> crate::dtype::Nullability {
match self.dtype() {
Expand All @@ -333,33 +419,54 @@ pub trait ListArrayExt: TypedArrayRef<List> {

fn offset_at(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<usize> {
vortex_ensure!(
index <= self.len(),
"Index {index} out of bounds 0..={}",
self.len()
index < self.offsets().len(),
"Index {index} out of bounds 0..{}",
self.offsets().len()
);

if let Some(p) = self.offsets().as_opt::<Primitive>() {
Ok(match_each_native_ptype!(p.ptype(), |P| {
p.as_slice::<P>()[index].as_()
}))
if let Some(p) = self.offsets().as_opt::<Primitive>()
&& p.buffer_handle().as_host_opt().is_some()
{
match_each_integer_ptype!(p.ptype(), |P| {
primitive_offset_at(p.as_slice::<P>(), index)
})
} else {
self.offsets()
.execute_scalar(index, ctx)?
.as_primitive()
.as_::<usize>()
.ok_or_else(|| vortex_error::vortex_err!("offset value does not fit in usize"))
.as_opt::<usize>()
.flatten()
.ok_or_else(|| vortex_err!("List offset must be non-negative and fit in usize"))
}
}

fn list_elements_at(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
let start = self.offset_at(index, ctx)?;
let end = self.offset_at(index + 1, ctx)?;
vortex_ensure!(
start <= end,
"List offsets must be sorted, but start offset {start} exceeds end offset {end} at index {index}"
);
vortex_ensure!(
end <= self.elements().len(),
"List offset {end} exceeds elements length {}",
self.elements().len()
);
self.elements().slice(start..end)?.optimize_ctx(ctx)
}

fn sliced_elements(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
let start = self.offset_at(0, ctx)?;
let end = self.offset_at(self.len(), ctx)?;
vortex_ensure!(
start <= end,
"List offsets must be sorted, but start offset {start} exceeds end offset {end}"
);
vortex_ensure!(
end <= self.elements().len(),
"List offset {end} exceeds elements length {}",
self.elements().len()
);
self.elements().slice(start..end)?.optimize_ctx(ctx)
}

Expand Down
Loading
Loading