Skip to content
Merged
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
279 changes: 276 additions & 3 deletions crates/data/src/source/parquet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1296,6 +1296,7 @@ fn column_reader_within(rg: &dyn RowGroupReader, col: usize, limit: u64) -> Resu
chunk_values: u64::try_from(chunk.num_values()).ok().filter(|&n| n > 0).unwrap_or(u64::MAX),
note: note.clone(),
column: desc.path().string(),
dictionary: Dictionary::default(),
};
Ok((parquet::column::reader::get_column_reader(desc, Box::new(pages)), note))
}
Expand Down Expand Up @@ -1421,6 +1422,16 @@ struct CheckedPages {
note: Arc<PageNote>,
/// The column's name (its path), which a refusal names.
column: String,
dictionary: Dictionary,
}

/// What has become of a column's dictionary page.
#[derive(Default)]
struct Dictionary {
/// It has been handed over.
given: bool,
/// The one a skip passed over, held until it is asked for.
skipped: Option<parquet::column::page::Page>,
}

impl Iterator for CheckedPages {
Expand Down Expand Up @@ -1470,6 +1481,67 @@ impl CheckedPages {
Ok(len)
}

/// Refuses a data page of indices into a dictionary the column doesn't have, which the crate's
/// decoder panics on (`parquet` 60.2.0 `ColumnValueDecoderImpl::set_data`). The crate asks for one a
/// skip passed over only once it has the page, so it is taken here and held for then.
fn check_dictionary(&mut self, page: &parquet::column::page::Page) -> parquet::errors::Result<()> {
use parquet::column::page::{Page, PageReader};
match page {
Page::DictionaryPage { .. } => self.dictionary.given = true,
Page::DataPage { encoding, .. } | Page::DataPageV2 { encoding, .. } => {
if !matches!(encoding, Encoding::PLAIN_DICTIONARY | Encoding::RLE_DICTIONARY) || self.dictionary.given {
return Ok(());
}
if self.dictionary.skipped.is_none() {
self.dictionary.skipped = self.take_deferred_dictionary()?;
}
if self.dictionary.skipped.is_none() {
return Err(parquet::errors::ParquetError::General(
"a page uses a dictionary, which its column chunk doesn't have".into(),
));
}
}
}
Ok(())
}

/// Refuses a data page whose levels are longer than it is: the crate slices the page by their
/// lengths (`parquet` 60.2.0 `read_new_page`, `parse_v1_level`). A version 1 page's RLE levels, whose
/// length the crate checks, are walked to find where the bit-packed ones start.
fn check_levels(&self, page: &parquet::column::page::Page) -> parquet::errors::Result<()> {
use parquet::column::page::Page;
let (bytes, len) = match page {
Page::DataPage { buf, num_values, def_level_encoding, rep_level_encoding, .. } => {
#[expect(deprecated, reason = "BIT_PACKED levels are deprecated but still read")]
let packed = Encoding::BIT_PACKED;
// A stream's place is known from those in front of it. One whose length is cut off is an
// error of the crate's, unless those in front already run past the page.
let mut at = 0u64;
for (max, encoding) in [(self.max_rep, rep_level_encoding), (self.max_def, def_level_encoding)] {
if max <= 0 {
continue;
}
if *encoding == packed {
at = at.saturating_add(packed_levels(max, *num_values));
} else {
let prefix = usize::try_from(at).ok().and_then(|at| buf.get(at..at.checked_add(4)?));
let Some(prefix) = prefix.and_then(|b| <[u8; 4]>::try_from(b).ok()) else { break };
at = at.saturating_add(4).saturating_add(u64::from(u32::from_le_bytes(prefix)));
}
}
(at, buf.len())
}
Page::DataPageV2 { buf, def_levels_byte_len, rep_levels_byte_len, .. } => {
(u64::from(*def_levels_byte_len).saturating_add(u64::from(*rep_levels_byte_len)), buf.len())
}
Page::DictionaryPage { .. } => return Ok(()),
};
if bytes > u64::try_from(len).unwrap_or(u64::MAX) {
return Err(parquet::errors::ParquetError::General(format!("a page's levels take {bytes} bytes, more than its {len}")));
}
Ok(())
}

/// Refuses a DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY data page whose streams say they hold
/// more values than the page or the column chunk does, or whose arrays the decoder would make
/// for them (4 bytes a value for each stream, `parquet` 60.2.0 `set_data`) are more than the
Expand All @@ -1496,9 +1568,7 @@ impl CheckedPages {
let len = prefix.map(u32::from_le_bytes).and_then(|n| usize::try_from(n).ok());
len.and_then(|n| n.checked_add(4)).ok_or_else(|| delta_err("its levels are cut off"))?
} else if *level_encoding == bit_packed {
let bits = u64::from(u64::BITS - u64::try_from(max).unwrap_or(0).leading_zeros());
let bytes = (u64::from(*num_values).saturating_mul(bits)).div_ceil(8);
usize::try_from(bytes).map_err(|_| delta_err("its levels are cut off"))?
usize::try_from(packed_levels(max, *num_values)).map_err(|_| delta_err("its levels are cut off"))?
} else {
return Err(delta_err(&format!("its levels are in the {level_encoding} encoding, which a page can't have")));
};
Expand Down Expand Up @@ -1550,6 +1620,12 @@ impl CheckedPages {
}
}

/// The bytes of a version 1 page's BIT_PACKED levels of up to `max`, one for each value.
fn packed_levels(max: i16, values: u32) -> u64 {
let bits = u64::from(u64::BITS - u64::try_from(max).unwrap_or(0).leading_zeros());
u64::from(values).saturating_mul(bits).div_ceil(8)
}

fn delta_err(what: &str) -> parquet::errors::ParquetError {
parquet::errors::ParquetError::General(format!("a delta page is refused: {what}"))
}
Expand Down Expand Up @@ -1711,7 +1787,9 @@ impl parquet::column::page::PageReader for CheckedPages {
"a page uses the {encoding} encoding, which its column chunk doesn't list"
))));
}
self.check_dictionary(page).map_err(|e| self.named(e))?;
self.check_delta(page).map_err(|e| self.named(e))?;
self.check_levels(page).map_err(|e| self.named(e))?;
if let parquet::column::page::Page::DataPage { num_values, .. } | parquet::column::page::Page::DataPageV2 { num_values, .. } =
page
{
Expand Down Expand Up @@ -1765,6 +1843,10 @@ impl parquet::column::page::PageReader for CheckedPages {
/// The dictionary a skip passed over, checked as a dictionary page read in turn is, now that a
/// page needs it.
fn take_deferred_dictionary(&mut self) -> parquet::errors::Result<Option<parquet::column::page::Page>> {
if let Some(page) = self.dictionary.skipped.take() {
self.dictionary.given = true;
return Ok(Some(page));
}
let page = self.pages.take_deferred_dictionary()?;
if let Some(page) = &page {
self.check_size(page)?;
Expand Down Expand Up @@ -3101,6 +3183,7 @@ mod tests {
chunk_values: u64::MAX,
note: Arc::new(PageNote::default()),
column: "height".into(),
dictionary: Dictionary::default(),
}
.get_next_page()
}
Expand All @@ -3127,6 +3210,191 @@ mod tests {
}
}

/// A page of indices needs a dictionary: the column's own, or one a skip passed over, which is
/// handed over when it is asked for. (A fuzzed GeoParquet's page said it was one, #3309.)
#[test]
fn checked_pages_refuse_a_page_of_indices_without_a_dictionary() {
/// Pages whose dictionary a skip has passed over.
struct Skipped(Pages, Option<Page>);
impl Iterator for Skipped {
type Item = parquet::errors::Result<Page>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
impl PageReader for Skipped {
fn get_next_page(&mut self) -> parquet::errors::Result<Option<Page>> {
self.0.get_next_page()
}
fn peek_next_page(&mut self) -> parquet::errors::Result<Option<PageMetadata>> {
Ok(None)
}
fn skip_next_page(&mut self) -> parquet::errors::Result<()> {
Ok(())
}
fn take_deferred_dictionary(&mut self) -> parquet::errors::Result<Option<Page>> {
Ok(self.1.take())
}
}
let dictionary =
|| Page::DictionaryPage { buf: Bytes::from(vec![0u8; 4]), num_values: 1, encoding: Encoding::PLAIN, is_sorted: false };
let read = |pages: Vec<Page>, skipped: Option<Page>| CheckedPages {
pages: Box::new(Skipped(Pages(pages.into_iter()), skipped)),
bits: 32,
limit: u64::MAX,
chunk_bytes: None,
delta_listed: [false; 2],
max_def: 0,
max_rep: 0,
chunk_values: u64::MAX,
note: Arc::new(PageNote::default()),
column: "height".into(),
dictionary: Dictionary::default(),
};
for encoding in [Encoding::PLAIN_DICTIONARY, Encoding::RLE_DICTIONARY] {
for page in [data_page(4, encoding), data_page_v2(4, encoding)] {
let error = read(vec![page.clone()], None).get_next_page().unwrap_err().to_string();
assert!(error.contains("column height: a page uses a dictionary, which its column chunk doesn't have"), "{error}");
let mut pages = read(vec![dictionary(), page.clone(), page.clone()], None);
assert!((0..3).all(|_| pages.get_next_page().unwrap().is_some()));
let mut pages = read(vec![page.clone(), page.clone()], Some(dictionary()));
assert!(pages.get_next_page().unwrap().is_some());
assert!(matches!(pages.take_deferred_dictionary().unwrap(), Some(Page::DictionaryPage { .. })));
assert!(pages.take_deferred_dictionary().unwrap().is_none());
assert!(pages.get_next_page().unwrap().is_some());
}
}
}

/// The same of a whole file: an error, where the decoder panicked.
#[test]
fn a_file_whose_page_needs_a_dictionary_it_lacks_is_an_error() {
use arrow_array::{ArrayRef, BinaryArray, RecordBatch};
let column: ArrayRef = Arc::new(BinaryArray::from(vec![&b"aa"[..], b"bb", b"aa"]));
let batch = RecordBatch::try_from_iter([("g", column)]).unwrap();
let mut bytes = Vec::new();
let mut writer = ::parquet::arrow::ArrowWriter::try_new(&mut bytes, batch.schema(), None).unwrap();
writer.write(&batch).unwrap();
writer.close().unwrap();
let reader = SerializedFileReader::new(Bytes::from(bytes)).unwrap();
let chunk = reader.metadata().row_group(0).column(0);
assert!(chunk.dictionary_page_offset().is_some());
let rg = reader.get_row_group(0).unwrap();
let mut pages = rg.get_column_page_reader(0).unwrap();
// The file's pages without its dictionary.
assert!(matches!(pages.get_next_page().unwrap(), Some(Page::DictionaryPage { .. })));
let checked = CheckedPages {
pages,
bits: 32,
limit: u64::MAX,
chunk_bytes: None,
delta_listed: [false; 2],
max_def: 1,
max_rep: 0,
chunk_values: 3,
note: Arc::new(PageNote::default()),
column: "g".into(),
dictionary: Dictionary::default(),
};
let ColumnReader::ByteArrayColumnReader(mut r) =
parquet::column::reader::get_column_reader(chunk.column_descr_ptr(), Box::new(checked))
else {
panic!("bytes")
};
let error = read_column(&mut r, &[true; 3], 1).unwrap_err().to_string();
assert!(error.contains("a page uses a dictionary"), "{error}");
}

/// Levels said to be longer than their page, which the crate slices by what is said.
#[test]
fn checked_pages_refuse_levels_longer_than_their_page() {
#[expect(deprecated, reason = "BIT_PACKED levels are deprecated but still read")]
let packed = Encoding::BIT_PACKED;
let v1 = |num_values| Page::DataPage {
buf: Bytes::from(vec![0u8; 4]),
num_values,
encoding: Encoding::PLAIN,
def_level_encoding: packed,
rep_level_encoding: Encoding::RLE,
statistics: None,
};
let v2 = |def_levels_byte_len, rep_levels_byte_len| Page::DataPageV2 {
buf: Bytes::from(vec![0u8; 4]),
num_values: 1,
encoding: Encoding::PLAIN,
num_nulls: 0,
num_rows: 1,
def_levels_byte_len,
rep_levels_byte_len,
is_compressed: false,
statistics: None,
};
for long in [v1(33), v1(u32::MAX), v2(5, 0), v2(2, 3), v2(u32::MAX, 2)] {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

checked_in always sets max_rep: 0, so none of these cases reaches the repetition-level path: the RLE prefix walk and the bit-packed offset for max_rep > 0. That path is new code, and the test list doesn't exercise it. A case with max_rep set, such as a version 1 page whose repetition RLE prefix claims more bytes than the page holds, would cover it.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added in 4e9ceee: packed repetition levels past the page, an RLE length past it, packed definition levels that don't fit after one, and a page where both fit.

let error = checked_in(long, 1, u64::MAX, u64::MAX).unwrap_err().to_string();
assert!(error.contains("a page's levels take"), "{error}");
}
for fits in [v1(32), v2(4, 0), v2(2, 2)] {
assert!(checked_in(fits, 1, u64::MAX, u64::MAX).unwrap().is_some());
}
// A column with repetition levels too, in front of the definition levels.
let both = |buf: Vec<u8>, num_values, rep, def| {
CheckedPages {
pages: Box::new(Pages(
vec![Page::DataPage {
buf: Bytes::from(buf),
num_values,
encoding: Encoding::PLAIN,
def_level_encoding: def,
rep_level_encoding: rep,
statistics: None,
}]
.into_iter(),
)),
bits: 32,
limit: u64::MAX,
chunk_bytes: None,
delta_listed: [false; 2],
max_def: 3,
max_rep: 1,
chunk_values: u64::MAX,
note: Arc::new(PageNote::default()),
column: "c".into(),
dictionary: Dictionary::default(),
}
.get_next_page()
};
let rle = Encoding::RLE;
for (buf, n, rep, def) in [
// Packed repetition levels past the page, where the length after them would be.
(vec![0; 4], 33, packed, rle),
// An RLE length past the page, and packed definition levels that don't fit after one.
(vec![9, 0, 0, 0], 1, rle, packed),
(vec![1, 0, 0, 0, 0, 0], 8, rle, packed),
] {
let error = both(buf, n, rep, def).unwrap_err().to_string();
assert!(error.contains("a page's levels take"), "{error}");
}
// One byte of each fits; a length that is cut off is left to the crate, which refuses it.
assert!(both(vec![1, 0, 0, 0, 0, 0], 4, rle, packed).unwrap().is_some());
for cut in [vec![0; 2], vec![0; 4]] {
let descr = std::sync::Arc::new(parquet::schema::types::ColumnDescriptor::new(
std::sync::Arc::new(parquet::schema::types::Type::primitive_type_builder("c", Physical::INT32).build().unwrap()),
3,
1,
parquet::schema::types::ColumnPath::from("c"),
));
let page = both(cut, 1, rle, rle).unwrap().unwrap();
let ColumnReader::Int32ColumnReader(mut r) =
parquet::column::reader::get_column_reader(descr, Box::new(Pages(vec![page].into_iter())))
else {
panic!("numbers")
};
let (mut defs, mut reps, mut values) = (vec![], vec![], vec![]);
let error = r.read_records(1, Some(&mut defs), Some(&mut reps), &mut values).unwrap_err().to_string();
assert!(error.contains("not enough data to read levels"), "{error}");
}
}

/// A footer that gives no usable size (zero or negative) is read as no size, not as a large one.
#[test]
fn checked_pages_take_the_limit_for_a_footer_without_a_size() {
Expand Down Expand Up @@ -3182,6 +3450,7 @@ mod tests {
chunk_values: u64::MAX,
note: Arc::new(PageNote::default()),
column: "height".into(),
dictionary: Dictionary::default(),
}
.get_next_page()
}
Expand Down Expand Up @@ -3255,6 +3524,7 @@ mod tests {
chunk_values: u64::MAX,
note: note.clone(),
column: "c".into(),
dictionary: Dictionary::default(),
};
assert!(pages.get_next_page().unwrap().is_some());
assert_eq!((note.page.load(Ordering::Relaxed), note.in_page.load(Ordering::Relaxed)), (40, 1));
Expand Down Expand Up @@ -3382,6 +3652,7 @@ mod tests {
chunk_values,
note,
column: "c".into(),
dictionary: Dictionary::default(),
}
.get_next_page()
}
Expand Down Expand Up @@ -3668,6 +3939,7 @@ mod tests {
chunk_values: u64::MAX,
note: Arc::new(PageNote::default()),
column: "c".into(),
dictionary: Dictionary::default(),
};
assert!(pages.get_next_page().unwrap().is_some());
}
Expand Down Expand Up @@ -3716,6 +3988,7 @@ mod tests {
chunk_values: u64::MAX,
note: note.clone(),
column: "c".into(),
dictionary: Dictionary::default(),
};
let budget = Budget::new(1 << 20, 0);
let pace = Pace { watch: Some((&note, &budget)) };
Expand Down
Loading