Skip to content

Validate untrusted ListArray offsets lazily in consumers - #12353

Open
lwwmanning wants to merge 1 commit into
developfrom
wm/validate-list-offsets-lazily
Open

lwwmanning wants to merge 1 commit into
developfrom
wm/validate-list-offsets-lazily

Conversation

@lwwmanning

@lwwmanning lwwmanning commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #12099.

ListReader constructs ListArrays with ListArray::new_unchecked so reads stay O(1) without eagerly decoding or scanning offset buffers, which previously left downstream consumers vulnerable to panics, underflow, or invalid Arrow OffsetBuffers when a file contains negative, unsorted, or out-of-bounds offsets. This adds O(1) structural and bounded-endpoint validation in ListReader, and validates offset bounds and ordering lazily across all ListArray consumers (ListArrayExt, List::probe_scalar, ListBuilder, ListViewBuilder, ListArray::compact, list_view_from_list, ChunkedArray swizzle_list, list_to_list, take, and filter) so malformed offsets return a VortexError.

Behavior change: reading or consuming a ListLayout with negative, unsorted, or out-of-bounds offsets now returns an error instead of panicking or producing an invalid array.

Assisted by Antigravity.

@lwwmanning lwwmanning added the changelog/fix A bug fix label Nov 30, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-30T00:35:32.306438Z 8d2c76c New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@vortex-roborev-bot

vortex-roborev-bot Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

roborev: Combined Review (8d2c76c)

Verdict: Changes require fixes for 2 findings.

Low

  • vortex-array/src/arrays/list/rebuild.rs:49-64: 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.

  • vortex-arrow/src/executor/list.rs:136-189: 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.


Reviewers: claude-code | Synthesis: claude-code, 10s, ~$0.03 | Total: 2m5s, ~$1.04

@vortex-roborev-bot vortex-roborev-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Line comments for the roborev review of f4dcf7b. The roborev PR comment has the full review.

Comment on lines +137 to 190
/// 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)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment on lines +138 to +156
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}"
);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +316 to 317
validate_offsets_shape(row_count, &offsets)?;
let lengths = list_lengths_from_offsets(offsets)?;

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 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 👍 / 👎.

Comment on lines +221 to +224
/// 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

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 👍 / 👎.

Co-Authored-By: Antigravity <noreply@google.com>
Signed-off-by: Will Manning <will@willmanning.io>
@lwwmanning
lwwmanning force-pushed the wm/validate-list-offsets-lazily branch from f4dcf7b to 8d2c76c Compare November 30, 2026 00:33

@lwwmanning lwwmanning left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.rs ListExporter::export only checks the last offset, then computes next_offset - offset per row in u64. A ListLayout with 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_exporter takes the List path before canonicalizing, so a full ListReader read gets there directly. Calling validate_offset_slice_values on the executed offsets in new_exporter would fix it.
  • vortex-cuda/src/kernel/arrays/list.rs builds its views on the device, and ListViewArray::try_new skips 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 the reinterpret_cast(to_unsigned()) and match_each_unsigned_integer_ptype!. After the reinterpret, a negative offset is a huge unsigned value, and checked_list_range's end <= elements_len check 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_offsets and validate_arrow_offsets each re-check part of what validate_offset_slice_values checks. In list_view_from_list in particular, the new per-row vortex_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.

@vortex-roborev-bot vortex-roborev-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Line comments for the roborev review of 8d2c76c. The roborev PR comment has the full review.

Comment on lines 49 to 64
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());
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment on lines +136 to +189
/// 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

changelog/fix A bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant