Repository navigation
Validate untrusted ListArray offsets lazily in consumers - #12353
lwwmanning wants to merge 1 commit into
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
roborev: Combined Review (
|
| /// length `expected_len + 1`, non-negative, monotonically non-decreasing, and bounded by | ||
| /// `elements_len`. | ||
| fn validate_arrow_offsets<O: OffsetSizeTrait + NativePType>( | ||
| offsets: &[O], | ||
| expected_len: usize, | ||
| elements_len: usize, | ||
| ) -> VortexResult<()> { | ||
| vortex_ensure_eq!( | ||
| offsets.len(), | ||
| expected_len + 1, | ||
| "ListArray must have one more offset than lists" | ||
| ); | ||
| if !is_sorted_chunked(offsets) | ||
| && let Some(idx) = offsets.windows(2).position(|w| w[0] > w[1]) | ||
| { | ||
| vortex_bail!( | ||
| "List offsets must be sorted, but offset {} at index {idx} exceeds offset {} at index {}", | ||
| offsets[idx], | ||
| offsets[idx + 1], | ||
| idx + 1 | ||
| ); | ||
| } | ||
| let zero = O::usize_as(0); | ||
| let first = offsets[0]; | ||
| let last = offsets[expected_len]; | ||
| vortex_ensure!( | ||
| first >= zero, | ||
| "List start offset {first} must be non-negative" | ||
| ); | ||
| vortex_ensure!( | ||
| last.as_usize() <= elements_len, | ||
| "List max offset {last} exceeds elements length {elements_len}" | ||
| ); | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn is_sorted_chunked<O: OffsetSizeTrait>(slice: &[O]) -> 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) | ||
| } |
There was a problem hiding this comment.
Low: is_sorted_chunked copies the private helper in vortex-array/src/arrays/list/array.rs, and validate_arrow_offsets repeats most of validate_offset_slice_values (sorted order, first offset non-negative, last offset within the elements length). With two copies of this security-relevant validation, any future fix has to be made in both places.
Fix: Expose validate_offset_slice_values (currently pub(crate)) or a thin public wrapper from vortex-array, call it from list_to_list after the length check, and delete the duplicated helper and checks.
| vortex_ensure!( | ||
| end <= elements.len(), | ||
| "List end offset {end} exceeds elements length {}", | ||
| elements.len() | ||
| ); | ||
| if let (Some(&first_start), Some(&last_start)) = (starts.first(), starts.last()) { | ||
| vortex_ensure!( | ||
| first_start >= O::zero(), | ||
| "List start offset {first_start} must be non-negative" | ||
| ); | ||
| vortex_ensure!( | ||
| starts.windows(2).all(|w| w[0] <= w[1]), | ||
| "List offsets must be sorted" | ||
| ); | ||
| vortex_ensure!( | ||
| checked_offset_to_usize(last_start)? <= end, | ||
| "List start offset {last_start} exceeds end offset {end}" | ||
| ); | ||
| } |
There was a problem hiding this comment.
Low: ListArray::compact now validates the whole offsets slice up front, and then drop_unreferenced_elements scans starts again for non-negativity, sorted order and the end bound. That second O(n) pass does no useful work on the compact path. On the ListView rebuild_back_to_back path, the starts come from a zero-copy-to-list view and have already been reinterpreted as unsigned.
Fix: Validate in only one place, either by having callers guarantee the precondition or by turning the scan in drop_unreferenced_elements into a debug_assert!; compact must still return an error on malformed offsets, as the new tests require.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f4dcf7b520
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| validate_offsets_shape(row_count, &offsets)?; | ||
| let lengths = list_lengths_from_offsets(offsets)?; |
There was a problem hiding this comment.
Validate offset values before computing list lengths
For an offsets-only expression such as list_length, a file containing monotonic but invalid offsets bypasses the promised lazy validation because this checks only dtype and length before subtracting adjacent values. For example, offsets [-2, -1, 0] produce lengths [1, 1], and offsets [0, 2, 99] report an out-of-bounds list length even when the elements child has only four rows; neither case returns an error. Materialize and validate non-negativity, monotonicity, and the elements bound before deriving lengths.
Useful? React with 👍 / 👎.
| /// 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 |
There was a problem hiding this comment.
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 👍 / 👎.
Co-Authored-By: Antigravity <noreply@google.com> Signed-off-by: Will Manning <will@willmanning.io>
f4dcf7b to
8d2c76c
Compare
lwwmanning
left a comment
There was a problem hiding this comment.
Posted by Claude Opus 5.5 on Will's behalf.
The reader side now does what #12099 needed: only O(1) checks and lazy offsets, so list_read should be back at develop's numbers once CodSpeed reports.
The description says offsets are validated "across all ListArray consumers", and the new new_unchecked safety doc makes that a requirement. Two consumers outside vortex-array still trust the offsets:
vortex-duckdb/src/exporter/list.rsListExporter::exportonly checks the last offset, then computesnext_offset - offsetper row inu64. AListLayoutwith u32 offsets[0, 3, 1, 4]over 4 elements passes the check, and row 1's length wraps to 2^64 - 2 in release builds. DuckDB then reads far past the child vector.new_array_exportertakes theListpath before canonicalizing, so a fullListReaderread gets there directly. Callingvalidate_offset_slice_valueson the executed offsets innew_exporterwould fix it.vortex-cuda/src/kernel/arrays/list.rsbuilds its views on the device, andListViewArray::try_newskips validation for device buffers.
Please also name the new_unchecked contract change as a public API behaviour change in the description.
Two changes would shrink the diff:
- In
list/compute/take.rs, keep thereinterpret_cast(to_unsigned())andmatch_each_unsigned_integer_ptype!. After the reinterpret, a negative offset is a huge unsigned value, andchecked_list_range'send <= elements_lencheck already rejects it. Switching to signed offsets doubles the generic instantiations of the take kernel for no safety gain. build_sizes_from_offsets,drop_unreferenced_elements,filter_offsetsandvalidate_arrow_offsetseach re-check part of whatvalidate_offset_slice_valueschecks. Inlist_view_from_listin particular, the new per-rowvortex_ensure!in the sizes loop likely stops it from vectorizing, and it runs on every list canonicalization. Calling the shared vectorized validator once and keeping develop's plain loop would be smaller and probably faster.
| pub fn compact(&self, ctx: &mut ExecutionCtx) -> VortexResult<ListArray> { | ||
| let validity = self.list_validity(); | ||
| if validity.definitely_no_nulls() | ||
| && self.offset_at(0, ctx)? == 0 | ||
| && self.offset_at(self.len(), ctx)? == self.elements().len() | ||
| { | ||
| let offsets = self.offsets().clone().execute::<PrimitiveArray>(ctx)?; | ||
| vortex_ensure_eq!( | ||
| offsets.len(), | ||
| self.len() + 1, | ||
| "ListArray must have one more offset than lists" | ||
| ); | ||
| let elements_len = self.elements().len(); | ||
| let (first, last) = match_each_integer_ptype!(offsets.ptype(), |P| { | ||
| validate_and_endpoints(offsets.as_slice::<P>(), elements_len)? | ||
| }); | ||
|
|
||
| if validity.definitely_no_nulls() && first == 0 && last == elements_len { | ||
| return Ok(self.clone()); | ||
| } |
There was a problem hiding this comment.
Low: ListArray::compact no longer returns early in O(1) when the list is already compact. It now decodes the offsets to a PrimitiveArray and scans them all with validate_offset_slice_values before the compactness check. So an already-compact list with encoded offsets gets fully decoded and scanned just to return self.clone(). This path is reached through the compressor's reset_offsets(recurse=true) and Canonical::compact.
Fix: Check the endpoints first with offset_at(0) and offset_at(len), return early when definitely_no_nulls() holds and the endpoints span all elements, and materialize and validate the offsets only on the rebuild path.
| /// Validates that `offsets` satisfies Arrow `OffsetBuffer` and `GenericListArray` invariants: | ||
| /// length `expected_len + 1`, non-negative, monotonically non-decreasing, and bounded by | ||
| /// `elements_len`. | ||
| fn validate_arrow_offsets<O: OffsetSizeTrait + NativePType>( | ||
| offsets: &[O], | ||
| expected_len: usize, | ||
| elements_len: usize, | ||
| ) -> VortexResult<()> { | ||
| vortex_ensure_eq!( | ||
| offsets.len(), | ||
| expected_len + 1, | ||
| "ListArray must have one more offset than lists" | ||
| ); | ||
| if !is_sorted_chunked(offsets) | ||
| && let Some(idx) = offsets.windows(2).position(|w| w[0] > w[1]) | ||
| { | ||
| vortex_bail!( | ||
| "List offsets must be sorted, but offset {} at index {idx} exceeds offset {} at index {}", | ||
| offsets[idx], | ||
| offsets[idx + 1], | ||
| idx + 1 | ||
| ); | ||
| } | ||
| let zero = O::usize_as(0); | ||
| let first = offsets[0]; | ||
| let last = offsets[expected_len]; | ||
| vortex_ensure!( | ||
| first >= zero, | ||
| "List start offset {first} must be non-negative" | ||
| ); | ||
| vortex_ensure!( | ||
| last.as_usize() <= elements_len, | ||
| "List max offset {last} exceeds elements length {elements_len}" | ||
| ); | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn is_sorted_chunked<O: OffsetSizeTrait>(slice: &[O]) -> 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) |
There was a problem hiding this comment.
Low: Offset validation is duplicated. validate_arrow_offsets and is_sorted_chunked copy the sort/min/max checks from vortex-array/src/arrays/list/array.rs. drop_unreferenced_elements also adds its own unvectorized starts.windows(2).all(..) scan, even though on the ListArray path compact has already validated the same offsets, so they get scanned twice.
Fix: Expose one public helper in vortex-array (for example validate_list_offsets(&[P], elements_len)) and call it from the Arrow exporter, and remove the second sortedness scan in drop_unreferenced_elements or have only the ListView caller validate.
Follow-up to #12099.
ListReaderconstructsListArrays withListArray::new_uncheckedso reads stayO(1)without eagerly decoding or scanning offset buffers, which previously left downstream consumers vulnerable to panics, underflow, or invalid ArrowOffsetBuffers when a file contains negative, unsorted, or out-of-bounds offsets. This addsO(1)structural and bounded-endpoint validation inListReader, and validates offset bounds and ordering lazily across allListArrayconsumers (ListArrayExt,List::probe_scalar,ListBuilder,ListViewBuilder,ListArray::compact,list_view_from_list,ChunkedArrayswizzle_list,list_to_list,take, andfilter) so malformed offsets return aVortexError.Behavior change: reading or consuming a
ListLayoutwith negative, unsorted, or out-of-bounds offsets now returns an error instead of panicking or producing an invalid array.Assisted by Antigravity.