diff --git a/parquet/benches/push_decoder.rs b/parquet/benches/push_decoder.rs index 3d98086bee06..cb0a206c0a9c 100644 --- a/parquet/benches/push_decoder.rs +++ b/parquet/benches/push_decoder.rs @@ -9,13 +9,16 @@ //! //! The `scan_plan` group measures `ParquetPushDecoder::scan_plan` for wide //! schemas with a page index. +//! +//! The `decode` and `decode_8192` groups decode a file with `try_decode`, for +//! each [`RequestGranularity`]. use std::hint::black_box; use std::ops::Range; use std::sync::Arc; use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; -use arrow_array::{Float32Array, RecordBatch}; +use arrow_array::{Float32Array, RecordBatch, StringArray}; use bytes::Bytes; use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; use parquet::DecodeResult; @@ -24,7 +27,7 @@ use parquet::arrow::ProjectionMask; use parquet::arrow::arrow_reader::{ ArrowReaderMetadata, ArrowReaderOptions, RowSelection, RowSelector, }; -use parquet::arrow::push_decoder::ParquetPushDecoderBuilder; +use parquet::arrow::push_decoder::{ParquetPushDecoderBuilder, RequestGranularity}; use parquet::file::metadata::{PageIndexPolicy, ParquetMetaDataPushDecoder}; use parquet::file::properties::WriterProperties; @@ -311,11 +314,121 @@ fn bench_scan_plan(c: &mut Criterion) { group.finish(); } +/// The benchmark name of each [`RequestGranularity`]. +const GRANULARITIES: [(&str, RequestGranularity); 2] = [ + ("row_group", RequestGranularity::RowGroup), + ("batch", RequestGranularity::Batch), +]; + +/// Decode the file with `try_decode`. Push exactly the ranges that the +/// decoder requests. Returns the number of rows. +fn decode_file(builder: ParquetPushDecoderBuilder, file_data: &Bytes) -> usize { + let mut decoder = builder.build().unwrap(); + let mut num_rows = 0; + loop { + match decoder.try_decode().unwrap() { + DecodeResult::NeedsData(ranges) => { + let data = ranges + .iter() + .map(|r| file_data.slice(r.start as usize..r.end as usize)) + .collect(); + decoder.push_ranges(ranges, data).unwrap(); + } + DecodeResult::Data(batch) => num_rows += batch.num_rows(), + DecodeResult::Finished => return num_rows, + } + } +} + +/// Decode 10 columns and 1,000 rows with small batches, so that the cost of +/// one request is large next to the decode work. +/// +/// `row_group` and `batch` are the [`RequestGranularity`] of the decoder. +/// `10pages_100batch` has one page per batch. `100pages_10batch` has small +/// pages and small batches. +fn bench_decode(c: &mut Criterion) { + let mut group = c.benchmark_group("push_decoder/decode"); + + for (pages, batch_size) in [(10, 100), (100, 10)] { + let file_data = make_paged_test_file(10, pages); + let options = ArrowReaderOptions::new().with_page_index_policy(PageIndexPolicy::Required); + let metadata = ArrowReaderMetadata::load(&file_data, options).unwrap(); + + let id = format!("{pages}pages_{batch_size}batch"); + for (name, granularity) in GRANULARITIES { + group.bench_function(BenchmarkId::new(name, &id), |b| { + b.iter(|| { + let builder = ParquetPushDecoderBuilder::new_with_metadata(metadata.clone()) + .with_batch_size(batch_size) + .with_request_granularity(granularity); + black_box(decode_file(builder, &file_data)) + }) + }); + } + } + + group.finish(); +} + +/// Decode a file with one `f32` column and one string column in batches of +/// 8,192 rows. The file has 1,000,000 rows in one row group and uses the +/// default writer properties. +/// +/// `low_cardinality` has 1,000 distinct strings, so the writer uses dictionary +/// pages. `unique` has 1,000,000 distinct strings. +fn bench_decode_large_batches(c: &mut Criterion) { + let mut group = c.benchmark_group("push_decoder/decode_8192"); + group.sample_size(20); + + let num_rows = 1_000_000usize; + let schema = Arc::new(Schema::new(vec![ + Field::new("f", DataType::Float32, false), + Field::new("s", DataType::Utf8, false), + ])); + + for (strings, distinct) in [("low_cardinality", 1_000), ("unique", num_rows)] { + // Spread the values, so that the columns are not sorted. + let shuffle = |row: usize| row.wrapping_mul(2_654_435_761) % num_rows; + let floats = Float32Array::from_iter_values((0..num_rows).map(|row| shuffle(row) as f32)); + let strings_array = StringArray::from_iter_values( + (0..num_rows).map(|row| format!("customer-{:012}", shuffle(row) % distinct)), + ); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(floats), Arc::new(strings_array)], + ) + .unwrap(); + let mut buf = Vec::new(); + let mut writer = ArrowWriter::try_new(&mut buf, schema.clone(), None).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + let file_data = Bytes::from(buf); + + let options = ArrowReaderOptions::new().with_page_index_policy(PageIndexPolicy::Required); + let metadata = ArrowReaderMetadata::load(&file_data, options).unwrap(); + + for (name, granularity) in GRANULARITIES { + group.bench_function(BenchmarkId::new(name, strings), |b| { + b.iter(|| { + let builder = ParquetPushDecoderBuilder::new_with_metadata(metadata.clone()) + .with_batch_size(8192) + .with_request_granularity(granularity); + black_box(decode_file(builder, &file_data)) + }) + }); + } + } + + group.finish(); +} + criterion_group!( benches, bench_1buf, bench_nbuf, bench_prefetch, - bench_scan_plan + bench_scan_plan, + bench_decode, + bench_decode_large_batches ); criterion_main!(benches); diff --git a/parquet/src/arrow/arrow_reader/mod.rs b/parquet/src/arrow/arrow_reader/mod.rs index 37d88eb47761..25b40b9a88df 100644 --- a/parquet/src/arrow/arrow_reader/mod.rs +++ b/parquet/src/arrow/arrow_reader/mod.rs @@ -1576,7 +1576,7 @@ impl FilterMaskAccumulator { } /// Converts the projection buffered by `array_reader` into a record batch. -fn consume_record_batch(array_reader: &mut dyn ArrayReader) -> Result { +pub(crate) fn consume_record_batch(array_reader: &mut dyn ArrayReader) -> Result { let array = array_reader.consume_batch()?; let struct_array = array.as_struct_opt().ok_or_else(|| { ArrowError::ParquetError("Struct array reader should return struct array".to_string()) diff --git a/parquet/src/arrow/arrow_reader/selection/cursor.rs b/parquet/src/arrow/arrow_reader/selection/cursor.rs index 11f001f45df4..a3c551afa15f 100644 --- a/parquet/src/arrow/arrow_reader/selection/cursor.rs +++ b/parquet/src/arrow/arrow_reader/selection/cursor.rs @@ -384,7 +384,8 @@ impl LoadedRowRanges { Self(ranges) } - fn end_containing(&self, row: usize) -> Option { + /// The end of the loaded range that holds `row`, if any. + pub(crate) fn end_containing(&self, row: usize) -> Option { let idx = self.0.partition_point(|range| range.end <= row); self.0 .get(idx) diff --git a/parquet/src/arrow/arrow_reader/selection/ranges.rs b/parquet/src/arrow/arrow_reader/selection/ranges.rs index c7625911fa94..b9ec2fc29fab 100644 --- a/parquet/src/arrow/arrow_reader/selection/ranges.rs +++ b/parquet/src/arrow/arrow_reader/selection/ranges.rs @@ -48,6 +48,10 @@ pub(super) fn scan_ranges_from_mask( } /// Byte ranges of the data pages containing at least one selected row. +/// +/// The cost is `O(log pages)` for each skip and `O(pages)` for each selected +/// run in the pages that it covers. Thus, a selection of a few rows of a +/// large column chunk does not visit all pages. #[inline] pub(super) fn scan_ranges_from_selectors( selectors: I, @@ -57,40 +61,44 @@ where I: IntoIterator, { let mut ranges: Vec> = vec![]; + if page_locations.is_empty() { + return ranges; + } + // The first row that the selectors did not cover yet let mut row_offset = 0; - - let mut pages = page_locations.iter().peekable(); - let mut selectors = selectors.into_iter(); - let mut current_selector = selectors.next(); - let mut current_page = pages.next(); - + // The page that holds `row_offset` + let mut page_idx = 0; let mut current_page_included = false; - while let Some((selector, page)) = current_selector.as_mut().zip(current_page) { - if !(selector.skip || current_page_included) { - let start = page.offset as u64; - let end = start + page.compressed_page_size as u64; - ranges.push(start..end); - current_page_included = true; - } - - if let Some(next_page) = pages.peek() { - if row_offset + selector.row_count > next_page.first_row_index as usize { - let remaining_in_page = next_page.first_row_index as usize - row_offset; - selector.row_count -= remaining_in_page; - row_offset += remaining_in_page; - current_page = pages.next(); + for selector in selectors { + let end = row_offset + selector.row_count; + if selector.skip { + // Go to the page that holds the first row after the skip + let after = page_locations[page_idx..] + .partition_point(|page| page.first_row_index as usize <= end); + if after > 1 { + page_idx += after - 1; current_page_included = false; - } else { - if row_offset + selector.row_count == next_page.first_row_index as usize { - current_page = pages.next(); + } + row_offset = end; + continue; + } + // Include each page that holds a row of this run + while row_offset < end { + let page = &page_locations[page_idx]; + if !current_page_included { + let start = page.offset as u64; + ranges.push(start..start + page.compressed_page_size as u64); + current_page_included = true; + } + match page_locations.get(page_idx + 1) { + Some(next_page) if next_page.first_row_index as usize <= end => { + row_offset = next_page.first_row_index as usize; + page_idx += 1; current_page_included = false; } - row_offset += selector.row_count; - current_selector = selectors.next(); + _ => row_offset = end, } - } else { - current_selector = selectors.next() } } @@ -139,6 +147,69 @@ where mod tests { use super::*; + /// The scan that visits every page, as a reference. + fn scan_all_pages(selectors: &[RowSelector], pages: &[PageLocation]) -> Vec> { + let mut ranges = vec![]; + let mut row = 0; + for selector in selectors { + let run = row..row + selector.row_count; + row = run.end; + if selector.skip || run.is_empty() { + continue; + } + for (idx, page) in pages.iter().enumerate() { + let first = page.first_row_index as usize; + let end = pages + .get(idx + 1) + .map_or(usize::MAX, |next| next.first_row_index as usize); + let range = + page.offset as u64..(page.offset + page.compressed_page_size as i64) as u64; + if first < run.end && run.start < end && ranges.last() != Some(&range) { + ranges.push(range); + } + } + } + ranges + } + + #[test] + fn scan_ranges_from_selectors_matches_a_scan_of_all_pages() { + use rand::{RngExt, SeedableRng, rngs::StdRng}; + let mut rng = StdRng::seed_from_u64(7); + for _ in 0..5_000 { + let mut first_row = 0; + let pages: Vec = (0..rng.random_range(0..12)) + .map(|idx| { + let page = PageLocation { + offset: 100 * idx, + compressed_page_size: 100, + first_row_index: first_row, + }; + first_row += rng.random_range(1..8); + page + }) + .collect(); + // Runs that are empty, end at a page boundary, cover many pages, + // and go past the last page. + let mut skip = rng.random_bool(0.5); + let selectors: Vec = (0..rng.random_range(0..10)) + .map(|_| { + skip = !skip || rng.random_bool(0.1); + let row_count = [0, 1, 2, 3, 7, 20, 60][rng.random_range(0..7)]; + match skip { + true => RowSelector::skip(row_count), + false => RowSelector::select(row_count), + } + }) + .collect(); + assert_eq!( + scan_ranges_from_selectors(selectors.iter().copied(), &pages), + scan_all_pages(&selectors, &pages), + "{selectors:?} {pages:?}" + ); + } + } + fn page_locations(starts: impl IntoIterator) -> Vec { starts .into_iter() diff --git a/parquet/src/arrow/in_memory_row_group.rs b/parquet/src/arrow/in_memory_row_group.rs index 79e0377f6143..2b19d95b6a49 100644 --- a/parquet/src/arrow/in_memory_row_group.rs +++ b/parquet/src/arrow/in_memory_row_group.rs @@ -11,6 +11,7 @@ use crate::file::metadata::page_index::RowGroupPageIndex; use crate::file::metadata::{ParquetMetaData, RowGroupMetaData}; use crate::file::page_index::offset_index::PageLocation; use crate::file::reader::{ChunkReader, Length, SerializedPageReader}; +use crate::util::push_buffers::SharedPushBuffers; use bytes::{Buf, Bytes}; use std::ops::Range; use std::sync::Arc; @@ -230,17 +231,18 @@ impl<'a> ColumnFetch<'a> { }; // `scan_ranges` returns the ranges of the selected pages in page // order. Map them back to page indexes. - let fetched = selection.scan_ranges(locations); - let mut fetched = fetched.iter().peekable(); - let pages = locations + // Page offsets increase, so a binary search from the previous page + // finds each page. A scan of all pages would cost `O(pages)` for a + // selection of a few rows. + let mut from = 0; + let pages = selection + .scan_ranges(locations) .iter() - .enumerate() - .filter(|(_, location)| { - fetched - .next_if(|range| range.start == location.offset as u64) - .is_some() + .map(|range| { + from += locations[from..] + .partition_point(|location| (location.offset as u64) < range.start); + from }) - .map(|(idx, _)| idx) .collect(); Self::Pages { dictionary: dictionary_range(chunk.start, locations), @@ -350,6 +352,17 @@ pub(crate) enum ColumnChunkData { }, /// Full column chunk and the offset within the original file Dense { offset: usize, data: Bytes }, + /// Bytes in the [`PushBuffers`] of the push decoder. The decoder pushes + /// more pages while the reader uses them, so the reader can continue + /// across [`DecodeResult::NeedsData`]. + /// + /// [`PushBuffers`]: crate::util::push_buffers::PushBuffers + /// [`DecodeResult::NeedsData`]: crate::DecodeResult::NeedsData + Shared { + /// Length of the full column chunk + length: usize, + buffers: SharedPushBuffers, + }, } impl ColumnChunkData { @@ -370,6 +383,14 @@ impl ColumnChunkData { let start = start as usize - *offset; Ok(data.slice(start..)) } + ColumnChunkData::Shared { buffers, .. } => { + buffers.lock().unwrap().get_from(start).ok_or_else(|| { + general_err!( + "Internal Error: no data at offset {start} in shared column chunk data. \ + The push decoder did not request the page before the reader needed it." + ) + }) + } } } } @@ -380,6 +401,7 @@ impl Length for ColumnChunkData { match &self { ColumnChunkData::Sparse { length, .. } => *length as u64, ColumnChunkData::Dense { data, .. } => data.len() as u64, + ColumnChunkData::Shared { length, .. } => *length as u64, } } } @@ -434,5 +456,24 @@ mod tests { ); let err = dense.get_bytes(105, 6).unwrap_err().to_string(); assert!(err.contains("has 5 bytes, expected 6"), "{err}"); + + let buffers = SharedPushBuffers::default(); + buffers + .lock() + .unwrap() + .push_range(200..204, Bytes::from_static(b"abcd")) + .unwrap(); + let shared = ColumnChunkData::Shared { + length: 10, + buffers, + }; + assert_eq!( + shared.get_bytes(200, 4).unwrap(), + Bytes::from_static(b"abcd") + ); + let err = shared.get_bytes(200, 5).unwrap_err().to_string(); + assert!(err.contains("has 4 bytes, expected 5"), "{err}"); + let err = shared.get_bytes(204, 1).unwrap_err().to_string(); + assert!(err.contains("no data at offset 204"), "{err}"); } } diff --git a/parquet/src/arrow/push_decoder/mod.rs b/parquet/src/arrow/push_decoder/mod.rs index 92169632da73..9192f6e07d4d 100644 --- a/parquet/src/arrow/push_decoder/mod.rs +++ b/parquet/src/arrow/push_decoder/mod.rs @@ -193,6 +193,55 @@ pub type ParquetPushDecoderBuilder = ArrowReaderBuilder; pub struct PushDecoderInput { /// Bytes pushed into the decoder, awaiting decode. buffers: PushBuffers, + /// How [`ParquetPushDecoder::try_decode`] fetches and decodes row groups. + request_granularity: RequestGranularity, +} + +/// How [`ParquetPushDecoder::try_decode`] requests data and decodes row +/// groups. +/// +/// Set with [`ParquetPushDecoderBuilder::with_request_granularity`]. Both +/// values give the same batches in the same order. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum RequestGranularity { + /// Request and decode a full row group at a time. This is the default. + /// + /// [`DecodeResult::NeedsData`] asks for all bytes that the row group + /// reads, and the first batch is ready after all of them are pushed. + /// This gives good decode speed, but the decoder buffers all pages of + /// the row group that the scan reads. For large row groups (for example + /// with many strings) this can require substantial memory. + #[default] + RowGroup, + /// Request and decode one batch at a time. + /// + /// [`DecodeResult::NeedsData`] asks only for the pages that the next + /// output batch reads. This gives the first batch sooner and needs no + /// more bytes than [`Self::RowGroup`]. See [`ParquetPushDecoder`] for + /// how this changes I/O and memory. + /// + /// * The [`ParquetMetaData`] must have an offset index for all requested + /// columns to find the pages of a batch (see + /// [`ArrowReaderOptions::with_page_index_policy`]). The decoder + /// requests the full column chunk for all columns without an offset + /// index. + /// * The decoder splits the selected rows of a row group into windows of + /// `batch_size` rows. For each window, it evaluates the [`RowFilter`] + /// predicates in order, then decodes the output. Each of these steps + /// requests only the pages that hold rows of the window. A predicate + /// can remove rows, so a batch can contain the rows of more than one + /// window. + /// * The decoder releases the pages that the decoded windows passed. See + /// [`ParquetPushDecoder::buffered_bytes`]. + /// * In one row group, use only the method that started the row group + /// ([`ParquetPushDecoder::try_decode`] or + /// [`ParquetPushDecoder::try_next_reader`]). The other method returns an + /// error. + /// + /// [`RowFilter`]: crate::arrow::arrow_reader::RowFilter + /// [`ArrowReaderOptions::with_page_index_policy`]: crate::arrow::arrow_reader::ArrowReaderOptions::with_page_index_policy + Batch, } /// Methods for building a ParquetDecoder. See the base [`ArrowReaderBuilder`] for @@ -239,7 +288,22 @@ impl ParquetPushDecoderBuilder { /// decoder reads. pub fn with_buffers(self, buffers: PushBuffers) -> Self { Self { - input: PushDecoderInput { buffers }, + input: PushDecoderInput { + buffers, + ..self.input + }, + ..self + } + } + + /// Set how [`ParquetPushDecoder::try_decode`] requests data and decodes + /// row groups. See [`RequestGranularity`]. + pub fn with_request_granularity(self, request_granularity: RequestGranularity) -> Self { + Self { + input: PushDecoderInput { + request_granularity, + ..self.input + }, ..self } } @@ -299,7 +363,11 @@ impl ParquetPushDecoderBuilder { /// Create a [`ParquetPushDecoder`] with the configured options pub fn build(self) -> Result { let Self { - input: PushDecoderInput { buffers }, + input: + PushDecoderInput { + buffers, + request_granularity, + }, metadata: parquet_metadata, schema, fields, @@ -318,6 +386,21 @@ impl ParquetPushDecoderBuilder { let filter = filter.map(|filter| { filter.fuse_same_projection(parquet_metadata.file_metadata().schema_descr()) }); + // `with_batch_size` clamps the batch size to the number of rows in + // the file. Thus, a file without rows has a batch size of 0, which is + // valid. Check the row groups, because the row count of the file can + // be wrong. + if request_granularity == RequestGranularity::Batch + && batch_size == 0 + && parquet_metadata + .row_groups() + .iter() + .any(|row_group| row_group.num_rows() > 0) + { + return Err(general_err!( + "batch_size must be greater than 0 with RequestGranularity::Batch" + )); + } let has_predicates = filter .as_ref() @@ -336,6 +419,7 @@ impl ParquetPushDecoderBuilder { max_predicate_cache_size, buffers, row_selection_policy, + request_granularity, ); // Initialize the decoder with the configured options @@ -382,6 +466,7 @@ fn builder_from_remaining(parts: RemainingRowGroupsParts) -> ParquetPushDecoderB metrics, row_selection_policy, buffers, + request_granularity, } = reader_builder; ArrowReaderBuilder { @@ -402,6 +487,7 @@ fn builder_from_remaining(parts: RemainingRowGroupsParts) -> ParquetPushDecoderB // Carry the decoder's already-fetched bytes across the rebuild so the new // decoder does not re-request them. .with_buffers(buffers) + .with_request_granularity(request_granularity) } /// A push based Parquet Decoder @@ -420,6 +506,22 @@ fn builder_from_remaining(parts: RemainingRowGroupsParts) -> ParquetPushDecoderB /// /// The decoder's internal state tracks what has been already decoded and what /// is needed next. +/// +/// # I/O and memory +/// +/// The decoder does no I/O. The caller decides how much to fetch: it can push +/// only the ranges of each [`DecodeResult::NeedsData`], or push more ranges +/// before the decoder asks for them to make fewer and larger requests. +/// +/// With [`RequestGranularity::RowGroup`] (the default), the decoder requests +/// all bytes that a row group reads before it returns the first batch of the +/// row group, and it holds these bytes until the row group ends. +/// +/// With [`RequestGranularity::Batch`], the decoder requests only the pages of +/// the next window of `batch_size` rows. If the caller pushes only the +/// requested ranges, a window needs up to one round trip for each predicate +/// and one for the output. The decoder releases the pages that the decoded +/// windows passed. See [`Self::buffered_bytes`]. #[derive(Debug)] pub struct ParquetPushDecoder { /// The inner state. @@ -462,6 +564,19 @@ impl ParquetPushDecoder { /// } ///``` pub fn try_decode(&mut self) -> Result, ParquetError> { + if let ParquetDecoderState::ReadingRowGroup { + remaining_row_groups, + } = &self.state + && remaining_row_groups.request_granularity() == RequestGranularity::Batch + && remaining_row_groups.is_building_reader() + { + // Do not consume the decoder. The caller can continue with + // `try_next_reader`. + return Err(general_err!( + "try_decode called while try_next_reader is reading a row group; \ + call try_next_reader until it returns the reader", + )); + } let current_state = std::mem::replace(&mut self.state, ParquetDecoderState::Finished); let (new_state, decode_result) = current_state.try_next_batch()?; self.state = new_state; @@ -509,6 +624,18 @@ impl ParquetPushDecoder { pub fn try_next_reader( &mut self, ) -> Result, ParquetError> { + if let ParquetDecoderState::ReadingRowGroup { + remaining_row_groups, + } = &self.state + && remaining_row_groups.is_incremental() + { + // Do not consume the decoder. The caller can continue with + // `try_decode`. + return Err(general_err!( + "try_next_reader called while try_decode is decoding a row group a batch \ + at a time; call try_decode until the row group is done", + )); + } let current_state = std::mem::replace(&mut self.state, ParquetDecoderState::Finished); let (new_state, decode_result) = current_state.try_next_reader()?; self.state = new_state; @@ -518,19 +645,8 @@ impl ParquetPushDecoder { /// Push data into the decoder for processing /// /// This is a convenience wrapper around [`Self::push_ranges`] for pushing a - /// single range of data. - /// - /// Note this can be the entire file or just a part of it. If it is part of the file, - /// the ranges should correspond to the data ranges requested by the decoder. - /// - /// # Memory Usage - /// - /// The decoder releases the pushed bytes that it will not read again (for - /// example, the bytes of a row group when it is done with that row group). - /// However, it does not release *all* pushed bytes: it keeps the bytes of - /// row groups that it does not read (for example, row groups without - /// selected rows, or after the limit). Call [`Self::clear_all_ranges`] to - /// release them. + /// single range of data. The range can be the entire file or a part of + /// it. See [`Self::push_ranges`] for the rules. /// /// See example in [`ParquetPushDecoderBuilder`] pub fn push_range(&mut self, range: Range, data: Bytes) -> Result<(), ParquetError> { @@ -539,16 +655,25 @@ impl ParquetPushDecoder { /// Push data into the decoder for processing /// - /// This should correspond to the data ranges requested by the decoder. + /// `data[i]` holds the bytes of `ranges[i]`. + /// + /// | Rule | Detail | + /// |---|---| + /// | Early pushes | You can push ranges before the decoder requests them, for example from [`Self::scan_plan`]. A pushed buffer can be larger than a request, for example a whole column chunk or the whole file. | + /// | One buffer per request | Each range of a [`DecodeResult::NeedsData`] must lie inside one pushed buffer. The decoder does not join adjacent buffers. If the bytes of a request are split over two buffers, the decoder requests the range again. | + /// | Release | The decoder releases bytes by range, not by buffer. It trims or splits a pushed buffer and keeps the parts that it can still read. See below. | /// - /// If you fetch data before the decoder requests it, for example with - /// [`Self::scan_plan`], keep it in your own cache and push exactly the - /// ranges in each [`DecodeResult::NeedsData`]: + /// The decoder releases these bytes: /// - /// * The decoder does not use a requested range that is split over two - /// pushed buffers. - /// * The decoder releases a pushed buffer only if its range is equal to a - /// requested range. Other pushed data stays buffered. + /// * The bytes of the column chunks of a row group when the row group is + /// done, also the bytes that the decoder did not request. A row group + /// that the queue reads again keeps its bytes. + /// * With [`RequestGranularity::Batch`], the pages that the decoded + /// windows of the active row group passed. See [`Self::buffered_bytes`]. + /// + /// Other bytes stay buffered, for example the bytes of row groups that + /// the decoder does not read (row groups without selected rows, or after + /// the limit). Call [`Self::clear_all_ranges`] to release them. pub fn push_ranges( &mut self, ranges: Vec>, @@ -559,16 +684,25 @@ impl ParquetPushDecoder { Ok(()) } - /// Returns the total number of buffered bytes in the decoder + /// Returns the number of pushed bytes that the decoder still holds. /// - /// This is the sum of the size of all [`Bytes`] that has been pushed to the - /// decoder but not yet consumed. + /// This counts logical bytes, not allocated memory. When the decoder + /// releases a part of a pushed [`Bytes`], it keeps the other parts as + /// slices of the same allocation. The allocation is freed only after + /// all of its parts are released. A caller that pushes large buffers can + /// thus keep more memory alive than this method reports. The count also + /// does not include the overhead of the internal data structures. /// - /// Note that this does not include any overhead of the internal data - /// structures and that since [`Bytes`] are ref counted memory, this may not - /// reflect additional memory usage. + /// With [`RequestGranularity::Batch`], the count includes the pages that + /// later windows of the active row group read. The decoder releases the + /// pages that the decoded windows passed, except: /// - /// This can be used to monitor memory usage of the decoder. + /// * the pages from the last multiple of `batch_size` rows before the + /// next window on. A later window or a predicate cache miss reads them, + /// * dictionary pages, + /// * column chunks without an offset index, which stay until the row + /// group is done, + /// * the pages of a row group that the queue reads again. pub fn buffered_bytes(&self) -> u64 { self.state.buffered_bytes() } @@ -591,7 +725,8 @@ impl ParquetPushDecoder { /// and the next row group has not yet been planned. While /// [`Self::try_decode`] is iterating an active row group's reader this /// returns `false`; with [`Self::try_next_reader`] there is a clean - /// window between two consecutive returns where this is `true`. + /// window between two consecutive returns where this is `true`. See also + /// [`RequestGranularity::Batch`]. pub fn is_at_row_group_boundary(&self) -> bool { self.state.is_at_row_group_boundary() } @@ -756,6 +891,9 @@ impl ParquetDecoderState { /// This structure is used to reduce the indentation level of the main loop /// in try_build fn try_next_batch(self) -> Result<(Self, DecodeResult), ParquetError> { + if self.request_granularity() == RequestGranularity::Batch { + return self.try_next_batch_incremental(); + } let mut current_state = self; loop { let (new_state, decode_result) = current_state.transition()?; @@ -805,6 +943,43 @@ impl ParquetDecoderState { } } + /// How this decoder fetches and decodes row groups. + fn request_granularity(&self) -> RequestGranularity { + match self { + Self::ReadingRowGroup { + remaining_row_groups, + } + | Self::DecodingRowGroup { + remaining_row_groups, + .. + } => remaining_row_groups.request_granularity(), + Self::Finished => RequestGranularity::default(), + } + } + + /// [`Self::try_next_batch`] for [`RequestGranularity::Batch`]. + fn try_next_batch_incremental(self) -> Result<(Self, DecodeResult), ParquetError> { + match self { + Self::ReadingRowGroup { + mut remaining_row_groups, + } => { + let result = remaining_row_groups.try_next_batch_incremental()?; + let state = match result { + DecodeResult::Finished => Self::Finished, + _ => Self::ReadingRowGroup { + remaining_row_groups, + }, + }; + Ok((state, result)) + } + // `try_decode` does not create this state with `RequestGranularity::Batch`. + Self::DecodingRowGroup { .. } => Err(general_err!( + "Internal Error: row group reader with RequestGranularity::Batch", + )), + Self::Finished => Ok((Self::Finished, DecodeResult::Finished)), + } + } + /// Transition to the next state with a reader (data can be produced), if not end of stream /// /// This function is called in a loop until the decoder is ready to return @@ -1368,6 +1543,107 @@ mod test { assert_eq!(all_output, TEST_BATCH.slice(251, 149)); } + /// The same scenario as [`test_decoder_first_pages_only`] + /// with [`RequestGranularity::Batch`]: the decoder asks only for the pages + /// of the first batch, and returns the batch as soon as they are pushed. + #[test] + fn test_decoder_first_pages_only_batch_granularity() { + let metadata = test_file_parquet_metadata_with_offset_index(); + let mut decoder = ParquetPushDecoderBuilder::try_new_decoder(Arc::clone(&metadata)) + .unwrap() + .with_batch_size(100) + .with_request_granularity(RequestGranularity::Batch) + .build() + .unwrap(); + + let (first_page_ranges, second_page_ranges) = first_and_second_page_ranges(&metadata); + + // Row group 0: the decoder asks for the dictionary page and the first + // data page of each column: the bytes of the first batch. + let ranges = expect_needs_data(decoder.try_decode()); + let dictionary_and_first_pages: Vec<_> = first_page_ranges + .iter() + .zip(metadata.row_group(0).columns()) + .enumerate() + .flat_map(|(idx, (range, column))| { + let first_page = metadata + .page_index_for_row_group(0) + .page_locations(idx) + .unwrap()[0] + .offset as u64; + let (start, _) = column.byte_range(); + [start..first_page, first_page..range.end] + }) + .filter(|range| !range.is_empty()) + .collect(); + assert_eq!(ranges, dictionary_and_first_pages); + + // Push only the first page of each column (with the dictionary page, + // as one range). This is all the data needed for the first batch, and + // the decoder returns it. + push_ranges_to_decoder(&mut decoder, first_page_ranges); + let batch = expect_data(decoder.try_decode()); + assert_eq!(batch, TEST_BATCH.slice(0, 100)); + + // The decoder releases each first data page that ends at or before + // row 100. It holds the dictionary pages, and each first data page + // that also has rows of the second batch. + let page_index = metadata.page_index_for_row_group(0); + let held_bytes: u64 = metadata + .row_group(0) + .columns() + .iter() + .enumerate() + .map(|(idx, column)| { + let pages = page_index.page_locations(idx).unwrap(); + let dictionary = pages[0].offset as u64 - column.byte_range().0; + match pages[1].first_row_index <= 100 { + true => dictionary, + false => dictionary + pages[0].compressed_page_size as u64, + } + }) + .sum(); + assert_eq!(decoder.buffered_bytes(), held_bytes); + + // The second batch needs the second page of each column. + let ranges = expect_needs_data(decoder.try_decode()); + assert_eq!(ranges, second_page_ranges); + push_ranges_to_decoder(&mut decoder, ranges); + let batch = expect_data(decoder.try_decode()); + assert_eq!(batch, TEST_BATCH.slice(100, 100)); + + // The row group is done, and its bytes are released. + assert!(decoder.is_at_row_group_boundary()); + assert_eq!(decoder.buffered_bytes(), 0); + } + + /// For each column of row group 0 of the test file: the range from the + /// column chunk start to the second data page (the dictionary page and + /// the first data page), and the range of the second data page. + fn first_and_second_page_ranges( + metadata: &ParquetMetaData, + ) -> (Vec>, Vec>) { + let page_index = metadata.page_index_for_row_group(0); + let row_group = metadata.row_group(0); + let mut first_page_ranges = vec![]; + let mut second_page_ranges = vec![]; + for (idx, column) in row_group.columns().iter().enumerate() { + let (start, len) = column.byte_range(); + let locations = page_index.page_locations(idx).unwrap(); + assert_eq!(locations.len(), 2, "expected 2 data pages per column chunk"); + let second_page_start = locations[1].offset as u64; + first_page_ranges.push(start..second_page_start); + second_page_ranges.push(second_page_start..start + len); + } + // Note the first range for each column includes the dictionary page + assert_eq!(first_page_ranges, vec![4..1734, 1860..3590, 3716..10936]); + assert_eq!( + second_page_ranges, + vec![1734..1860, 3590..3716, 10936..11062] + ); + (first_page_ranges, second_page_ranges) + } + /// Decode multiple columns "a" and "b", expect that the decoder requests /// only a single request per row group #[test] @@ -3156,7 +3432,7 @@ mod test { } /// return the metadata for the test file, including the offset index - fn test_file_parquet_metadata_with_offset_index() -> Arc { + pub fn test_file_parquet_metadata_with_offset_index() -> Arc { let mut metadata_decoder = ParquetMetaDataPushDecoder::try_new(test_file_len()) .unwrap() .with_offset_index_policy(PageIndexPolicy::Required); diff --git a/parquet/src/arrow/push_decoder/reader_builder/filter.rs b/parquet/src/arrow/push_decoder/reader_builder/filter.rs index d3d50c9d3f20..6e7420a3f38d 100644 --- a/parquet/src/arrow/push_decoder/reader_builder/filter.rs +++ b/parquet/src/arrow/push_decoder/reader_builder/filter.rs @@ -32,7 +32,7 @@ pub(super) struct FilterInfo { /// /// Note this is basically the same as CacheOptionsBuilder /// but it owns the ProjectionMask and RowGroupCache -#[derive(Debug)] +#[derive(Debug, Clone)] pub(super) struct CacheInfo { /// The columns to cache in the predicate cache. /// Normally these are the columns that filters may look at such that diff --git a/parquet/src/arrow/push_decoder/reader_builder/mod.rs b/parquet/src/arrow/push_decoder/reader_builder/mod.rs index 24036b7c6d87..918f6de0aa55 100644 --- a/parquet/src/arrow/push_decoder/reader_builder/mod.rs +++ b/parquet/src/arrow/push_decoder/reader_builder/mod.rs @@ -7,14 +7,15 @@ mod filter; mod stages; use crate::arrow::ProjectionMask; -use crate::arrow::array_reader::{ArrayReaderBuilder, CacheOptions, RowGroupCache}; +use crate::arrow::array_reader::{ArrayReader, ArrayReaderBuilder, CacheOptions, RowGroupCache}; use crate::arrow::arrow_reader::metrics::ArrowReaderMetrics; use crate::arrow::arrow_reader::selection::{LoadedRowRanges, RowSelectionStrategy}; use crate::arrow::arrow_reader::{ ParquetRecordBatchReader, PredicateOptions, ReadPlanBuilder, RowFilter, RowSelection, - RowSelectionPolicy, + RowSelectionPolicy, consume_record_batch, }; -use crate::arrow::in_memory_row_group::ColumnChunkData; +use crate::arrow::in_memory_row_group::{ColumnChunkData, InMemoryRowGroup}; +use crate::arrow::push_decoder::RequestGranularity; use crate::arrow::push_decoder::reader_builder::data::DataRequestBuilder; use crate::arrow::push_decoder::reader_builder::filter::CacheInfo; use crate::arrow::push_decoder::scan_plan::{ @@ -24,12 +25,16 @@ use crate::arrow::schema::ParquetField; use crate::errors::ParquetError; use crate::file::metadata::page_index::RowGroupPageIndex; use crate::file::metadata::{ColumnChunkMetaData, ParquetMetaData}; -use crate::util::push_buffers::PushBuffers; +use crate::util::push_buffers::{PushBuffers, SharedPushBuffers}; +use arrow_array::{Array, BooleanArray, RecordBatch}; +use arrow_buffer::BooleanBufferBuilder; +use arrow_select::filter::{filter_record_batch, prep_null_mask_filter}; use bytes::Bytes; use data::DataRequest; use filter::AdvanceResult; use filter::FilterInfo; pub(crate) use stages::{Stage, StageSchedule}; +use std::collections::VecDeque; use std::ops::Range; use std::sync::{Arc, RwLock}; @@ -40,6 +45,9 @@ struct RowGroupInfo { row_count: usize, plan_builder: ReadPlanBuilder, budget: RowBudget, + /// `Some` with [`RequestGranularity::Batch`], from the first window on. + /// Then `plan_builder` holds the selection of the current window only. + windows: Option>, } /// This is the inner state machine for reading a single row group. @@ -70,6 +78,9 @@ enum RowGroupDecoderState { cache_info: Option, }, /// Needs data to proceed with reading the output + /// + /// With [`RequestGranularity::Batch`], `data_request` holds only the + /// output pages of the current window. See [`Windows`]. WaitingOnData { row_group_info: RowGroupInfo, data_request: DataRequest, @@ -94,6 +105,183 @@ impl RowGroupDecoderState { } } +/// The state of a row group that is decoded with [`RequestGranularity::Batch`]. +/// +/// The decoder splits the selected rows of the row group into windows of +/// `batch_size` rows. Each window runs the same states as a full row group, +/// and requests only its own pages: +/// +/// ```text +/// Start ──► Filters ──► WaitingOnFilterData ──► StartData ──► WaitingOnData +/// ▲ ▲ │ (one loop per predicate) │ +/// │ └────────────────┘ │ +/// └──────────────────────── next window ─────────────────────────┘ +/// ``` +/// +/// The array readers live for the full row group. They read +/// [`ColumnChunkData::Shared`], so they see the pages that the caller pushes +/// for later windows. A predicate can leave fewer than `batch_size` rows in a +/// window. The output reader keeps those rows until `batch_size` rows are +/// ready, so the batches are the same as with +/// [`RequestGranularity::RowGroup`]. +struct Windows { + /// The selected rows that are not in a window yet, sorted. + remaining: VecDeque>, + /// The predicate cache of the row group, if there are predicates. + cache_info: Option, + /// One reader for each predicate, built when its first pages are pushed. + predicate_readers: Vec>, + /// The output reader, built when its first pages are pushed. + output_reader: Option, + /// The rows of the current window that the output reader must still read. + output_rows: VecDeque>, + /// How the output reader passes the rows between `output_rows`. + output_gaps: Gaps, + /// The rows that the output reader read and did not return yet. + pending_rows: usize, + /// The pages that end at or before this row are released. See + /// [`RowGroupReaderBuilder::release_passed_pages`]. + released_before: usize, +} + +impl Windows { + fn new(selection: Option<&RowSelection>, row_count: usize, num_predicates: usize) -> Self { + let remaining = match selection { + Some(selection) => selection_to_ranges(selection).into(), + None if row_count == 0 => VecDeque::new(), + None => std::iter::once(0..row_count).collect(), + }; + Self { + remaining, + cache_info: None, + predicate_readers: (0..num_predicates).map(|_| None).collect(), + output_reader: None, + output_rows: VecDeque::new(), + output_gaps: Gaps::Skip, + pending_rows: 0, + released_before: 0, + } + } +} + +impl std::fmt::Debug for Windows { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Windows") + .field("remaining", &self.remaining) + .field("output_rows", &self.output_rows) + .field("pending_rows", &self.pending_rows) + .finish_non_exhaustive() + } +} + +/// How a [`StepReader`] passes the unselected rows between two selected +/// ranges of a window. This is the [`RowSelectionPolicy`] of the scan, +/// resolved for one window. +enum Gaps { + /// Skip the rows. The reader does not need their pages. + Skip, + /// Decode the rows, and remove them from the batch with a mask. This is + /// faster than many short skips. It needs the pages of the rows, so it + /// applies only inside the loaded row ranges. `None`: all rows of the + /// window are loaded. + Decode(Option), +} + +impl Gaps { + /// Returns true if the reader decodes the rows of `gap`. The row before + /// `gap` is a selected row. + fn decodes(&self, gap: &Range) -> bool { + match self { + Self::Skip => false, + Self::Decode(None) => true, + Self::Decode(Some(loaded)) => loaded + .end_containing(gap.start - 1) + .is_some_and(|end| end >= gap.end), + } + } +} + +/// An array reader that reads a row group in steps, and its position. +struct StepReader { + reader: Box, + /// The first row of the row group that the reader did not pass yet. + position: usize, + /// One bit for each row that the reader decoded since the last batch: + /// true for a selected row. + mask: BooleanBufferBuilder, + /// `mask` has a false bit. + decoded_gap: bool, +} + +impl StepReader { + /// Read the rows of `ranges`, which are sorted. [`Self::take_batch`] + /// returns the rows. + fn read_rows(&mut self, ranges: &[Range], gaps: &Gaps) -> Result<(), ParquetError> { + let mut previous_end = None; + for range in ranges { + if let Some(end) = previous_end + && end < range.start + && gaps.decodes(&(end..range.start)) + { + self.decode(end..range.start)?; + self.mask.append_n(range.start - end, false); + self.decoded_gap = true; + } + self.decode(range.clone())?; + self.mask.append_n(range.end - range.start, true); + previous_end = Some(range.end); + } + Ok(()) + } + + /// Decode the rows of `range`, and skip the rows before it. + fn decode(&mut self, range: Range) -> Result<(), ParquetError> { + let to_skip = range.start - self.position; + if to_skip > 0 { + let skipped = self.reader.skip_records(to_skip)?; + if skipped != to_skip { + return Err(general_err!( + "failed to skip rows, expected {to_skip}, got {skipped}" + )); + } + } + let to_read = range.end - range.start; + let read = self.reader.read_records(to_read)?; + if read != to_read { + return Err(general_err!( + "failed to read rows, expected {to_read}, got {read}" + )); + } + self.position = range.end; + Ok(()) + } + + /// The selected rows that the reader read since the last batch. + fn take_batch(&mut self) -> Result { + let batch = consume_record_batch(self.reader.as_mut())?; + let mask = self.mask.finish(); + if !std::mem::take(&mut self.decoded_gap) { + return Ok(batch); + } + Ok(filter_record_batch(&batch, &BooleanArray::new(mask, None))?) + } +} + +/// The result of [`RowGroupReaderBuilder::try_build_incremental`]. +#[derive(Debug)] +pub(crate) enum IncrementalResult { + /// The bytes that the next batch needs. + NeedsData(Vec>), + /// The next output batch. `remaining_budget` is `Some` if this batch + /// finishes the row group. + Batch { + batch: RecordBatch, + remaining_budget: Option, + }, + /// The row group is finished, without more batches. + Finished { remaining_budget: RowBudget }, +} + /// The byte range of a column chunk in the file. pub(crate) fn column_chunk_range(column: &ColumnChunkMetaData) -> Range { let (start, length) = column.byte_range(); @@ -109,6 +297,12 @@ pub(crate) enum RowGroupBuildResult { }, /// More bytes are needed before the active row group can make progress. NeedsData(Vec>), + /// The next batch of a row group decoded with [`RequestGranularity::Batch`]. + /// `remaining_budget` is `Some` if this batch finishes the row group. + Batch { + batch: RecordBatch, + remaining_budget: Option, + }, /// The active row group produced a reader. Data { batch_reader: ParquetRecordBatchReader, @@ -187,12 +381,20 @@ pub(crate) struct RowGroupReaderBuilder { /// it is a bug error if it is not put back after transitioning states. state: Option, - /// The underlying data store - buffers: PushBuffers, + /// The underlying data store. Shared with the output reader of a row + /// group that is decoded with [`RequestGranularity::Batch`]. + buffers: SharedPushBuffers, /// What each decoding stage fetches. Kept here because the filter is /// moved out of the builder while a row group is decoded. stages: Arc, + /// How [`Self::try_build_incremental`] fetches and decodes row groups. + request_granularity: RequestGranularity, + /// `try_build_incremental` started the active row group. + batch_mode_active: bool, + /// The queue reads the active row group again later, so the decoder keeps + /// its pages. See [`Self::release_passed_pages`]. + keep_passed_pages: bool, } /// The parts of a [`RowGroupReaderBuilder`] needed to rebuild it, recovered by @@ -212,6 +414,7 @@ pub(crate) struct RowGroupReaderBuilderParts { /// Bytes already pushed into the decoder, carried across a rebuild so they /// are not re-requested. pub buffers: PushBuffers, + pub request_granularity: RequestGranularity, } impl RowGroupReaderBuilder { @@ -227,6 +430,7 @@ impl RowGroupReaderBuilder { max_predicate_cache_size: usize, buffers: PushBuffers, row_selection_policy: RowSelectionPolicy, + request_granularity: RequestGranularity, ) -> Self { let (predicate_projections, cache_projection) = match &filter { Some(filter) => ( @@ -256,8 +460,11 @@ impl RowGroupReaderBuilder { max_predicate_cache_size, row_selection_policy, state: Some(RowGroupDecoderState::Finished), - buffers, + buffers: Arc::new(std::sync::Mutex::new(buffers)), stages: Arc::new(stages), + request_granularity, + batch_mode_active: false, + keep_passed_pages: false, } } @@ -280,7 +487,12 @@ impl RowGroupReaderBuilder { buffers, // Recomputed from `filter` when the builder is rebuilt. stages: _, + request_granularity, + batch_mode_active: _, + keep_passed_pages: _, } = self; + // A reader of the discarded state can hold a reference. + let buffers = std::mem::take(&mut *buffers.lock().unwrap()); RowGroupReaderBuilderParts { batch_size, projection, @@ -290,16 +502,19 @@ impl RowGroupReaderBuilder { metrics, row_selection_policy, buffers, + request_granularity, } } /// Push new data buffers that can be used to satisfy pending requests + // `&mut`: the method changes the shared buffers. + #[expect(clippy::needless_pass_by_ref_mut)] pub fn push_data( &mut self, ranges: Vec>, buffers: Vec, ) -> Result<(), ParquetError> { - self.buffers.push_ranges(ranges, buffers) + self.buffers.lock().unwrap().push_ranges(ranges, buffers) } /// True iff the inner state is `Finished`. This is the only state in @@ -312,12 +527,71 @@ impl RowGroupReaderBuilder { /// Returns the total number of buffered bytes available pub fn buffered_bytes(&self) -> u64 { - self.buffers.buffered_bytes() + self.buffers.lock().unwrap().buffered_bytes() + } + + /// How [`ParquetPushDecoder::try_decode`] fetches and decodes row groups. + /// + /// [`ParquetPushDecoder::try_decode`]: crate::arrow::push_decoder::ParquetPushDecoder::try_decode + pub(crate) fn request_granularity(&self) -> RequestGranularity { + self.request_granularity + } + + /// Returns true if `try_decode` decodes the active row group one batch at + /// a time. While this is true, `try_next_reader` returns an error. + pub(crate) fn is_incremental(&self) -> bool { + self.batch_mode_active && self.has_active_row_group() + } + + /// Decode the active row group one batch at a time. See + /// [`RequestGranularity::Batch`]. This runs the same state machine as + /// [`Self::try_build`]. + /// + /// `read_again`: the queue reads this row group again later. The decoder + /// then keeps the pages of the row group, so the later read does not + /// request them again. + pub(crate) fn try_build_incremental( + &mut self, + read_again: bool, + ) -> Result { + self.keep_passed_pages = read_again; + if !self.batch_mode_active { + if !matches!(self.state, Some(RowGroupDecoderState::Start { .. })) { + return Err(general_err!( + "Internal Error: try_build_incremental called for a row group of try_build" + )); + } + self.batch_mode_active = true; + } + let result = self.try_build(); + if !self.has_active_row_group() || result.is_err() { + self.batch_mode_active = false; + } + Ok(match result? { + RowGroupBuildResult::NeedsData(ranges) => IncrementalResult::NeedsData(ranges), + RowGroupBuildResult::Finished { remaining_budget } => { + IncrementalResult::Finished { remaining_budget } + } + RowGroupBuildResult::Batch { + batch, + remaining_budget, + } => IncrementalResult::Batch { + batch, + remaining_budget, + }, + RowGroupBuildResult::Data { .. } => { + return Err(general_err!( + "Internal Error: reader built with RequestGranularity::Batch" + )); + } + }) } /// Clear any staged ranges currently buffered for future decode work. + // `&mut`: the method changes the shared buffers. + #[expect(clippy::needless_pass_by_ref_mut)] pub fn clear_all_ranges(&mut self) { - self.buffers.clear_all_ranges(); + self.buffers.lock().unwrap().clear_all_ranges(); } /// take the current state, leaving None in its place. @@ -363,6 +637,7 @@ impl RowGroupReaderBuilder { row_count, plan_builder, budget, + windows: None, }; self.state = Some(RowGroupDecoderState::Start { row_group_info }); @@ -415,6 +690,9 @@ impl RowGroupReaderBuilder { current_state: RowGroupDecoderState, ) -> Result { let result = match current_state { + RowGroupDecoderState::Start { row_group_info } if self.batch_mode_active => { + self.start_window(row_group_info)? + } RowGroupDecoderState::Start { row_group_info } => { debug_assert!( !row_group_info.budget.is_exhausted(), @@ -470,10 +748,24 @@ impl RowGroupReaderBuilder { row_count, plan_builder, budget, + windows, } = row_group_info; // If nothing is selected, we are done with this row group if !plan_builder.selects_any() { + if windows.is_some() { + // The earlier predicates ruled out the window + self.filter = Some(filter_info.into_filter()); + return Ok(NextState::again(RowGroupDecoderState::Start { + row_group_info: RowGroupInfo { + row_group_idx, + row_count, + plan_builder, + budget, + windows, + }, + })); + } // ruled out entire row group self.filter = Some(filter_info.into_filter()); return Ok(NextState::result( @@ -509,6 +801,7 @@ impl RowGroupReaderBuilder { row_count, plan_builder, budget, + windows, }; NextState::again(RowGroupDecoderState::WaitingOnFilterData { @@ -523,7 +816,7 @@ impl RowGroupReaderBuilder { mut filter_info, } => { // figure out what ranges we still need - let needed_ranges = data_request.needed_ranges(&self.buffers); + let needed_ranges = data_request.needed_ranges(&self.buffers.lock().unwrap()); if !needed_ranges.is_empty() { // still need data return Ok(NextState::result( @@ -536,12 +829,17 @@ impl RowGroupReaderBuilder { )); } + if row_group_info.windows.is_some() { + return self.evaluate_window_predicate(row_group_info, filter_info); + } + // otherwise we have all the data we need to evaluate the predicate let RowGroupInfo { row_group_idx, row_count, mut plan_builder, budget, + windows, } = row_group_info; let predicate = filter_info.current(); @@ -551,7 +849,7 @@ impl RowGroupReaderBuilder { row_count, &self.metadata, predicate.projection(), - &mut self.buffers, + &mut self.buffers.lock().unwrap(), )?; let cache_options = filter_info.cache_builder().producer(); @@ -598,6 +896,7 @@ impl RowGroupReaderBuilder { row_count, plan_builder, budget, + windows, }; // Take back the column chunks that were read @@ -635,6 +934,7 @@ impl RowGroupReaderBuilder { row_count, plan_builder, budget, + windows, } = row_group_info; let BudgetedReadPlan { @@ -644,6 +944,19 @@ impl RowGroupReaderBuilder { remaining_budget, } = budget.apply_to_plan(plan_builder, row_count); + if rows_after_budget == 0 && windows.is_some() { + // The window has no output rows + return Ok(NextState::again(RowGroupDecoderState::Start { + row_group_info: RowGroupInfo { + row_group_idx, + row_count, + plan_builder, + budget: remaining_budget, + windows, + }, + })); + } + if rows_before_budget == 0 { // ruled out entire row group return Ok(NextState::result( @@ -661,6 +974,42 @@ impl RowGroupReaderBuilder { } let fetch = self.stages.fetch(Stage::Projection); + if let Some(mut windows) = windows { + // The rows of the window that pass the predicates, the + // offset and the limit + let rows = plan_builder + .selection() + .map(selection_to_ranges) + .unwrap_or_default(); + windows.output_gaps = match plan_builder.selection() { + Some(selection) => { + self.gaps(row_group_idx, row_count, &self.projection, selection, &rows) + } + None => Gaps::Skip, + }; + windows.output_rows = rows.into(); + let data_request = DataRequestBuilder::new( + row_group_idx, + row_count, + self.batch_size, + &self.metadata, + fetch.projection, + ) + .with_selection(plan_builder.selection()) + .with_cache_projection(fetch.cache_projection) + .build(); + return Ok(NextState::again(RowGroupDecoderState::WaitingOnData { + row_group_info: RowGroupInfo { + row_group_idx, + row_count, + plan_builder, + budget: remaining_budget, + windows: Some(windows), + }, + data_request, + cache_info, + })); + } let data_request = DataRequestBuilder::new( row_group_idx, row_count, @@ -688,6 +1037,7 @@ impl RowGroupReaderBuilder { row_count, plan_builder, budget: remaining_budget, + windows, }; NextState::again(RowGroupDecoderState::WaitingOnData { @@ -696,13 +1046,21 @@ impl RowGroupReaderBuilder { cache_info, }) } + // Waiting on the output pages of the current window + RowGroupDecoderState::WaitingOnData { + row_group_info, + data_request, + cache_info, + } if row_group_info.windows.is_some() => { + self.read_window_output(row_group_info, data_request, cache_info)? + } // Waiting on data to proceed with reading the output RowGroupDecoderState::WaitingOnData { row_group_info, data_request, cache_info, } => { - let needed_ranges = data_request.needed_ranges(&self.buffers); + let needed_ranges = data_request.needed_ranges(&self.buffers.lock().unwrap()); if !needed_ranges.is_empty() { // still need data return Ok(NextState::result( @@ -714,13 +1072,13 @@ impl RowGroupReaderBuilder { RowGroupBuildResult::NeedsData(needed_ranges), )); } - // otherwise we have all the data we need to proceed let RowGroupInfo { row_group_idx, row_count, plan_builder, budget, + windows: _, } = row_group_info; let row_group = data_request.try_into_in_memory_row_group( @@ -728,7 +1086,7 @@ impl RowGroupReaderBuilder { row_count, &self.metadata, &self.projection, - &mut self.buffers, + &mut self.buffers.lock().unwrap(), )?; let plan = plan_builder.build(); @@ -765,6 +1123,405 @@ impl RowGroupReaderBuilder { Ok(result) } + /// Start the next window of a row group decoded with + /// [`RequestGranularity::Batch`], or finish the row group. See + /// [`Windows`]. + fn start_window(&mut self, row_group_info: RowGroupInfo) -> Result { + let RowGroupInfo { + row_group_idx, + row_count, + plan_builder, + budget, + windows, + } = row_group_info; + let num_predicates = self.filter.as_ref().map_or(0, |f| f.predicates.len()); + let mut windows = windows.unwrap_or_else(|| { + Box::new(Windows::new( + plan_builder.selection(), + row_count, + num_predicates, + )) + }); + + if windows.remaining.is_empty() || budget.is_exhausted() { + // Return the rows that did not fill a batch + let result = match windows.output_reader.as_mut() { + Some(output) if windows.pending_rows > 0 => RowGroupBuildResult::Batch { + batch: output.take_batch()?, + remaining_budget: Some(budget), + }, + _ => RowGroupBuildResult::Finished { + remaining_budget: budget, + }, + }; + return Ok(NextState::result(RowGroupDecoderState::Finished, result)); + } + + if let Some(next) = windows.remaining.front() { + self.release_passed_pages(row_group_idx, next.start, &mut windows.released_before); + } + let rows = take_rows(&mut windows.remaining, self.batch_size); + let plan_builder = ReadPlanBuilder::new(self.batch_size) + .with_selection(Some(ranges_to_selection(&rows, row_count))); + + let filter = match self.filter.take() { + Some(filter) if !filter.predicates.is_empty() => filter, + filter => { + self.filter = filter; + return Ok(NextState::again(RowGroupDecoderState::StartData { + row_group_info: RowGroupInfo { + row_group_idx, + row_count, + plan_builder, + budget, + windows: Some(windows), + }, + column_chunks: None, + cache_info: None, + })); + } + }; + let cache_info = match &windows.cache_info { + Some(cache_info) => cache_info.clone(), + None => { + let cache_info = CacheInfo::new( + self.compute_cache_projection(row_group_idx, &filter), + Arc::new(RwLock::new(RowGroupCache::new( + self.batch_size, + self.max_predicate_cache_size, + ))), + ); + windows.cache_info = Some(cache_info.clone()); + cache_info + } + }; + Ok(NextState::again(RowGroupDecoderState::Filters { + row_group_info: RowGroupInfo { + row_group_idx, + row_count, + plan_builder, + budget, + windows: Some(windows), + }, + column_chunks: None, + filter_info: FilterInfo::new(filter, cache_info), + })) + } + + /// Release the pages of the active row group that no later window reads. + /// `first_row` is the first row of the next window. + /// + /// ```text + /// batch_size = 100, next window starts at row 250 + /// + /// rows: 0 100 200 250 300 + /// pages: ├── p0 ──┼── p1 ───┼──── p2 ────┼── p3 ── + /// released: ██████████████████ + /// ``` + /// + /// The readers have decoded the rows before `first_row`, so they do not + /// need those bytes again. Three things stay: + /// + /// | Bytes | Reason | + /// |---|---| + /// | The page that holds `first_row` | A later window reads it. | + /// | Pages from the last `batch_size` boundary on | On a predicate cache miss, the reader decodes the full cache batch again. | + /// | The dictionary page | Each request of the column chunk lists it. | + /// + /// Without an offset index, the column chunk is one buffer and stays + /// until the row group ends. + fn release_passed_pages( + &self, + row_group_idx: usize, + first_row: usize, + released_before: &mut usize, + ) { + if self.keep_passed_pages { + return; + } + let before = first_row - first_row % self.batch_size; + if before <= *released_before { + return; + } + *released_before = before; + let Some(page_index) = self.row_group_offset_index(row_group_idx) else { + return; + }; + let num_columns = self.metadata.row_group(row_group_idx).num_columns(); + let ranges: Vec> = (0..num_columns) + .filter_map(|column_idx| { + let pages = page_index.page_locations(column_idx)?; + // The pages before the page that holds row `before` + let passed = pages + .partition_point(|page| page.first_row_index as usize <= before) + .checked_sub(1)?; + Some(pages.first()?.offset as u64..pages[passed].offset as u64) + }) + .collect(); + self.buffers.lock().unwrap().release_ranges(&ranges); + } + + /// Evaluate the current predicate on the rows of the current window. + /// The pages of these rows are in the buffers. + fn evaluate_window_predicate( + &mut self, + row_group_info: RowGroupInfo, + mut filter_info: FilterInfo, + ) -> Result { + let RowGroupInfo { + row_group_idx, + row_count, + mut plan_builder, + budget, + windows, + } = row_group_info; + let Some(mut windows) = windows else { + return Err(general_err!("Internal Error: window state missing")); + }; + let Some(selection) = plan_builder.selection().cloned() else { + return Err(general_err!("Internal Error: window without a selection")); + }; + + let predicate_idx = filter_info.index(); + let reader = match &mut windows.predicate_readers[predicate_idx] { + Some(reader) => reader, + slot => { + let cache_options = filter_info.cache_builder().producer(); + slot.insert(self.build_step_reader( + row_group_idx, + row_count, + filter_info.current().projection(), + Some(&cache_options), + )?) + } + }; + let rows = selection_to_ranges(&selection); + let gaps = self.gaps( + row_group_idx, + row_count, + filter_info.current().projection(), + &selection, + &rows, + ); + reader.read_rows(&rows, &gaps)?; + let batch = reader.take_batch()?; + let input_rows = batch.num_rows(); + let filter = filter_info.current_mut().evaluate(batch)?; + if filter.len() != input_rows { + return Err(arrow_err!( + "ArrowPredicate predicate returned {} rows, expected {input_rows}", + filter.len() + )); + } + let filter = match filter.null_count() { + 0 => filter, + _ => prep_null_mask_filter(&filter), + }; + if filter.true_count() != filter.len() { + let passed = RowSelection::from_filters(&[filter]); + plan_builder = plan_builder.with_selection(Some(selection.and_then(&passed))); + } + + let row_group_info = RowGroupInfo { + row_group_idx, + row_count, + plan_builder, + budget, + windows: Some(windows), + }; + Ok(match filter_info.advance() { + AdvanceResult::Continue(filter_info) => { + NextState::again(RowGroupDecoderState::Filters { + row_group_info, + column_chunks: None, + filter_info, + }) + } + AdvanceResult::Done(filter, _) => { + self.filter = Some(filter); + NextState::again(RowGroupDecoderState::StartData { + row_group_info, + column_chunks: None, + cache_info: None, + }) + } + }) + } + + /// Read the output rows of the current window, or return the pages that + /// they need. Returns a batch when `batch_size` rows are ready. + // `&mut`: the method changes the shared buffers. + #[expect(clippy::needless_pass_by_ref_mut)] + fn read_window_output( + &mut self, + mut row_group_info: RowGroupInfo, + data_request: DataRequest, + cache_info: Option, + ) -> Result { + let needed_ranges = data_request.needed_ranges(&self.buffers.lock().unwrap()); + if !needed_ranges.is_empty() { + return Ok(NextState::result( + RowGroupDecoderState::WaitingOnData { + row_group_info, + data_request, + cache_info, + }, + RowGroupBuildResult::NeedsData(needed_ranges), + )); + } + let (row_group_idx, row_count) = (row_group_info.row_group_idx, row_group_info.row_count); + let Some(windows) = row_group_info.windows.as_mut() else { + return Err(general_err!("Internal Error: window state missing")); + }; + + let output = match &mut windows.output_reader { + Some(output) => output, + slot => { + let cache_options = windows + .cache_info + .as_ref() + .map(|cache_info| cache_info.builder().consumer()); + slot.insert(self.build_step_reader( + row_group_idx, + row_count, + &self.projection, + cache_options.as_ref(), + )?) + } + }; + + if windows.pending_rows < self.batch_size { + let rows = take_rows( + &mut windows.output_rows, + self.batch_size - windows.pending_rows, + ); + output.read_rows(&rows, &windows.output_gaps)?; + windows.pending_rows += rows.iter().map(|r| r.end - r.start).sum::(); + } + if windows.output_rows.is_empty() + && let Some(next) = windows.remaining.front() + { + // The readers decoded all rows of the window + self.release_passed_pages(row_group_idx, next.start, &mut windows.released_before); + } + if windows.pending_rows < self.batch_size { + // The window did not fill a batch + return Ok(NextState::again(RowGroupDecoderState::Start { + row_group_info, + })); + } + + let batch = output.take_batch()?; + windows.pending_rows = 0; + if !windows.output_rows.is_empty() { + return Ok(NextState::result( + RowGroupDecoderState::WaitingOnData { + row_group_info, + data_request, + cache_info, + }, + RowGroupBuildResult::Batch { + batch, + remaining_budget: None, + }, + )); + } + if windows.remaining.is_empty() || row_group_info.budget.is_exhausted() { + return Ok(NextState::result( + RowGroupDecoderState::Finished, + RowGroupBuildResult::Batch { + batch, + remaining_budget: Some(row_group_info.budget), + }, + )); + } + Ok(NextState::result( + RowGroupDecoderState::Start { row_group_info }, + RowGroupBuildResult::Batch { + batch, + remaining_budget: None, + }, + )) + } + + /// Build a reader of the columns in `projection` that lives for the full + /// row group. Its column chunks are [`ColumnChunkData::Shared`] views of + /// the shared [`PushBuffers`]. + fn build_step_reader( + &self, + row_group_idx: usize, + row_count: usize, + projection: &ProjectionMask, + cache_options: Option<&CacheOptions>, + ) -> Result { + let metadata = self.metadata.row_group(row_group_idx); + let column_chunks = metadata + .columns() + .iter() + .enumerate() + .map(|(idx, column)| { + projection.leaf_included(idx).then(|| { + Arc::new(ColumnChunkData::Shared { + length: column.byte_range().1 as usize, + buffers: Arc::clone(&self.buffers), + }) + }) + }) + .collect(); + let row_group = InMemoryRowGroup { + page_index: self.row_group_offset_index(row_group_idx), + column_chunks, + row_count, + row_group_idx, + metadata: &self.metadata, + }; + let reader = ArrayReaderBuilder::new(&row_group, &self.metrics) + .with_batch_size(self.batch_size) + .with_parquet_metadata(&self.metadata) + .with_cache_options(cache_options) + .build_array_reader(self.fields.as_deref(), projection)?; + Ok(StepReader { + reader, + position: 0, + mask: BooleanBufferBuilder::new(0), + decoded_gap: false, + }) + } + + /// Resolve the [`RowSelectionPolicy`] of the scan for one window. + /// `rows` are the selected rows of `selection`, which is the selection of + /// the window for the columns of `projection`. + fn gaps( + &self, + row_group_idx: usize, + row_count: usize, + projection: &ProjectionMask, + selection: &RowSelection, + rows: &[Range], + ) -> Gaps { + let [first, .., last] = rows else { + // No gaps + return Gaps::Skip; + }; + // `Auto` uses the mean length of the runs. Remove the rows before + // and after the window, which are one long skip each. + let start = first.start; + let window = RowSelection::from_consecutive_ranges( + rows.iter().map(|r| r.start - start..r.end - start), + last.end - start, + ); + match self.row_selection_policy.resolve(Some(&window)) { + RowSelectionStrategy::Selectors => Gaps::Skip, + RowSelectionStrategy::Mask => Gaps::Decode(loaded_row_ranges_for_projection( + Some(selection), + projection, + self.row_group_offset_index(row_group_idx), + self.metadata.file_metadata().schema_descr().num_columns(), + row_count, + )), + } + } + /// The index of the active row group, if any. pub(crate) fn active_row_group_idx(&self) -> Option { self.state @@ -776,6 +1533,8 @@ impl RowGroupReaderBuilder { /// includes bytes that the caller pushed but the decoder did not request, /// for example the bytes between the requested ranges of a larger pushed /// buffer. + // `&mut`: the method changes the shared buffers. + #[expect(clippy::needless_pass_by_ref_mut)] pub(crate) fn release_row_group(&mut self, row_group_idx: usize) { let ranges: Vec> = self .metadata @@ -784,14 +1543,16 @@ impl RowGroupReaderBuilder { .iter() .map(column_chunk_range) .collect(); - self.buffers.release_ranges(&ranges); + self.buffers.lock().unwrap().release_ranges(&ranges); } /// Remove the buffered bytes outside the read column chunks of /// `row_groups`. A column chunk is read if the output or a predicate /// reads its column. Indexes that are not in the file are ignored. + // `&mut`: the method changes the shared buffers. + #[expect(clippy::needless_pass_by_ref_mut)] pub(crate) fn release_unread_bytes(&mut self, row_groups: impl IntoIterator) { - if self.buffers.buffered_bytes() == 0 { + if self.buffers.lock().unwrap().buffered_bytes() == 0 { return; } let mut read_columns = self.projection.clone(); @@ -814,13 +1575,19 @@ impl RowGroupReaderBuilder { .map(|(_, column)| column_chunk_range(column)), ); } - self.buffers.retain_ranges(&keep); + self.buffers.lock().unwrap().retain_ranges(&keep); } /// A [`ScanPlanBuilder`] that plans the same ranges as this builder, for - /// the row groups in `frontier`. + /// the row groups in `frontier`. It plans the row groups that the + /// decoder has not started in the order of `try_decode`. pub(crate) fn scan_plan_builder(&self, frontier: RowGroupFrontier) -> ScanPlanBuilder { - ScanPlanBuilder::new(frontier, self.batch_size, Arc::clone(&self.stages)) + ScanPlanBuilder::new( + frontier, + self.batch_size, + Arc::clone(&self.stages), + self.request_granularity == RequestGranularity::Batch, + ) } /// Which columns should be cached? @@ -959,6 +1726,49 @@ fn loaded_row_ranges_for_projection( .map(LoadedRowRanges::from_selection) } +/// Row ranges to a [`RowSelection`] of `row_count` rows. +fn ranges_to_selection(ranges: &[Range], row_count: usize) -> RowSelection { + RowSelection::from_consecutive_ranges(ranges.iter().cloned(), row_count) +} + +/// The selected rows of `selection`, as sorted row ranges. +fn selection_to_ranges(selection: &RowSelection) -> Vec> { + let mut out: Vec> = vec![]; + let mut pos = 0; + for selector in selection.iter() { + if !selector.skip && selector.row_count > 0 { + match out.last_mut() { + Some(last) if last.end == pos => last.end = pos + selector.row_count, + _ => out.push(pos..pos + selector.row_count), + } + } + pos += selector.row_count; + } + out +} + +/// Remove and return the first `n` rows of `ranges`. +fn take_rows(ranges: &mut VecDeque>, n: usize) -> Vec> { + let mut taken = vec![]; + let mut remaining = n; + while remaining > 0 { + let Some(range) = ranges.front_mut() else { + break; + }; + let len = range.end - range.start; + if len <= remaining { + taken.push(range.clone()); + remaining -= len; + ranges.pop_front(); + } else { + taken.push(range.start..range.start + remaining); + range.start += remaining; + remaining = 0; + } + } + taken +} + #[cfg(test)] mod tests { use super::*; @@ -974,7 +1784,7 @@ mod tests { #[test] // Verify that the size of RowGroupDecoderState does not grow too large fn test_structure_size() { - assert_eq!(std::mem::size_of::(), 240); + assert_eq!(std::mem::size_of::(), 248); } #[test] diff --git a/parquet/src/arrow/push_decoder/remaining.rs b/parquet/src/arrow/push_decoder/remaining.rs index 9921ec6c3d93..5cd9454d30f3 100644 --- a/parquet/src/arrow/push_decoder/remaining.rs +++ b/parquet/src/arrow/push_decoder/remaining.rs @@ -4,12 +4,14 @@ use crate::DecodeResult; use crate::arrow::arrow_reader::{ParquetRecordBatchReader, RowGroupPlan}; +use crate::arrow::push_decoder::RequestGranularity; use crate::arrow::push_decoder::reader_builder::{ - RowGroupBuildResult, RowGroupReaderBuilder, RowGroupReaderBuilderParts, + IncrementalResult, RowGroupBuildResult, RowGroupReaderBuilder, RowGroupReaderBuilderParts, }; use crate::arrow::push_decoder::scan_plan::{NextRowGroup, RowBudget, RowGroupFrontier, ScanPlan}; use crate::errors::ParquetError; use crate::file::metadata::ParquetMetaData; +use arrow_array::RecordBatch; use arrow_schema::SchemaRef; use bytes::Bytes; use std::ops::Range; @@ -108,7 +110,10 @@ impl RemainingRowGroups { pub(super) fn scan_plan(&self) -> ScanPlan { self.row_group_reader_builder .scan_plan_builder(self.frontier.clone()) - .with_active_row_group(self.active_row_group.clone()) + .with_active_row_group( + self.active_row_group.clone(), + self.row_group_reader_builder.is_incremental(), + ) .build() } @@ -171,6 +176,78 @@ impl RemainingRowGroups { .release_unread_bytes(self.frontier.queued_row_groups()); } + /// How [`Self::try_next_batch_incremental`] fetches and decodes. + pub(crate) fn request_granularity(&self) -> RequestGranularity { + self.row_group_reader_builder.request_granularity() + } + + /// See [`RowGroupReaderBuilder::is_incremental`]. + pub(crate) fn is_incremental(&self) -> bool { + self.row_group_reader_builder.is_incremental() + } + + /// Returns true if `try_next_reader` started the active row group and + /// did not return its reader yet. + pub(crate) fn is_building_reader(&self) -> bool { + self.row_group_reader_builder.has_active_row_group() + && !self.row_group_reader_builder.is_incremental() + } + + /// Returns the next batch. Decodes the row groups one batch at a time. + /// See [`RequestGranularity::Batch`]. + pub(crate) fn try_next_batch_incremental( + &mut self, + ) -> Result, ParquetError> { + loop { + if !self.row_group_reader_builder.has_active_row_group() { + match self.frontier.next_readable_row_group()? { + Some(next_row_group) => { + self.active_row_group = Some(next_row_group.clone()); + let NextRowGroup { + row_group_idx, + row_count, + selection, + budget, + } = next_row_group; + self.row_group_reader_builder.next_row_group( + row_group_idx, + row_count, + selection, + budget, + )?; + } + None => return Ok(DecodeResult::Finished), + } + } + + let row_group_idx = self.row_group_reader_builder.active_row_group_idx(); + let read_again = row_group_idx.is_some_and(|idx| self.frontier.is_queued(idx)); + // `remaining_budget` is `Some` if the row group is finished. + let (batch, remaining_budget) = match self + .row_group_reader_builder + .try_build_incremental(read_again)? + { + IncrementalResult::NeedsData(ranges) => { + return Ok(DecodeResult::NeedsData(ranges)); + } + IncrementalResult::Finished { remaining_budget } => (None, Some(remaining_budget)), + IncrementalResult::Batch { + batch, + remaining_budget, + } => (Some(batch), remaining_budget), + }; + if let Some(remaining_budget) = remaining_budget { + self.active_row_group = None; + self.frontier + .update_budget_after_row_group(remaining_budget); + self.release_row_group(row_group_idx); + } + if let Some(batch) = batch { + return Ok(DecodeResult::Data(batch)); + } + } + } + /// Release the buffered bytes of a row group that is done, unless the /// queue reads it again. The reader of the row group holds its own /// copies of the bytes that it reads. @@ -227,6 +304,11 @@ impl RemainingRowGroups { // need more data to proceed return Ok(DecodeResult::NeedsData(ranges)); } + RowGroupBuildResult::Batch { .. } => { + return Err(general_err!( + "Internal Error: batch output with RequestGranularity::RowGroup" + )); + } RowGroupBuildResult::Data { batch_reader, remaining_budget, diff --git a/parquet/src/arrow/push_decoder/scan_plan/mod.rs b/parquet/src/arrow/push_decoder/scan_plan/mod.rs index b32f5bd430ec..e03f638be381 100644 --- a/parquet/src/arrow/push_decoder/scan_plan/mod.rs +++ b/parquet/src/arrow/push_decoder/scan_plan/mod.rs @@ -47,10 +47,14 @@ pub struct PlannedRange { /// One past the last planned row that this range serves. #[cfg_attr(not(test), expect(dead_code))] pub(crate) last_row: u64, + /// The decoding stage that reads this range. + #[cfg_attr(not(test), expect(dead_code))] + pub(crate) stage: ScanStage, } /// Compares the public fields only. `first_row` and `last_row` count from /// the start of a plan, so they differ between two plans of the same decoder. +/// `stage` follows from the column and the decoder. impl PartialEq for PlannedRange { fn eq(&self, other: &Self) -> bool { let Self { @@ -60,6 +64,7 @@ impl PartialEq for PlannedRange { kind, first_row: _, last_row: _, + stage: _, } = self; *range == other.range && *row_group == other.row_group @@ -124,24 +129,36 @@ pub(crate) use super::reader_builder::Stage as ScanStage; /// rebuild the decoder with [`ParquetPushDecoder::into_builder`], the old /// plan is not valid for the new decoder. Call `scan_plan` again on the new /// decoder. -/// * Row groups are in read order. In a row group, the columns of the -/// [`RowFilter`] predicates come first, then the other output columns. The -/// ranges are ordered by the first row that they serve, and the ranges of -/// one column chunk stay in file order. +/// * Row groups are in read order. The order in a row group depends on the +/// [`RequestGranularity`]: +/// * With [`RequestGranularity::RowGroup`], the columns of the +/// [`RowFilter`] predicates come first, then the other output columns. +/// * With [`RequestGranularity::Batch`], the decoder evaluates the +/// predicates and decodes the output one window of `batch_size` rows at +/// a time. The plan lists the ranges of each window in the same order: +/// the predicate columns of the window, then its output columns. A range +/// is in the first window that reads it. If the predicates remove all +/// rows of a window, the decoder requests the later stages of the window +/// in a later window, or not at all. A row group that +/// [`ParquetPushDecoder::try_next_reader`] reads has the order of +/// [`RequestGranularity::RowGroup`]. +/// +/// In each stage, the ranges are ordered by the first row that they serve. +/// The ranges of one column chunk stay in file order. /// * There is one range for each page if the column has an offset index, /// and one range for the entire column chunk if not. /// * The plan does not change decoding, does no I/O and does not depend /// on pushed data. /// * Without a row selection, the state of the plan does not grow with the /// number of pages. With a row selection, the plan keeps the indexes of -/// the selected pages of each column chunk in the current decoding stage -/// of the current row group. +/// the selected pages of each read column chunk of the current row group. /// * If the decoder will return an error for a row group, the plan ends /// before that row group. An example is a row selection with more rows /// than the row group. /// -/// Keep the fetched ranges in your own cache, and answer each `NeedsData` -/// with exactly the requested ranges. See [`ParquetPushDecoder::push_ranges`]. +/// You can push the fetched ranges before the decoder requests them, or +/// keep them in your own cache and answer each `NeedsData` from it. See +/// [`ParquetPushDecoder::push_ranges`]. /// /// # Example /// @@ -216,6 +233,10 @@ pub(crate) use super::reader_builder::Stage as ScanStage; /// ``` /// /// [`RowFilter`]: crate::arrow::arrow_reader::RowFilter +/// [`RequestGranularity`]: super::RequestGranularity +/// [`RequestGranularity::RowGroup`]: super::RequestGranularity::RowGroup +/// [`RequestGranularity::Batch`]: super::RequestGranularity::Batch +/// [`ParquetPushDecoder::try_next_reader`]: super::ParquetPushDecoder::try_next_reader /// [`DecodeResult::NeedsData`]: crate::DecodeResult::NeedsData /// [`ParquetPushDecoder::scan_plan`]: super::ParquetPushDecoder::scan_plan /// [`ParquetPushDecoder::into_builder`]: super::ParquetPushDecoder::into_builder @@ -244,6 +265,8 @@ struct Planner { /// The row group that the decoder was fetching when the plan was made. /// It is planned first. active_row_group: Option, + /// The decoder reads `active_row_group` one window at a time. + active_windowed: bool, /// The decoder's projection, predicates and batch size. columns: Arc, /// Planned rows before the next row group. @@ -261,6 +284,9 @@ struct StageColumns { batch_size: usize, /// What each decoding stage fetches, shared with the decoder. stages: Arc, + /// The decoder reads the row groups that it has not started one window + /// of `batch_size` rows at a time. + windowed: bool, } /// Builds a [`ScanPlan`] from a decoder's row-group frontier and the columns @@ -269,28 +295,43 @@ struct StageColumns { pub(crate) struct ScanPlanBuilder { frontier: RowGroupFrontier, active_row_group: Option, + active_windowed: bool, columns: StageColumns, } impl ScanPlanBuilder { /// Plan the row groups in `frontier`, decoding in batches of - /// `batch_size` rows with the decoding stages `stages`. + /// `batch_size` rows with the decoding stages `stages`. `windowed`: the + /// decoder reads these row groups one window of `batch_size` rows at a + /// time. pub(crate) fn new( frontier: RowGroupFrontier, batch_size: usize, stages: Arc, + windowed: bool, ) -> Self { Self { frontier, active_row_group: None, - columns: StageColumns { batch_size, stages }, + active_windowed: false, + columns: StageColumns { + batch_size, + stages, + windowed, + }, } } /// Plan `active_row_group` first: the row group that the decoder is - /// fetching, which the frontier has already handed over. - pub(crate) fn with_active_row_group(mut self, active_row_group: Option) -> Self { + /// fetching, which the frontier has already handed over. `windowed`: the + /// decoder reads it one window at a time. + pub(crate) fn with_active_row_group( + mut self, + active_row_group: Option, + windowed: bool, + ) -> Self { self.active_row_group = active_row_group; + self.active_windowed = windowed; self } @@ -298,11 +339,13 @@ impl ScanPlanBuilder { let Self { frontier, active_row_group, + active_windowed, columns, } = self; let planner = Planner { frontier, active_row_group, + active_windowed, columns: Arc::new(columns), next_row: 0, current: None, @@ -322,9 +365,12 @@ impl Planner { fn plan_next_row_group(&mut self) -> Result { // Use the decoder's own row-group walk, so row groups that the // selection or the budget removes are skipped here too. - let next_row_group = match self.active_row_group.take() { - Some(active) => Some(active), - None => self.frontier.next_readable_row_group()?, + let (next_row_group, windowed) = match self.active_row_group.take() { + Some(active) => (Some(active), self.active_windowed), + None => ( + self.frontier.next_readable_row_group()?, + self.columns.windowed, + ), }; let Some(NextRowGroup { row_group_idx, @@ -384,39 +430,36 @@ impl Planner { let num_columns = row_group.columns().len(); let mut planned_columns = vec![false; num_columns]; - let mut stage_plans = vec![]; + // `columns_to_fetch` filters, so it gives no size hint. Reserve for + // every column to avoid growing the vector one column at a time. + let mut cursors = Vec::with_capacity(num_columns); for (stage, fetch) in stages.stages() { // The decoder reuses a column that an earlier stage read. - // `columns_to_fetch` filters, so it gives no size hint. Reserve - // for every column to avoid growing the vector one column at a time. - let mut columns = Vec::with_capacity(num_columns); - columns.extend(columns_to_fetch(fetch.projection, num_columns, |idx| { - planned_columns[idx] - })); - // The plan keeps `columns` until the end of the row group. Release - // the capacity that a narrow projection does not use. - columns.shrink_to_fit(); - for &column_idx in &columns { + let columns = + columns_to_fetch(fetch.projection, num_columns, |idx| planned_columns[idx]); + let stage_start = cursors.len(); + cursors.extend(columns.map(|column_idx| (column_idx, stage))); + for &(column_idx, _) in &cursors[stage_start..] { planned_columns[column_idx] = true; } - stage_plans.push(StagePlan { stage, columns }); } + // The plan keeps `cursors` until the end of the row group. Release + // the capacity that a narrow projection does not use. + cursors.shrink_to_fit(); - self.current = Some(RowGroupRanges { - row_group: RowGroupContext { - row_group_idx, - row_count, - first_row, - rows, - selection, - expanded_selection, - stages: Arc::clone(&self.columns.stages), - metadata: Arc::clone(metadata), - page_index, - }, - stages: stage_plans.into_iter(), - stage: None, - }); + let row_group = RowGroupContext { + row_group_idx, + row_count, + first_row, + rows, + selection, + expanded_selection, + window_rows: windowed.then_some(self.columns.batch_size as u64), + stages: Arc::clone(&self.columns.stages), + metadata: Arc::clone(metadata), + page_index, + }; + self.current = Some(RowGroupRanges::new(row_group, cursors)); Ok(true) } } @@ -454,28 +497,30 @@ impl Planner { /// Once [`ScanPlan::next`] returns `None`, it always returns `None`. impl FusedIterator for ScanPlan {} -/// The columns that one decoding stage of a row group reads first. -#[derive(Debug, Clone)] -struct StagePlan { - stage: ScanStage, - /// Leaf column indexes, in file order. - columns: Vec, -} - /// The planned ranges of one row group, in decode order. /// -/// Each stage is a merge of one cursor per column chunk. A cursor +/// The ranges are a merge of one cursor per read column chunk. A cursor /// returns the ranges of its column chunk in file order, and their first /// rows do not decrease. A heap picks the cursor whose next range has the -/// smallest [`RangeOrder`], so the ranges of a stage are ordered by first -/// row without collecting and sorting all of them. +/// smallest [`RangeKey`], so the ranges are in decode order without +/// collecting and sorting all of them. +/// +/// A cursor is one heap entry: the sort key of its next range, the cursor +/// position and the position of that range. The other parts of the range +/// are computed again when the entry is popped. Thus a cursor stores no +/// state other than its heap entry, unless the selection removes pages. #[derive(Debug, Clone)] struct RowGroupRanges { row_group: RowGroupContext, - /// Stages not yet started. - stages: std::vec::IntoIter, - /// The stage being merged. - stage: Option, + /// The leaf column index and the reading stage of each cursor. A + /// [`HeapEntry`] refers to a cursor by its position in this list. + cursors: Vec<(usize, ScanStage)>, + /// For each cursor, the indexes of the data pages that the decoder + /// reads, if the selection removes pages. `None` if no cursor has such + /// a list. + selected: Option>>>, + /// The next range of each cursor that has one, smallest first. + heap: BinaryHeap>, } /// What the ranges of one row group are computed from. @@ -491,6 +536,9 @@ struct RowGroupContext { /// The selection expanded to batch boundaries, for cached predicate /// columns. expanded_selection: Option, + /// The planned rows of one window, if the decoder reads the row group + /// one window at a time. See [`RangeKey`]. + window_rows: Option, /// What each decoding stage fetches. stages: Arc, /// The file metadata, for the byte ranges of the column chunks. @@ -499,26 +547,6 @@ struct RowGroupContext { page_index: Option>, } -/// The merge state of one stage. -/// -/// A cursor of a column chunk is one heap entry: the sort key of its next -/// range, the column and the position of that range. The other parts of the -/// range are computed again when the entry is popped. Thus a stage stores -/// no per-column state other than its heap entry, unless the selection -/// removes pages. -#[derive(Debug, Clone)] -struct StageRanges { - /// Leaf column indexes, in file order. A [`HeapEntry`] refers to a - /// column by its position in this list. - columns: Vec, - /// For each column in `columns`, the indexes of the data pages that the - /// decoder reads, if the selection removes pages. `None` if no column of - /// the stage has such a list. - selected: Option>>>, - /// The next range of each cursor that has one, smallest first. - heap: BinaryHeap>, -} - /// How the heap orders the next ranges of different column chunks: by first /// row, then more rows first (a dictionary page), then by file offset. The /// ranges of one column chunk keep file order, also a page with no planned @@ -527,11 +555,29 @@ struct StageRanges { /// The key is `(first row, Reverse(last row), range start)`. type RangeOrder = (u64, Reverse, u64); +/// The decode order of a range: `(window, stage, order)`. +/// +/// The decoder reads the stages of a row group in order. Without windows, +/// the window is 0, so all ranges of a stage come before the next stage. +/// With windows, the decoder runs all stages for the first `batch_size` +/// planned rows of the row group, then for the next `batch_size` rows, and +/// so on. The window of a range is the window of its first row: +/// +/// ```text +/// batch_size = 100, predicate on `a`, output `c` +/// +/// rows: 0 100 200 +/// a pages: ├─ a0 ───┼─ a1 ────┤ +/// c pages: ├ c0 ┼ c1 ┼ c2 ┼ c3 ┤ +/// plan: a0 c0 c1 a1 c2 c3 +/// ``` +type RangeKey = (u64, ScanStage, RangeOrder); + /// A heap entry: the sort key of the next range of a cursor, the position -/// of the column in [`StageRanges::columns`], and the [`HeadPosition`] of -/// that range. The column position breaks ties, so ranges with equal keys +/// of the cursor in [`RowGroupRanges::cursors`], and the [`HeadPosition`] of +/// that range. The cursor position breaks ties, so ranges with equal keys /// stay in file order of their columns. -type HeapEntry = (RangeOrder, u32, HeadPosition); +type HeapEntry = (RangeKey, u32, HeadPosition); /// Which range of a column chunk is next: [`CHUNK`], [`DICTIONARY`], or the /// position of a data page in the pages that the decoder reads. @@ -543,7 +589,7 @@ const CHUNK: HeadPosition = u32::MAX; /// The next range is the dictionary page. const DICTIONARY: HeadPosition = u32::MAX - 1; -/// Converts a column or page position to a heap entry field. +/// Converts a cursor or page position to a heap entry field. fn position(position: usize) -> u32 { u32::try_from(position).expect("fewer than u32::MAX - 1 columns and pages") } @@ -574,8 +620,28 @@ impl PageSet<'_> { } } -impl StageRanges { - /// The data pages that the decoder reads of the column at `slot`, whose +impl RowGroupRanges { + fn new(row_group: RowGroupContext, cursors: Vec<(usize, ScanStage)>) -> Self { + let mut selected = None; + let mut heap = Vec::with_capacity(cursors.len()); + for (slot, &(column_idx, stage)) in cursors.iter().enumerate() { + let (head, pages) = row_group.first_range(column_idx, stage); + if let Some(pages) = pages { + selected.get_or_insert_with(|| vec![None; cursors.len()])[slot] = Some(pages); + } + if let Some((order, head)) = head { + heap.push(Reverse((row_group.key(stage, order), position(slot), head))); + } + } + Self { + row_group, + cursors, + selected, + heap: BinaryHeap::from(heap), + } + } + + /// The data pages that the decoder reads of the cursor at `slot`, whose /// page locations are `locations`. fn pages(&self, slot: usize, locations: &[PageLocation]) -> PageSet<'_> { match self @@ -587,67 +653,53 @@ impl StageRanges { None => PageSet::All(locations.len()), } } -} -impl RowGroupRanges { fn next(&mut self) -> Option { - loop { - if let Some(stage) = self.stage.as_mut() - && let Some(Reverse(((first_row, Reverse(last_row), start), slot, head))) = - stage.heap.pop() - { - let row_group = &self.row_group; - let column_idx = stage.columns[slot as usize]; - let (end, kind) = if head == CHUNK { - (row_group.chunk(column_idx).end, PageKind::ColumnChunk) - } else { - let locations = row_group - .locations(column_idx) - .expect("pages have locations"); - let pages = stage.pages(slot as usize, locations); - let (end, kind, next) = if head == DICTIONARY { - (locations[0].offset as u64, PageKind::Dictionary, 0) - } else { - let page = page_range(&locations[pages.page(head as usize)]); - (page.end, PageKind::Data, head as usize + 1) - }; - if let Some(order) = row_group.data_page(locations, pages, next) { - stage.heap.push(Reverse((order, slot, position(next)))); - } - (end, kind) - }; - return Some(PlannedRange { - range: start..end, - row_group: row_group.row_group_idx, - column: column_idx, - kind, - first_row, - last_row, - }); - } - let plan = self.stages.next()?; - let mut selected = None; - let mut heap = Vec::with_capacity(plan.columns.len()); - for (slot, &column_idx) in plan.columns.iter().enumerate() { - let (head, pages) = self.row_group.first_range(column_idx, plan.stage); - if let Some(pages) = pages { - selected.get_or_insert_with(|| vec![None; plan.columns.len()])[slot] = - Some(pages); - } - if let Some((order, head)) = head { - heap.push(Reverse((order, position(slot), head))); - } + let Reverse(((_, stage, (first_row, Reverse(last_row), start)), slot, head)) = + self.heap.pop()?; + let row_group = &self.row_group; + let column_idx = self.cursors[slot as usize].0; + let (end, kind) = if head == CHUNK { + (row_group.chunk(column_idx).end, PageKind::ColumnChunk) + } else { + let locations = row_group + .locations(column_idx) + .expect("pages have locations"); + let pages = self.pages(slot as usize, locations); + let (end, kind, next) = if head == DICTIONARY { + (locations[0].offset as u64, PageKind::Dictionary, 0) + } else { + let page = page_range(&locations[pages.page(head as usize)]); + (page.end, PageKind::Data, head as usize + 1) + }; + if let Some(order) = row_group.data_page(locations, pages, next) { + let key = row_group.key(stage, order); + self.heap.push(Reverse((key, slot, position(next)))); } - self.stage = Some(StageRanges { - columns: plan.columns, - selected, - heap: BinaryHeap::from(heap), - }); - } + (end, kind) + }; + Some(PlannedRange { + range: start..end, + row_group: self.row_group.row_group_idx, + column: column_idx, + kind, + first_row, + last_row, + stage, + }) } } impl RowGroupContext { + /// The [`RangeKey`] of a range that `stage` reads, ordered by `order`. + fn key(&self, stage: ScanStage, order: RangeOrder) -> RangeKey { + let window = match self.window_rows { + Some(window_rows) => (order.0 - self.first_row) / window_rows, + None => 0, + }; + (window, stage, order) + } + fn locations(&self, column_idx: usize) -> Option<&[PageLocation]> { self.page_index .as_ref()? diff --git a/parquet/src/arrow/push_decoder/scan_plan/tests.rs b/parquet/src/arrow/push_decoder/scan_plan/tests.rs index a7406297b2fe..227317db6642 100644 --- a/parquet/src/arrow/push_decoder/scan_plan/tests.rs +++ b/parquet/src/arrow/push_decoder/scan_plan/tests.rs @@ -10,7 +10,7 @@ use crate::arrow::arrow_reader::{ ArrowPredicateFn, ArrowReaderMetadata, ArrowReaderOptions, RowFilter, RowSelector, }; use crate::arrow::push_decoder::{ - ParquetPushDecoder, ParquetPushDecoderBuilder, RowGroupSelection, + ParquetPushDecoder, ParquetPushDecoderBuilder, RequestGranularity, RowGroupSelection, }; use crate::arrow::{ArrowWriter, ProjectionMask}; use crate::column::writer::ColumnCloseResult; @@ -139,23 +139,12 @@ fn decode_with( } /// Collect `plan`, and the decoding stage that reads each of its ranges. -/// -/// A [`PlannedRange`] does not give its stage, so this reads the stage from -/// the state of the planner. -fn collect_with_stages(mut plan: ScanPlan) -> (Vec, Vec) { - let mut ranges = vec![]; - let mut stages = vec![]; - while let Some(range) = plan.next() { - let planner = plan.planner.as_ref().unwrap(); - let all_stages: Vec<_> = planner.columns.stages.stages().map(|(s, _)| s).collect(); - // The planner starts the next stage only when it is asked for a range - // of it. Thus the stages that it has not started are the stages after - // the stage of `range`. - let later_stages = planner.current.as_ref().unwrap().stages.len(); - ranges.push(range); - stages.push(all_stages[all_stages.len() - 1 - later_stages]); - } - (ranges, stages) +fn collect_with_stages(plan: ScanPlan) -> (Vec, Vec) { + plan.map(|range| { + let stage = range.stage; + (range, stage) + }) + .unzip() } /// Check the documented order of `plan`, whose ranges are read by `stages`: @@ -882,14 +871,68 @@ fn plan_is_lazy() { let mut plan = decoder.scan_plan(); let first = plan.next().unwrap(); assert_eq!(first.row_group, 0); - // Only the first row group has been started, and only the first - // stage of it. + // Only the first row group has been started. let planner = plan.planner.as_ref().unwrap(); let current = planner.current.as_ref().unwrap(); assert_eq!(current.row_group.row_group_idx, 0); assert_eq!(planner.next_row, 200); // One cursor per projected column, not one entry per page. - assert_eq!(current.stage.as_ref().unwrap().heap.len(), 3); + assert_eq!(current.heap.len(), 3); +} + +/// With [`RequestGranularity::Batch`], `try_decode` evaluates the row +/// filter and decodes the output one window of `batch_size` rows at a time. +/// The plan lists the ranges in the order of the requests. +/// +/// The predicates keep rows in each window. If they removed all rows of a +/// window, the decoder would request the later stages of that window in a +/// later window. +#[test] +fn plan_order_matches_batch_requests_with_row_filter() { + let filter = || { + RowFilter::new(vec![ + Box::new(ArrowPredicateFn::new(mask([0]), |batch| { + gt(batch.column(0), &Int64Array::new_scalar(-1)) + })), + Box::new(ArrowPredicateFn::new(mask([1]), |batch| { + lt(batch.column(0), &Int64Array::new_scalar(3)) + })), + ]) + }; + // `a` is a predicate column. With `a` in the output, the predicate + // cache holds it. + for (name, projection) in [("output c", [2].as_slice()), ("output a, c", &[0, 2])] { + let builder = || { + builder() + .with_request_granularity(RequestGranularity::Batch) + .with_projection(mask(projection.iter().copied())) + .with_row_filter(filter()) + }; + let plan: Vec<_> = builder().build().unwrap().scan_plan().collect(); + let (requested, _) = demand(builder()); + + // The position in the plan of each requested range. + let positions: Vec = requested + .iter() + .map(|r| { + plan.iter() + .position(|p| r.start <= p.range.start && p.range.end <= r.end) + .unwrap_or_else(|| panic!("{name}: {r:?} is not planned")) + }) + .collect(); + assert!(positions.is_sorted(), "{name}: {positions:?}"); + + // The decoder reads the predicate pages of later windows after the + // output pages of earlier windows. + let stages: Vec<_> = positions.iter().map(|&idx| plan[idx].stage).collect(); + assert!( + stages + .windows(2) + .any(|s| s[0] == ScanStage::Projection && s[1] == ScanStage::Predicate(0)), + "{name}: {stages:?}" + ); + decode_from_plan(name, builder); + } } #[test] diff --git a/parquet/src/util/push_buffers.rs b/parquet/src/util/push_buffers.rs index cd731cf27895..2fd5137ec123 100644 --- a/parquet/src/util/push_buffers.rs +++ b/parquet/src/util/push_buffers.rs @@ -10,6 +10,11 @@ use std::collections::VecDeque; use std::fmt::Display; use std::ops::Range; +/// A [`PushBuffers`] that the push decoder shares with the column readers of +/// `ColumnChunkData::Shared`. +#[cfg(feature = "arrow")] +pub(crate) type SharedPushBuffers = std::sync::Arc>; + /// Holds multiple non-contiguous, caller-provided buffers of file data. /// /// This is the in-memory buffer used by the push-based Parquet decoders @@ -206,6 +211,24 @@ impl PushBuffers { .map(|(idx, _)| idx) } + /// The bytes from `start` to the end of the buffer that contains `start` + /// and reaches furthest, if any. + #[cfg(feature = "arrow")] + pub(crate) fn get_from(&self, start: u64) -> Option { + let candidates = self.ranges.partition_point(|r| r.start <= start); + let idx = self + .ranges + .range(..candidates) + .enumerate() + .rev() + .take_while(|(_, r)| r.start.saturating_add(self.max_len.get()) > start) + .filter(|(_, r)| r.end > start) + .max_by_key(|(_, r)| r.end) + .map(|(idx, _)| idx)?; + let offset = (start - self.ranges[idx].start) as usize; + Some(self.buffers[idx].slice(offset..)) + } + /// return the file length of the Parquet file being read pub(crate) fn file_len(&self) -> u64 { self.file_len diff --git a/parquet/tests/arrow_reader/mod.rs b/parquet/tests/arrow_reader/mod.rs index e872ae77e1c8..c7eef200f9ba 100644 --- a/parquet/tests/arrow_reader/mod.rs +++ b/parquet/tests/arrow_reader/mod.rs @@ -43,6 +43,7 @@ mod partial_offset_index; #[cfg(feature = "async")] mod predicate_cache; mod push_decoder_equivalence; +mod push_decoder_incremental; mod row_filter; mod statistics; diff --git a/parquet/tests/arrow_reader/push_decoder_equivalence.rs b/parquet/tests/arrow_reader/push_decoder_equivalence.rs index 473e1b5e8d7d..e0e8a8becc7f 100644 --- a/parquet/tests/arrow_reader/push_decoder_equivalence.rs +++ b/parquet/tests/arrow_reader/push_decoder_equivalence.rs @@ -6,9 +6,10 @@ //! //! Each test describes a scan as a [`Scan`], and [`assert_same_rows`] checks //! that the push decoder returns the same rows, in the same order, as -//! [`ParquetRecordBatchReader`] for the same scan. The `test_fuzz_*` tests -//! use [`proptest`] to combine the scan options at random and to shrink a -//! scan that fails. +//! [`ParquetRecordBatchReader`] for the same scan, and that +//! [`RequestGranularity::Batch`] returns the same batches as the default +//! [`RequestGranularity::RowGroup`]. The `test_fuzz_*` tests use [`proptest`] to +//! combine the scan options at random and to shrink a scan that fails. //! //! [`ParquetRecordBatchReader`]: parquet::arrow::arrow_reader::ParquetRecordBatchReader @@ -27,7 +28,9 @@ use parquet::arrow::arrow_reader::{ ArrowPredicate, ArrowPredicateFn, ArrowReaderMetadata, ArrowReaderOptions, ParquetRecordBatchReaderBuilder, RowFilter, RowSelection, RowSelectionPolicy, RowSelector, }; -use parquet::arrow::push_decoder::{ParquetPushDecoder, ParquetPushDecoderBuilder}; +use parquet::arrow::push_decoder::{ + ParquetPushDecoder, ParquetPushDecoderBuilder, RequestGranularity, +}; use parquet::arrow::{ArrowWriter, ProjectionMask}; use parquet::file::metadata::PageIndexPolicy; use parquet::file::properties::WriterProperties; @@ -41,9 +44,9 @@ use std::cell::Cell; use std::ops::Range; use std::sync::{Arc, LazyLock}; -const ROWS_PER_ROW_GROUP: usize = 600; -const ROWS_PER_PAGE: usize = 25; -const NUM_ROWS: usize = 1800; +pub(super) const ROWS_PER_ROW_GROUP: usize = 600; +pub(super) const ROWS_PER_PAGE: usize = 25; +pub(super) const NUM_ROWS: usize = 1800; /// Three row groups of 600 rows, with a new data page each 25 rows or less, /// columns: @@ -53,12 +56,12 @@ const NUM_ROWS: usize = 1800; /// * `c`: a string (plain) /// * `l`: a list of 0 to 3 `a` values, some lists null (plain) /// * `s`: a struct of `a * 2` and `a % 7` (plain) -struct TestFile { - data: Bytes, - batch: RecordBatch, +pub(super) struct TestFile { + pub(super) data: Bytes, + pub(super) batch: RecordBatch, } -static TEST_FILE: LazyLock = LazyLock::new(|| { +pub(super) static TEST_FILE: LazyLock = LazyLock::new(|| { let a: Vec = (0..NUM_ROWS as i64).collect(); let mut lists = ListBuilder::new(Int64Builder::new()); for &v in &a { @@ -138,7 +141,7 @@ static HETEROGENEOUS_FILE: LazyLock = LazyLock::new(|| { Bytes::from(buffer) }); -fn load_metadata(data: &Bytes, policy: PageIndexPolicy) -> ArrowReaderMetadata { +pub(super) fn load_metadata(data: &Bytes, policy: PageIndexPolicy) -> ArrowReaderMetadata { let options = ArrowReaderOptions::new().with_page_index_policy(policy); ArrowReaderMetadata::load(data, options).unwrap() } @@ -152,7 +155,7 @@ static HETEROGENEOUS_WITH_PAGE_INDEX: LazyLock = static HETEROGENEOUS_WITHOUT_PAGE_INDEX: LazyLock = LazyLock::new(|| load_metadata(&HETEROGENEOUS_FILE, PageIndexPolicy::Skip)); -fn metadata(page_index: bool) -> ArrowReaderMetadata { +pub(super) fn metadata(page_index: bool) -> ArrowReaderMetadata { if page_index { WITH_PAGE_INDEX.clone() } else { @@ -168,15 +171,20 @@ fn schema() -> SchemaDescriptor { .clone() } -fn columns(names: &[&str]) -> ProjectionMask { +pub(super) fn columns(names: &[&str]) -> ProjectionMask { ProjectionMask::columns(&schema(), names.iter().copied()) } /// Decode `file`, pushing exactly the requested ranges. Returns the batches /// and every range that the decoder requested, in order. +/// +/// `last_batch_ends_scan`: the decoder knows that the last batch is the last +/// when it returns that batch. This is false for batch mode with predicates: +/// the windows after the last batch can have rows that no predicate passes. fn drive_file( mut decoder: ParquetPushDecoder, file: &Bytes, + last_batch_ends_scan: bool, ) -> (Vec, Vec>) { let mut batches = vec![]; let mut requested = vec![]; @@ -200,16 +208,19 @@ fn drive_file( } } // The last batch finishes the last row group, which releases its bytes. - assert_eq!( - buffered_after_last_batch, 0, - "bytes left after the last batch" - ); + if last_batch_ends_scan { + assert_eq!( + buffered_after_last_batch, 0, + "bytes left after the last batch" + ); + } + assert_eq!(decoder.buffered_bytes(), 0, "bytes left after the scan"); (batches, requested) } /// A predicate on one column: an Int64 column unless noted. #[derive(Clone, Copy, Debug)] -enum Cmp { +pub(super) enum Cmp { Lt(i64), Ge(i64), ModNotZero(i64), @@ -224,13 +235,13 @@ enum Cmp { } #[derive(Clone, Debug)] -struct PredicateSpec { +pub(super) struct PredicateSpec { column: &'static str, cmp: Cmp, } impl PredicateSpec { - fn new(column: &'static str, cmp: Cmp) -> Self { + pub(super) fn new(column: &'static str, cmp: Cmp) -> Self { Self { column, cmp } } @@ -319,20 +330,20 @@ macro_rules! apply_options { /// A scan configuration, so that the same scan can be built for more than /// one reader. #[derive(Clone, Debug, Default)] -struct Scan { +pub(super) struct Scan { /// Read [`HETEROGENEOUS_FILE`] instead of [`TEST_FILE`]. - heterogeneous: bool, - page_index_off: bool, - batch_size: Option, - projection: Option, - row_groups: Option>, - selection: Option, - limit: Option, - offset: Option, + pub(super) heterogeneous: bool, + pub(super) page_index_off: bool, + pub(super) batch_size: Option, + pub(super) projection: Option, + pub(super) row_groups: Option>, + pub(super) selection: Option, + pub(super) limit: Option, + pub(super) offset: Option, /// Built again for each reader, as predicates have state. - predicates: Vec, - policy: Option, - max_predicate_cache_size: Option, + pub(super) predicates: Vec, + pub(super) policy: Option, + pub(super) max_predicate_cache_size: Option, } impl Scan { @@ -344,7 +355,7 @@ impl Scan { } } - fn data(&self) -> &'static Bytes { + pub(super) fn data(&self) -> &'static Bytes { if self.heterogeneous { &HETEROGENEOUS_FILE } else { @@ -352,9 +363,22 @@ impl Scan { } } - fn push_decoder(&self) -> ParquetPushDecoder { + pub(super) fn builder(&self) -> ParquetPushDecoderBuilder { let builder = ParquetPushDecoderBuilder::new_with_metadata(self.metadata()); - apply_options!(self, builder).build().unwrap() + apply_options!(self, builder) + } + + /// A decoder with [`RequestGranularity::RowGroup`], the default. + pub(super) fn row_group_decoder(&self) -> ParquetPushDecoder { + self.builder().build().unwrap() + } + + /// A decoder with [`RequestGranularity::Batch`]. + pub(super) fn batch_decoder(&self) -> ParquetPushDecoder { + self.builder() + .with_request_granularity(RequestGranularity::Batch) + .build() + .unwrap() } /// The batches of the scan from the sync reader. @@ -369,6 +393,20 @@ impl Scan { } } +/// Sort and merge ranges into disjoint, non-adjacent ranges. +pub(super) fn union(ranges: impl IntoIterator>) -> Vec> { + let mut ranges: Vec<_> = ranges.into_iter().filter(|r| !r.is_empty()).collect(); + ranges.sort_by_key(|r| r.start); + let mut merged: Vec> = vec![]; + for range in ranges { + match merged.last_mut() { + Some(last) if range.start <= last.end => last.end = last.end.max(range.end), + _ => merged.push(range), + } + } + merged +} + /// What the push decoder did for a scan. struct Decoded { /// Rows returned. @@ -385,7 +423,35 @@ struct Decoded { #[track_caller] fn assert_same_rows(scan: &Scan) -> Decoded { let (schema, expected) = scan.sync_batches(); - let (actual, requested) = drive_file(scan.push_decoder(), scan.data()); + let (actual, requested) = drive_file(scan.row_group_decoder(), scan.data(), true); + // `RequestGranularity::Batch` gives the same batches, with the same + // boundaries. + let (batch_mode, mut batch_mode_requested) = drive_file( + scan.batch_decoder(), + scan.data(), + scan.predicates.is_empty(), + ); + // Do not print the batches: proptest runs a failing scan many times to + // shrink it. + assert!(batch_mode == actual, "batch mode differs for {scan:?}"); + // Without predicates, both modes read the same bytes. Batch mode asks for + // them in more and smaller requests. + if scan.predicates.is_empty() { + assert_eq!( + union(batch_mode_requested.clone()), + union(requested.clone()), + "batch mode read other bytes for {scan:?}" + ); + } + // A range requested twice means the decoder released it too early. + let num_requested = batch_mode_requested.len(); + batch_mode_requested.sort_by_key(|r| (r.start, r.end)); + batch_mode_requested.dedup(); + assert_eq!( + batch_mode_requested.len(), + num_requested, + "batch mode requested a range twice for {scan:?}" + ); if let Some(batch_size) = scan.batch_size { assert!( actual.iter().all(|b| b.num_rows() <= batch_size), @@ -394,8 +460,6 @@ fn assert_same_rows(scan: &Scan) -> Decoded { } let expected = concat_batches(&schema, &expected).unwrap(); let actual = concat_batches(&schema, &actual).unwrap(); - // Do not print the rows: proptest runs a failing scan many times to - // shrink it. assert!( actual == expected, "rows differ for {scan:?}: {} rows, expected {}", @@ -420,6 +484,15 @@ fn test_empty_selection_requests_nothing() { assert!(decoded.requested.is_empty()); } +/// A scan with predicates and a batch size of 100. +pub(super) fn filtered(predicates: Vec) -> Scan { + Scan { + batch_size: Some(100), + predicates, + ..Default::default() + } +} + /// A selection of `total` rows: runs of skipped and selected rows in turn. /// It shrinks to a selection with fewer and shorter runs. fn selection_strategy(total: usize) -> impl Strategy { diff --git a/parquet/tests/arrow_reader/push_decoder_incremental.rs b/parquet/tests/arrow_reader/push_decoder_incremental.rs new file mode 100644 index 000000000000..7e94a6a621ef --- /dev/null +++ b/parquet/tests/arrow_reader/push_decoder_incremental.rs @@ -0,0 +1,675 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Tests for the behavior that is specific to [`RequestGranularity::Batch`]. +//! +//! The tests in [`push_decoder_equivalence`](super::push_decoder_equivalence) check that +//! batch mode returns the same batches as the row-group mode. The tests here +//! check: +//! +//! * Request shape: the decoder requests only the pages of the next batch +//! ([`test_partial_pushes_across_batches`], +//! [`test_predicates_do_not_wait_for_the_row_group`], +//! [`test_dictionary_page_is_requested_once_per_column_chunk`]). +//! * Memory release: the decoder releases the pages of a batch when it +//! returns the batch +//! ([`test_releases_bytes_pushed_ahead`], +//! [`test_predicates_release_bytes_pushed_ahead`]). +//! * The API: row group boundaries, `into_builder`, `try_next_reader` and +//! configuration errors. + +use super::push_decoder_equivalence::{ + Cmp, NUM_ROWS, PredicateSpec, ROWS_PER_ROW_GROUP, Scan, TEST_FILE, columns, filtered, + load_metadata, metadata, union, +}; +use arrow_array::RecordBatch; +use arrow_array::cast::AsArray; +use arrow_array::types::Int64Type; +use bytes::Bytes; +use parquet::DecodeResult; +use parquet::arrow::ArrowWriter; +use parquet::arrow::arrow_reader::{ArrowPredicateFn, RowFilter, RowSelection, RowSelector}; +use parquet::arrow::push_decoder::{ + ParquetPushDecoder, ParquetPushDecoderBuilder, RequestGranularity, +}; +use parquet::file::metadata::PageIndexPolicy; +use std::ops::{ControlFlow, Range}; +use std::sync::Arc; + +fn fetch(range: &Range) -> Bytes { + TEST_FILE + .data + .slice(range.start as usize..range.end as usize) +} + +/// What a decode run cost. +#[derive(Debug, Default)] +struct Cost { + /// `NeedsData` results. + rounds: usize, + /// Every range requested, in order. + requested: Vec>, +} + +/// What [`drive_with`] passes to its callback. +enum Event<'a> { + /// The decoder requested these ranges, and they were pushed. + Pushed(&'a [Range]), + /// The decoder returned a batch. + Batch(RecordBatch), +} + +/// Decode `file`, pushing exactly the requested ranges, and call `on_event` +/// after each push and for each batch. Returns the value of the first +/// [`ControlFlow::Break`], or `None` when the decoder finishes. +fn drive_with( + decoder: &mut ParquetPushDecoder, + file: &Bytes, + mut on_event: impl FnMut(&mut ParquetPushDecoder, Event<'_>) -> ControlFlow, +) -> Option { + loop { + let event = match decoder.try_decode().unwrap() { + DecodeResult::NeedsData(ranges) => { + assert!(!ranges.is_empty()); + let data = ranges + .iter() + .map(|r| file.slice(r.start as usize..r.end as usize)) + .collect(); + decoder.push_ranges(ranges.clone(), data).unwrap(); + on_event(decoder, Event::Pushed(&ranges)) + } + DecodeResult::Data(batch) => on_event(decoder, Event::Batch(batch)), + DecodeResult::Finished => return None, + }; + if let ControlFlow::Break(value) = event { + return Some(value); + } + } +} + +/// Decode `file`, pushing exactly the requested ranges. +fn drive_file(mut decoder: ParquetPushDecoder, file: &Bytes) -> (Vec, Cost) { + let mut batches = vec![]; + let mut cost = Cost::default(); + let mut last_buffered = 0; + drive_with(&mut decoder, file, |decoder, event| { + match event { + Event::Pushed(ranges) => { + cost.rounds += 1; + cost.requested.extend_from_slice(ranges); + } + Event::Batch(batch) => { + batches.push(batch); + last_buffered = decoder.buffered_bytes(); + } + } + ControlFlow::<()>::Continue(()) + }); + // The last batch finishes the last row group, which releases its bytes. + assert_eq!(last_buffered, 0, "bytes left after the last batch"); + (batches, cost) +} + +/// Assert that the scan gives the same batches for both granularities, and +/// return the costs (row group, batch). +#[track_caller] +fn assert_same_batches(scan: &Scan) -> (Cost, Cost) { + let (expected, row_group_cost) = drive_file(scan.row_group_decoder(), scan.data()); + let (actual, batch_cost) = drive_file(scan.batch_decoder(), scan.data()); + assert_eq!( + actual.iter().map(|b| b.num_rows()).collect::>(), + expected.iter().map(|b| b.num_rows()).collect::>(), + "batch sizes differ for {scan:?}" + ); + for (i, (actual, expected)) in actual.iter().zip(&expected).enumerate() { + assert_eq!(actual, expected, "batch {i} differs for {scan:?}"); + } + // A range requested twice means the decoder released it too early. + let mut requested = batch_cost.requested.clone(); + requested.sort_by_key(|r| (r.start, r.end)); + requested.dedup(); + assert_eq!( + requested.len(), + batch_cost.requested.len(), + "a range was requested twice for {scan:?}" + ); + (row_group_cost, batch_cost) +} + +/// The dictionary page (if any) and the data pages of a column chunk, one +/// range each. +fn page_ranges(row_group: usize, column: usize) -> Vec> { + let meta = metadata(true); + let (start, len) = meta + .metadata() + .row_group(row_group) + .column(column) + .byte_range(); + let page_index = meta.metadata().page_index_for_row_group(row_group); + let locations = page_index.page_locations(column).unwrap(); + let dictionary = start..locations[0].offset as u64; + let ranges: Vec> = std::iter::once(dictionary) + .chain( + locations + .iter() + .map(|l| l.offset as u64..l.offset as u64 + l.compressed_page_size as u64), + ) + .filter(|r| !r.is_empty()) + .collect(); + assert_eq!(ranges.last().unwrap().end, start + len); + ranges +} + +fn row_group_bytes(row_group: usize) -> u64 { + metadata(true) + .metadata() + .row_group(row_group) + .columns() + .iter() + .map(|c| c.byte_range().1) + .sum() +} + +// --------------------------------------------------------------------------- +// No predicates +// --------------------------------------------------------------------------- + +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_without_offset_index_requests_column_chunks() { + let scan = Scan { + page_index_off: true, + batch_size: Some(100), + selection: Some(RowSelection::from(vec![ + RowSelector::skip(100), + RowSelector::select(1000), + ])), + ..Default::default() + }; + let (row_group, batch) = assert_same_batches(&scan); + // Without page locations, whole column chunks are requested, the same + // bytes as in the row group mode. + assert_eq!(union(row_group.requested), union(batch.requested.clone())); + let chunks: Vec> = metadata(false) + .metadata() + .row_groups() + .iter() + .flat_map(|rg| rg.columns().iter()) + .map(|c| { + let (start, len) = c.byte_range(); + start..start + len + }) + .collect(); + assert!(batch.requested.iter().all(|r| chunks.contains(r))); +} + +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_dictionary_page_is_requested_once_per_column_chunk() { + let scan = Scan { + batch_size: Some(50), + projection: Some(columns(&["b"])), + ..Default::default() + }; + let (_, batch) = assert_same_batches(&scan); + let meta = metadata(true); + let meta = meta.metadata(); + let b = 1; + for row_group in 0..meta.num_row_groups() { + let (chunk_start, _) = meta.row_group(row_group).column(b).byte_range(); + let first_page = meta + .page_index_for_row_group(row_group) + .page_locations(b) + .unwrap()[0] + .offset as u64; + assert!(first_page > chunk_start, "expected a dictionary page"); + let dictionary = chunk_start..first_page; + let count = batch.requested.iter().filter(|r| **r == dictionary).count(); + assert_eq!( + count, 1, + "dictionary {dictionary:?} requested {count} times" + ); + } +} + +/// Push only what the decoder asks for, one batch at a time, and check that +/// each request serves exactly one batch: the first request of a row group +/// is small, and each `Data` needs no further push. +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_partial_pushes_across_batches() { + let meta = metadata(true); + let batch_size = 50; + let mut decoder = Scan { + batch_size: Some(batch_size), + projection: Some(columns(&["a", "c"])), + ..Default::default() + } + .batch_decoder(); + + let mut rows = 0; + let mut requests_per_batch = vec![]; + let mut requests = 0; + drive_with(&mut decoder, &TEST_FILE.data, |_, event| { + match event { + Event::Pushed(ranges) => { + // Each request is for pages of this batch's rows only: with + // 25 rows per page and 50 rows per batch, 2 pages per column. + assert!(ranges.len() <= 4, "{ranges:?}"); + requests += 1; + } + Event::Batch(batch) => { + assert_eq!( + batch, + TEST_FILE + .batch + .project(&[0, 2]) + .unwrap() + .slice(rows, batch.num_rows()) + ); + rows += batch.num_rows(); + requests_per_batch.push(requests); + requests = 0; + } + } + ControlFlow::<()>::Continue(()) + }); + assert_eq!(rows, NUM_ROWS); + assert!( + requests_per_batch.iter().all(|&r| r == 1), + "{requests_per_batch:?}" + ); + + // The first request of the scan is a small part of the row group. + let mut decoder = Scan { + batch_size: Some(batch_size), + ..Default::default() + } + .batch_decoder(); + let DecodeResult::NeedsData(first) = decoder.try_decode().unwrap() else { + panic!("expected NeedsData"); + }; + let first_bytes: u64 = first.iter().map(|r| r.end - r.start).sum(); + assert!(first_bytes * 5 < row_group_bytes(0), "{first_bytes}"); + // The pages of the first batch, and the dictionary page of `b`. + let page_index = meta.metadata().page_index_for_row_group(0); + for column in 0..meta.metadata().row_group(0).num_columns() { + let locations = page_index.page_locations(column).unwrap(); + for location in &locations[..2] { + let start = location.offset as u64; + assert!(first.contains(&(start..start + location.compressed_page_size as u64))); + } + let later = locations[2].offset as u64; + assert!(first.iter().all(|r| r.start != later)); + } +} + +/// Push every planned byte of the first two row groups up front, one buffer +/// per page. The decoder releases the pages of each batch when it returns the +/// batch, and holds less than one batch of a row group that was not pushed +/// ahead. +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_releases_bytes_pushed_ahead() { + let meta = metadata(true); + let mut decoder = Scan { + batch_size: Some(100), + ..Default::default() + } + .batch_decoder(); + + // Push every page of the first two row groups. + let mut pushed = 0; + for row_group in 0..2 { + for (column, chunk) in meta + .metadata() + .row_group(row_group) + .columns() + .iter() + .enumerate() + { + let ranges = page_ranges(row_group, column); + pushed += chunk.byte_range().1; + let data = ranges.iter().map(fetch).collect(); + decoder.push_ranges(ranges, data).unwrap(); + } + } + assert_eq!(decoder.buffered_bytes(), pushed); + + let mut resident = vec![]; + let mut rows = 0; + drive_with(&mut decoder, &TEST_FILE.data, |decoder, event| { + match event { + // Only the third row group was not pushed. + Event::Pushed(ranges) => { + assert!(rows >= 2 * ROWS_PER_ROW_GROUP, "{rows}: {ranges:?}") + } + Event::Batch(batch) => { + rows += batch.num_rows(); + resident.push(decoder.buffered_bytes()); + } + } + ControlFlow::<()>::Continue(()) + }); + assert_eq!(rows, NUM_ROWS); + // Each row group has 6 batches. Each batch of the two row groups that + // were pushed ahead releases its pages. + assert!(resident[0] < pushed, "{resident:?}"); + assert!(resident[..12].is_sorted_by(|a, b| a > b), "{resident:?}"); + assert_eq!(resident[5], row_group_bytes(1)); + assert_eq!(resident[11], 0); + // The third row group was not pushed ahead. After each batch, only the + // dictionary pages are left. + let batch_bytes = row_group_bytes(2) / 6; + assert!( + resident[12..].iter().all(|&r| r * 4 < batch_bytes), + "{resident:?}" + ); + assert_eq!(decoder.buffered_bytes(), 0); +} + +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_row_group_boundary_is_visible_after_the_last_batch() { + let mut decoder = Scan { + batch_size: Some(250), + ..Default::default() + } + .batch_decoder(); + let mut sizes = vec![]; + let mut boundaries = vec![]; + drive_with(&mut decoder, &TEST_FILE.data, |decoder, event| { + if let Event::Batch(batch) = event { + sizes.push(batch.num_rows()); + boundaries.push(decoder.is_at_row_group_boundary()); + } + ControlFlow::<()>::Continue(()) + }); + assert_eq!(sizes, vec![250, 250, 100, 250, 250, 100, 250, 250, 100]); + assert_eq!( + boundaries, + vec![false, false, true, false, false, true, false, false, true] + ); +} + +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_into_builder_at_a_boundary() { + let mut decoder = Scan { + batch_size: Some(300), + ..Default::default() + } + .batch_decoder(); + let mut batches = vec![]; + let mut collect = |decoder: &mut ParquetPushDecoder, event: Event<'_>| { + if let Event::Batch(batch) = event { + batches.push(batch); + if decoder.is_at_row_group_boundary() { + return ControlFlow::Break(()); + } + } + ControlFlow::Continue(()) + }; + // Decode the first row group. + assert!(drive_with(&mut decoder, &TEST_FILE.data, &mut collect).is_some()); + // Skip the second row group, keep batch granularity. + let mut decoder = decoder + .into_builder() + .unwrap() + .with_row_groups(vec![2]) + .build() + .unwrap(); + drive_with(&mut decoder, &TEST_FILE.data, &mut collect); + let rows: Vec = batches + .iter() + .flat_map(|b| b.column(0).as_primitive::().values().to_vec()) + .collect(); + let expected: Vec = (0..600).chain(1200..1800).collect(); + assert_eq!(rows, expected); +} + +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_try_next_reader_at_boundaries_and_not_in_a_row_group() { + let mut decoder = Scan { + batch_size: Some(300), + ..Default::default() + } + .batch_decoder(); + // `try_next_reader` still returns whole row groups. + let file = 0..TEST_FILE.data.len() as u64; + decoder.push_range(file.clone(), fetch(&file)).unwrap(); + let DecodeResult::Data(reader) = decoder.try_next_reader().unwrap() else { + panic!("expected a reader"); + }; + assert_eq!(reader.map(|b| b.unwrap().num_rows()).sum::(), 600); + + // A row group started by `try_decode` must be finished by it. + let result = decoder.try_decode().unwrap(); + let DecodeResult::Data(batch) = result else { + panic!("expected a batch, got {result:?}"); + }; + assert_eq!(batch.num_rows(), 300); + let err = decoder.try_next_reader().unwrap_err().to_string(); + assert!(err.contains("try_decode"), "{err}"); + let DecodeResult::Data(batch) = decoder.try_decode().unwrap() else { + panic!("expected a batch"); + }; + assert_eq!(batch.column(0).as_primitive::().value(0), 900); + + // At the boundary, `try_next_reader` works again. + let DecodeResult::Data(reader) = decoder.try_next_reader().unwrap() else { + panic!("expected a reader"); + }; + assert_eq!(reader.map(|b| b.unwrap().num_rows()).sum::(), 600); + assert!(matches!( + decoder.try_decode().unwrap(), + DecodeResult::Finished + )); +} + +/// A row group started by `try_next_reader` must be finished by it. +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_try_decode_in_a_row_group_of_try_next_reader() { + let mut decoder = Scan::default().batch_decoder(); + let DecodeResult::NeedsData(ranges) = decoder.try_next_reader().unwrap() else { + panic!("expected NeedsData"); + }; + let err = decoder.try_decode().unwrap_err().to_string(); + assert!(err.contains("try_next_reader"), "{err}"); + + let data = ranges.iter().map(fetch).collect(); + decoder.push_ranges(ranges, data).unwrap(); + let DecodeResult::Data(reader) = decoder.try_next_reader().unwrap() else { + panic!("expected a reader"); + }; + assert_eq!(reader.map(|b| b.unwrap().num_rows()).sum::(), 600); +} + +// --------------------------------------------------------------------------- +// Predicates +// --------------------------------------------------------------------------- + +/// Filtering and output overlap: the first batch of a row group is returned +/// before the pages of later windows are requested. +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_predicates_do_not_wait_for_the_row_group() { + let mut decoder = filtered(vec![PredicateSpec::new("b", Cmp::ModNotZero(2))]).batch_decoder(); + let mut requested = vec![]; + let batch = drive_with(&mut decoder, &TEST_FILE.data, |_, event| match event { + Event::Pushed(ranges) => { + requested.extend_from_slice(ranges); + ControlFlow::Continue(()) + } + Event::Batch(batch) => ControlFlow::Break(batch), + }) + .expect("expected a batch"); + assert_eq!(batch.num_rows(), 100); + let bytes: u64 = requested.iter().map(|r| r.end - r.start).sum(); + // Half the rows pass, so the first batch needs the predicate column for + // about 200 rows (plus one window, to know if more rows come) and the + // output columns for about 200 rows. + assert!(bytes * 2 < row_group_bytes(0), "{bytes}"); + let meta = metadata(true); + let page_index = meta.metadata().page_index_for_row_group(0); + // No page from row 300 on is requested. + for column in 0..meta.metadata().row_group(0).num_columns() { + for location in &page_index.page_locations(column).unwrap()[12..] { + let start = location.offset as u64; + assert!(requested.iter().all(|r| r.start != start), "{column}"); + } + } +} + +/// Resident bytes stay bounded with a selective predicate, including the +/// bytes of pages that were pushed ahead but that no row needs. +#[test] +fn test_predicates_release_bytes_pushed_ahead() { + let mut decoder = filtered(vec![PredicateSpec::new("a", Cmp::Ge(550))]).batch_decoder(); + // Push the first row group, one buffer per page. + let meta = metadata(true); + for column in 0..meta.metadata().row_group(0).num_columns() { + let ranges = page_ranges(0, column); + let data = ranges.iter().map(fetch).collect(); + decoder.push_ranges(ranges, data).unwrap(); + } + // Only rows 550.. of the first row group pass; the first batch holds + // them and 50 rows of the second row group. + let (row_group_1, _) = meta.metadata().row_group(1).column(0).byte_range(); + let first = drive_with(&mut decoder, &TEST_FILE.data, |_, event| match event { + Event::Pushed(ranges) => { + // Every byte of the first row group was pushed ahead and is + // kept until the decoder is done with it. + assert!(ranges.iter().all(|r| r.start >= row_group_1), "{ranges:?}"); + ControlFlow::Continue(()) + } + Event::Batch(batch) => ControlFlow::Break(batch), + }) + .expect("expected a batch"); + assert_eq!(first.num_rows(), 50); + // The first row group is done and every byte of it was released. + assert!(decoder.is_at_row_group_boundary()); + assert_eq!(decoder.buffered_bytes(), 0); +} + +// --------------------------------------------------------------------------- +// Configuration +// --------------------------------------------------------------------------- + +/// A batch size of 0 is an error with batch granularity. Row-group +/// granularity accepts it. +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_batch_size_zero_is_an_error() { + for predicates in [vec![], vec![PredicateSpec::new("a", Cmp::All)]] { + let scan = Scan { + batch_size: Some(0), + predicates, + ..Default::default() + }; + let err = scan + .builder() + .with_request_granularity(RequestGranularity::Batch) + .build() + .unwrap_err(); + assert_eq!( + err.to_string(), + "Parquet error: batch_size must be greater than 0 with RequestGranularity::Batch" + ); + scan.row_group_decoder(); + } +} + +/// `try_decode` returns the error of a predicate. +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_predicate_error_is_returned() { + let predicate = ArrowPredicateFn::new(columns(&["a"]), |_batch: RecordBatch| { + Err(arrow_schema::ArrowError::ComputeError(String::from( + "predicate failed", + ))) + }); + let mut decoder = Scan::default() + .builder() + .with_row_filter(RowFilter::new(vec![Box::new(predicate)])) + .with_request_granularity(RequestGranularity::Batch) + .build() + .unwrap(); + let file = 0..TEST_FILE.data.len() as u64; + decoder.push_range(file.clone(), fetch(&file)).unwrap(); + let err = decoder.try_decode().unwrap_err().to_string(); + assert!(err.contains("predicate failed"), "{err}"); +} + +/// A scan that reads a row group two times gives its batches two times. The +/// decoder requests the pages again for the second read. +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_row_group_read_two_times() { + for predicates in [vec![], vec![PredicateSpec::new("b", Cmp::ModNotZero(3))]] { + let scan = Scan { + batch_size: Some(100), + row_groups: Some(vec![1, 0, 1]), + predicates, + ..Default::default() + }; + let (row_group, _) = drive_file(scan.row_group_decoder(), &TEST_FILE.data); + let (batch, _) = drive_file(scan.batch_decoder(), &TEST_FILE.data); + assert_eq!(row_group, batch); + } +} + +/// A footer whose file row count is 0, but whose row groups have rows. The +/// batch size is clamped to 0, and `build` returns an error. +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_batch_size_zero_with_a_wrong_file_row_count() { + use parquet::file::metadata::{FileMetaData, ParquetMetaDataBuilder}; + let metadata = metadata(false); + let metadata = metadata.metadata(); + let file = metadata.file_metadata(); + let file = FileMetaData::new( + file.version(), + 0, + file.created_by().map(String::from), + file.key_value_metadata().cloned(), + file.schema_descr_ptr(), + file.column_orders().cloned(), + ); + let metadata = ParquetMetaDataBuilder::new(file) + .set_row_groups(metadata.row_groups().to_vec()) + .build(); + let err = ParquetPushDecoderBuilder::try_new_decoder(Arc::new(metadata)) + .unwrap() + .with_batch_size(1024) + .with_request_granularity(RequestGranularity::Batch) + .build() + .unwrap_err(); + assert_eq!( + err.to_string(), + "Parquet error: batch_size must be greater than 0 with RequestGranularity::Batch" + ); +} + +/// `with_batch_size` clamps the batch size to the file row count, so a file +/// without rows has a batch size of 0. That is not an error. +#[test] +#[cfg_attr(miri, ignore)] // Takes too long +fn test_batch_size_zero_without_rows() { + let schema = TEST_FILE.batch.schema(); + let mut buffer = vec![]; + let writer = ArrowWriter::try_new(&mut buffer, schema, None).unwrap(); + writer.close().unwrap(); + let file = Bytes::from(buffer); + let metadata = load_metadata(&file, PageIndexPolicy::Optional); + let decoder = ParquetPushDecoderBuilder::new_with_metadata(metadata) + .with_batch_size(1024) + .with_request_granularity(RequestGranularity::Batch) + .build() + .unwrap(); + let (batches, _) = drive_file(decoder, &file); + assert!(batches.is_empty()); +}