From f3bfa22f269480a167bedbfbc2ef3de36e8bb4c4 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Sat, 5 Dec 2026 01:06:36 -0600 Subject: [PATCH 1/6] chore: pin arrow-rs to 60.2.0 plus the unreleased push decoder changes (mechanical) EXPERIMENT. The Parquet scan in the next commits needs three push decoder changes that no arrow-rs release has: - `RequestGranularity::Batch` (https://github.com/apache/arrow-rs/pull/11238) - `ParquetPushDecoder::retain_row_groups` and `active_row_group` (https://github.com/apache/arrow-rs/pull/12456) - `active_row_group` under batch-granular `try_decode`, which needs both Patch every arrow crate to pydantic/arrow-rs at f37f753637572dde5602e5b28ac0544aed893259 (branch `claude/push-decoder-batch-granularity-60.2.0-v3`). That commit is the 60.2.0 release plus these three changes, so the pin adds no other unreleased arrow-rs change. `Cargo.lock` follows the new source. Mechanical: no DataFusion code changes. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 58 +++++++++++++++++++----------------------------------- Cargo.toml | 26 ++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 38 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 336d69d12547a..0ac820d39dd5d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -159,8 +159,7 @@ checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" [[package]] name = "arrow" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5ae4998cf4c111d52898382fbe81f37213b1a420677f480c55925eddfd46217" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-arith", "arrow-array", @@ -182,8 +181,7 @@ dependencies = [ [[package]] name = "arrow-arith" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5a50de298a7c0069ad475c66db65e731df547e85a9e1e7b6e7e0bf8f0c53725" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-array", "arrow-buffer", @@ -196,8 +194,7 @@ dependencies = [ [[package]] name = "arrow-array" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7a75080e8066219ed2d1e3b8fd2eb0b1a4b35d03b6fa87fb1035e93bd8dac95" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "ahash", "arrow-buffer", @@ -216,8 +213,7 @@ dependencies = [ [[package]] name = "arrow-avro" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee843c3d6581309f43323ddb6a6e4a3a5e03b7318874128e3ab6eb6fda631ea3" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-array", "arrow-buffer", @@ -240,8 +236,7 @@ dependencies = [ [[package]] name = "arrow-buffer" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c6bf2edf52662586214410c6030204215453eb86b8715037e8951326e173b19" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "bytes", "half", @@ -252,8 +247,7 @@ dependencies = [ [[package]] name = "arrow-cast" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcad6713dda348c245cd6ef36a578b4362c143c3a9dd829aa19e89f407c3e48b" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-array", "arrow-buffer", @@ -274,8 +268,7 @@ dependencies = [ [[package]] name = "arrow-cmp" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7e23e1092a61d7addfe57a69bf5cde7628b7b6685adea11731c19acdfd86695" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-array", "arrow-buffer", @@ -285,8 +278,7 @@ dependencies = [ [[package]] name = "arrow-csv" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9168dc86bba5375cb5a884f684d320148c6b556db18c0dace9f1d60ac543a1" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-array", "arrow-cast", @@ -300,8 +292,7 @@ dependencies = [ [[package]] name = "arrow-data" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a7becabdb9bf3fa058b55845c52e0f792bedc88fd0e28d6580c9730a902b60" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-buffer", "arrow-schema", @@ -313,8 +304,7 @@ dependencies = [ [[package]] name = "arrow-flight" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b91c84f077937c5f6dc351995091365e652afae67987253e25d013e3d08b758" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-arith", "arrow-array", @@ -339,8 +329,7 @@ dependencies = [ [[package]] name = "arrow-ipc" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6fe9198046b67abf4e3e3ef70de2d705099975bdc2a7d9f0661675a978a083" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-array", "arrow-buffer", @@ -355,8 +344,7 @@ dependencies = [ [[package]] name = "arrow-json" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19629d9e810280f0878738e2a361757b8ac53eae14336bb449e6879a68f71b9a" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-array", "arrow-buffer", @@ -380,8 +368,7 @@ dependencies = [ [[package]] name = "arrow-ord" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3935eb956aeb858ab67685e167e230facd7bf4b294cf003a72d85a80edac1d2" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-array", "arrow-buffer", @@ -394,8 +381,7 @@ dependencies = [ [[package]] name = "arrow-row" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79af8292302d7c3a1b64469a91afd33b34e7567365030098fdf4faa8130d43c3" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-array", "arrow-buffer", @@ -407,8 +393,7 @@ dependencies = [ [[package]] name = "arrow-schema" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e7574c4175cc731e0d26a8384bc25d455c5e220250988a772c1af843592444b" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "bitflags", "serde", @@ -419,8 +404,7 @@ dependencies = [ [[package]] name = "arrow-select" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d6a571e56e54b485b9f2d1dac4c3c34edcaffaa2668a23a7204108b66ef163d" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "ahash", "arrow-array", @@ -434,8 +418,7 @@ dependencies = [ [[package]] name = "arrow-string" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9eb6c979ef0582fd29189b66fa252e717ee32b41fd03158e801ac61005aefb9" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "arrow-array", "arrow-buffer", @@ -4709,8 +4692,7 @@ dependencies = [ [[package]] name = "parquet" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6701f0dd63f5ee23a0f1f2865ff76825c301759d6ab649e3e5686cc32d066957" +source = "git+https://github.com/pydantic/arrow-rs.git?rev=f37f753637572dde5602e5b28ac0544aed893259#f37f753637572dde5602e5b28ac0544aed893259" dependencies = [ "ahash", "arrow-array", @@ -5093,7 +5075,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6e4d69d0fa3e7f6f9cf6b53a0e83e4fc99ba3586f65ce166cff30bd13bb4ad2" dependencies = [ "heck", - "itertools 0.15.0", + "itertools 0.13.0", "log", "multimap", "petgraph", @@ -5112,7 +5094,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ad9c5423459fa2f729b8d9235fab810aa29628b171467744fc86d21460ad70d" dependencies = [ "anyhow", - "itertools 0.15.0", + "itertools 0.13.0", "proc-macro2", "quote", "syn 2.0.119", diff --git a/Cargo.toml b/Cargo.toml index 2d7acb9a0b2a5..5adaa0ab89a48 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -398,3 +398,29 @@ incremental = false [profile.ci-bench] inherits = "ci" opt-level = 1 + +# EXPERIMENT: pin arrow-rs to the 60.2.0 release plus the push decoder +# changes that no release has: apache/arrow-rs#11238 (batch-granular +# `ParquetPushDecoder`) and apache/arrow-rs#12456 (`retain_row_groups` and +# `active_row_group`). The commit is on pydantic/arrow-rs, branch +# claude/push-decoder-batch-granularity-60.2.0-v3. +# The patch covers every arrow crate, so that all of them come from one source. +[patch.crates-io] +arrow = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-arith = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-array = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-avro = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-buffer = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-cast = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-cmp = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-csv = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-data = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-flight = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-ipc = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-json = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-ord = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-row = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-schema = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-select = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +arrow-string = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } +parquet = { git = "https://github.com/pydantic/arrow-rs.git", rev = "f37f753637572dde5602e5b28ac0544aed893259" } From a229bb0511d5af4b1de6fad97cd4db2c2e91903f Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Sat, 5 Dec 2026 01:06:36 -0600 Subject: [PATCH 2/6] refactor: follow the Parquet push decoder with active_row_group and retain_row_groups The stream kept `rg_plan` in lock-step with the decoder by hand. At each row-group boundary it called `peek_next_row_group` to pop the row groups that the decoder skipped without a reader, and it popped the started row group itself. Runtime row-group pruning rebuilt the decoder with `into_builder` and `with_row_group_selections`. The decoder does not expose the selections of the row groups it has not started, so each `RgPlanEntry` kept a copy of its selection for that rebuild. A plan that trailed the decoder read a delivered row group again (https://github.com/apache/datafusion/issues/24352). The pinned arrow-rs has two methods that make the decoder the owner of this state (https://github.com/apache/arrow-rs/pull/12456): - `ParquetPushDecoder::active_row_group` names the row group that the decoder reads. After each decoder call, `follow_decoder` credits and pops `rg_plan` up to and including that row group. `rg_plan` thus holds only row groups that the decoder has not started. - `ParquetPushDecoder::retain_row_groups` drops queued row groups in place. It keeps the selection of each kept row group and the offset and limit budget, and it releases the buffered bytes of the dropped row groups. `prune_row_groups` calls it with the pruner and credits the dropped entries. Only the `RowFilter` toggle for fully matched row groups still rebuilds the decoder. It finds the entry of the next row group with `peek_next_row_group`, so only scans with a row filter pay for the peek. No behavior change. Removes `sync_rg_plan_to_decoder_frontier`, `advance_rg_plan_to` and its tests, `rebuild_decoder_at_boundary`, `RgPlanEntry::selection`, and the copies that the opener made for it. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 --- .../datasource-parquet/src/opener/mod.rs | 7 +- .../datasource-parquet/src/push_decoder.rs | 382 +++++++----------- datafusion/datasource-parquet/src/source.rs | 6 +- 3 files changed, 140 insertions(+), 255 deletions(-) diff --git a/datafusion/datasource-parquet/src/opener/mod.rs b/datafusion/datasource-parquet/src/opener/mod.rs index 1866b6ba81992..d0349bd65860d 100644 --- a/datafusion/datasource-parquet/src/opener/mod.rs +++ b/datafusion/datasource-parquet/src/opener/mod.rs @@ -1771,9 +1771,7 @@ impl RowGroupsPrunedParquetOpen { prepared_access_plan.row_groups.len(), ); // Move selections into the decoder, retaining only the metadata - // needed for pruning, filter toggles, and byte accounting. Only a - // pruning rebuild reads `RgPlanEntry::selection`, so a scan - // without a pruner does not hold a second copy of each selection. + // needed for filter toggles and byte accounting. let (selections, rg_plan): (Vec<_>, VecDeque) = prepared_access_plan .row_groups @@ -1784,9 +1782,6 @@ impl RowGroupsPrunedParquetOpen { rg_index, bytes: row_group_bytes(&rg_metadata[rg_index]), fully_matched: rg.fully_matched, - selection: pruner_eligible - .then(|| rg.selection.selection().cloned()) - .flatten(), }; (rg.selection, entry) }) diff --git a/datafusion/datasource-parquet/src/push_decoder.rs b/datafusion/datasource-parquet/src/push_decoder.rs index 3d70cef744328..8998afe3e86bc 100644 --- a/datafusion/datasource-parquet/src/push_decoder.rs +++ b/datafusion/datasource-parquet/src/push_decoder.rs @@ -13,16 +13,15 @@ //! **single** [`ParquetPushDecoder`] plus an [`RgPlanEntry`] queue //! (`rg_plan`) and uses arrow-rs's [`ParquetRecordBatchReader`] iterator //! to pause at row-group boundaries. At each boundary the optional -//! [`RowGroupPruner`] is consulted; row groups it proves unwinnable are -//! dropped from the head of `rg_plan` and the decoder is rebuilt via -//! [`ParquetPushDecoder::into_builder`] + -//! [`ParquetPushDecoderBuilder::with_row_group_selections`] so the skipped RGs are -//! bypassed entirely — no decode, no row-filter eval. +//! [`RowGroupPruner`] is consulted, and +//! [`ParquetPushDecoder::retain_row_groups`] drops the row groups it proves +//! unwinnable from the decoder's queue, so they are bypassed entirely: no +//! fetch, no decode, no row-filter eval. //! //! The opener constructs both halves and hands the state off to //! [`PushDecoderStreamState::into_stream`] for consumption. -use std::collections::VecDeque; +use std::collections::{HashSet, VecDeque}; use std::sync::Arc; use arrow::array::{RecordBatch, UInt32Array}; @@ -35,8 +34,7 @@ use parquet::DecodeResult; use parquet::arrow::ProjectionMask; use parquet::arrow::arrow_reader::metrics::ArrowReaderMetrics; use parquet::arrow::arrow_reader::{ - ArrowReaderMetadata, ParquetRecordBatchReader, RowFilter, RowSelection, - RowSelectionPolicy, + ArrowReaderMetadata, ParquetRecordBatchReader, RowFilter, RowSelectionPolicy, }; use parquet::arrow::async_reader::AsyncFileReader; use parquet::arrow::push_decoder::{ @@ -44,7 +42,7 @@ use parquet::arrow::push_decoder::{ }; use parquet::file::metadata::ParquetMetaData; -use datafusion_common::{DataFusionError, Result, internal_err}; +use datafusion_common::{DataFusionError, Result}; use datafusion_execution::memory_pool::MemoryReservation; use datafusion_physical_expr::expressions::DynamicFilterTracking; use datafusion_physical_expr_common::physical_expr::PhysicalExpr; @@ -62,8 +60,8 @@ use crate::row_group_filter::RowGroupPruningStatistics; /// Shared options applied to the [`ParquetPushDecoderBuilder`] for a file /// scan, and to any later rebuilds performed via -/// [`ParquetPushDecoder::into_builder`] at row-group boundaries (e.g. when -/// the [`RowGroupPruner`] drops subsequent row groups). +/// [`ParquetPushDecoder::into_builder`] at row-group boundaries (the +/// `RowFilter` toggle for fully matched row groups). pub(crate) struct DecoderBuilderConfig<'a> { /// Projection mask installed on every decoder in the scan. Sourced from /// the file's [`DecoderProjection`]. @@ -111,11 +109,6 @@ pub(crate) struct RgPlanEntry { /// /// [`ParquetFileMetrics`]: crate::ParquetFileMetrics pub(crate) bytes: u64, - /// The row-group-local selection the decoder was built with for this RG. - /// A runtime-pruning rebuild passes it back, because the decoder does not - /// expose the selections of the row groups it has not started. `None` - /// when the scan has no runtime pruner, because nothing reads it then. - pub(crate) selection: Option, } /// The initial per-file decoder state the opener builds and hands off to the @@ -128,8 +121,7 @@ pub(crate) struct InitialDecoderState { pub(crate) decoder: ParquetPushDecoder, /// The per-row-group plan, in the physical scan order the decoder reads. pub(crate) rg_plan: VecDeque, - /// Whether the scan builds a runtime row-group pruner. When it does not, - /// the `rg_plan` entries hold no selections. + /// Whether the scan builds a runtime row-group pruner. pub(crate) pruner_eligible: bool, /// Whether the freshly built decoder carries a real (non-empty) /// [`RowFilter`]. `false` when the first row group is fully matched and @@ -296,10 +288,8 @@ pub(crate) struct PushDecoderStreamState { /// (typically the threshold expression a `TopK` `SortExec` pushed down), /// we re-evaluate that predicate against the next pending RG's /// statistics and drop RGs the current threshold proves cannot - /// contribute. The decoder is rebuilt via - /// [`ParquetPushDecoder::into_builder`] + - /// [`ParquetPushDecoderBuilder::with_row_group_selections`] so the skipped RGs are - /// bypassed entirely. `None` when the scan has no watching dynamic + /// contribute, with [`ParquetPushDecoder::retain_row_groups`]. `None` + /// when the scan has no watching dynamic /// predicate or only one row group remains. pub(crate) row_group_pruner: Option, /// Count of row groups skipped at runtime by [`Self::row_group_pruner`]. @@ -492,53 +482,18 @@ impl PushDecoderStreamState { } } - // Step 2: when the decoder is sitting on a row-group boundary, - // scan the entire `rg_plan` and drop every RG the pruner proves - // cannot contribute — head, interior, and tail alike. Evaluating - // per-RG stats against the cached `PruningPredicate` is cheap; - // the expensive part is the `into_builder` rebuild, so we do at - // most one rebuild per boundary regardless of how many RGs were - // dropped. Buffered bytes for already-fetched RGs carry across - // the rebuild. - // - // `into_builder` errors out mid-row-group, so we gate the prune - // pass on `is_at_row_group_boundary()`. When the decoder is - // mid-RG (e.g. byte ranges have been pushed but no reader has - // been handed back yet), step 3 drives it forward and we get - // another chance at the next boundary — the pruner is stateful - // and idempotent, so deferring loses nothing. - let at_boundary = self - .decoder - .as_ref() - .expect("decoder present") - .is_at_row_group_boundary(); - // Keep `rg_plan.front()` aligned with the row group the decoder will - // actually emit next: arrow-rs silently finishes row groups whose - // post-predicate selection is empty without handing back a reader, so - // without this sync `rg_plan` trails the decoder by one and a rebuild - // either re-reads an already-delivered row group (#24352) or toggles - // the per-RG filter for the wrong row group. Both the runtime pruner - // and the per-RG `RowFilter` toggle consume `rg_plan`, so sync when - // either is active; gating avoids the O(remaining row groups) cost of - // `peek_next_row_group()` on ordinary scans that never rebuild. - if at_boundary - && (self.row_group_pruner.is_some() || self.row_filter_context.is_some()) - && let Err(e) = self.sync_rg_plan_to_decoder_frontier() - { - return Some((Err(e), self)); - } - if at_boundary && !self.rg_plan.is_empty() { - let pruned_count = self.prune_boundary_row_groups(); - match self.rebuild_decoder_at_boundary(pruned_count) { - Ok(true) => return None, - Ok(false) => {} - Err(e) => return Some((Err(e), self)), - } + // Step 2: row-group boundary work (pruning, filter toggle). + match self.handle_row_group_boundary() { + Ok(true) => return None, + Ok(false) => {} + Err(e) => return Some((Err(e), self)), } // Step 3: drive the decoder. let decoder = self.decoder.as_mut().expect("decoder present"); - match decoder.try_next_reader() { + let decoded = decoder.try_next_reader(); + self.follow_decoder(); + match decoded { Ok(DecodeResult::NeedsData(ranges)) => { // I/O, not compute. timer.stop(); @@ -563,21 +518,12 @@ impl PushDecoderStreamState { } } Ok(DecodeResult::Data(reader)) => { - // Pop the RG this reader is for (we already filtered - // pruned ones in step 2, so `rg_plan.front()` is the RG - // the decoder is about to read). - // - // Its bytes are credited here rather than once the reader - // is drained: the decoder has already fetched them, and a - // reader that is abandoned mid-row-group (`LIMIT`, early - // stop) would otherwise never credit them until the file - // closes. - if let Some(entry) = self.rg_plan.pop_front() { - self.byte_progress.credit(entry.bytes); - } self.active_reader = Some(reader); } - Ok(DecodeResult::Finished) => return None, + Ok(DecodeResult::Finished) => { + self.finish_row_groups(); + return None; + } Err(e) => { return Some((Err(DataFusionError::from(e)), self)); } @@ -585,153 +531,145 @@ impl PushDecoderStreamState { } } - /// Keep `rg_plan.front()` aligned with the row group the decoder will emit - /// next. `try_next_reader` silently finishes row groups whose post-predicate - /// selection is empty (no reader handed back) — e.g. page-index pruning - /// removed every page — which would otherwise leave `rg_plan` trailing the - /// decoder by one: a later prune/rebuild would then re-include an - /// already-delivered row group (#24352) or toggle the filter for the wrong RG. - /// Row-group-local selections keep selections and match status aligned when - /// preparing or reordering the plan, but do not prevent this decoder-side - /// advancement, so frontier synchronization is still required. - fn sync_rg_plan_to_decoder_frontier(&mut self) -> Result<()> { - match self + /// Row-group boundary work. Returns `Ok(true)` when the stream should + /// finish. + /// + /// At a row-group boundary, drop every queued row group that the pruner + /// proves cannot contribute, then toggle the per-row `RowFilter` for the + /// next row group. The toggle rebuilds the decoder, and + /// [`ParquetPushDecoder::into_builder`] errors mid-row-group. The pruner + /// is stateful and idempotent, so waiting for the next boundary loses + /// nothing. + fn handle_row_group_boundary(&mut self) -> Result { + let at_boundary = self .decoder .as_ref() .expect("decoder present") - .peek_next_row_group() - .map_err(DataFusionError::from)? - { - Some(actual) => Self::advance_rg_plan_to( - &mut self.rg_plan, - actual, - &mut self.byte_progress, - )?, - // Decoder has nothing left to emit — drain our plan so the stream - // finishes cleanly, crediting what it will now never read. - None => { - for entry in self.rg_plan.drain(..) { - self.byte_progress.credit(entry.bytes); - } - } + .is_at_row_group_boundary(); + if !at_boundary || self.rg_plan.is_empty() { + return Ok(false); } - Ok(()) + self.prune_row_groups()?; + if self.rg_plan.is_empty() { + return Ok(true); + } + self.toggle_row_filter()?; + Ok(false) } - /// Pop entries off `rg_plan` until its front is `target`. + /// Credit the row groups that the decoder is done with, after each call + /// that can start a row group: the row groups before its active row group, + /// which it skipped without a reader, and the active one. /// - /// `target` is the RG the decoder will emit next and must still be in the - /// plan. A missing `target` means the decoder's frontier and `rg_plan` have - /// diverged; we surface that as an internal error rather than silently - /// draining the plan, which would truncate the scan. Kept free-standing on - /// `rg_plan` (rather than `&mut self`) so the pop/guard logic is - /// unit-testable without constructing a full stream state. - fn advance_rg_plan_to( - rg_plan: &mut VecDeque, - target: usize, - byte_progress: &mut ByteProgress, - ) -> Result<()> { - while let Some(front) = rg_plan.front() { - if front.rg_index == target { - return Ok(()); - } - // Popped here means arrow-rs finished this row group without - // handing back a reader, so the scan is done with its bytes. - let popped = rg_plan.pop_front().expect("front present"); - byte_progress.credit(popped.bytes); + /// `rg_plan` then holds only row groups that the decoder has not started: + /// the row groups that [`ParquetPushDecoder::retain_row_groups`] can drop. + fn follow_decoder(&mut self) { + let Some(active) = self + .decoder + .as_ref() + .expect("decoder present") + .active_row_group() + else { + return; + }; + let Some(idx) = self.rg_plan.iter().position(|e| e.rg_index == active) else { + return; + }; + for entry in self.rg_plan.drain(..=idx) { + self.byte_progress.credit(entry.bytes); } - internal_err!( - "push decoder frontier RG {target} is not in rg_plan; \ - decoder and plan have diverged" - ) } - /// Drop every `rg_plan` entry the dynamic pruner proves cannot contribute, - /// returning how many were pruned. The single decoder rebuild that acts on - /// the survivors is left to the caller (at most one rebuild per boundary). - fn prune_boundary_row_groups(&mut self) -> usize { + /// Credit the row groups that the decoder will not read: it has finished. + fn finish_row_groups(&mut self) { + for entry in self.rg_plan.drain(..) { + self.byte_progress.credit(entry.bytes); + } + } + + /// The row group the decoder reads next, if it has not started it. + fn next_row_group(&self) -> Result> { + let next = self + .decoder + .as_ref() + .expect("decoder present") + .peek_next_row_group()?; + Ok(next.and_then(|next| self.rg_plan.iter().find(|e| e.rg_index == next))) + } + + /// Drop the queued row groups that the dynamic pruner proves cannot + /// contribute, and return how many were dropped. + fn prune_row_groups(&mut self) -> Result { let Some(pruner) = self.row_group_pruner.as_mut() else { - return 0; + return Ok(0); }; - let mut pruned_count = 0usize; - let mut kept = VecDeque::with_capacity(self.rg_plan.len()); - while let Some(entry) = self.rg_plan.pop_front() { - if pruner.should_prune(&[entry.rg_index]) { - pruned_count += 1; - self.row_groups_pruned_dynamic.add(1); + let mut pruned = HashSet::new(); + let dropped = self + .decoder + .as_mut() + .expect("decoder present") + .retain_row_groups(|queued| { + let row_group = queued.row_group_index(); + let prune = pruner.should_prune(&[row_group]); + if prune { + pruned.insert(row_group); + } + !prune + })?; + if dropped == 0 { + return Ok(0); + } + self.row_groups_pruned_dynamic.add(dropped); + let byte_progress = &mut self.byte_progress; + self.rg_plan.retain(|entry| { + let keep = !pruned.contains(&entry.rg_index); + if !keep { // The scan is done with this row group's bytes. - self.byte_progress.credit(entry.bytes); - } else { - kept.push_back(entry); + byte_progress.credit(entry.bytes); } - } - self.rg_plan = kept; - pruned_count + keep + }); + Ok(dropped) } - /// At a row-group boundary, rebuild the decoder so it reads only the - /// surviving `rg_plan` and toggle the per-row `RowFilter` for the upcoming - /// RG. Rebuilds only when something changed (`pruned_count > 0` or the - /// filter status flips), doing at most one `into_builder` rebuild per - /// boundary. Returns `Ok(true)` when the plan is now empty (the stream - /// should finish). - fn rebuild_decoder_at_boundary( - &mut self, - pruned_count: usize, - ) -> Result { + /// Install the per-row `RowFilter` for the next row group, or suppress it + /// if the row group is fully matched, by rebuilding the decoder. Returns + /// whether it rebuilt the decoder. + fn toggle_row_filter(&mut self) -> Result { // `desired_filter` is `Some(true)` when the next RG needs a real // filter, `Some(false)` when it is fully-matched (filter is a no-op, so // we suppress it), and `None` when there is no pushdown predicate at // all (toggling is meaningless). - let desired_filter: Option = self - .row_filter_context - .as_ref() - .and_then(|_| self.rg_plan.front().map(|e| !e.fully_matched)); - let filter_needs_toggle = - desired_filter.is_some_and(|want| want != self.filter_installed); - - if pruned_count == 0 && !filter_needs_toggle { + let desired_filter: Option = match self.row_filter_context { + Some(_) => self.next_row_group()?.map(|e| !e.fully_matched), + None => None, + }; + let Some(want_filter) = + desired_filter.filter(|&want| want != self.filter_installed) + else { return Ok(false); - } - if self.rg_plan.is_empty() { - return Ok(true); - } + }; let decoder = self.decoder.take().expect("decoder present"); let mut builder = decoder.into_builder().map_err(DataFusionError::from)?; - // Filter-only rebuilds preserve the decoder's remaining selections. - // A pruning rebuild replaces the row-group list, so it passes each - // survivor's selection back. Rebuilds happen only at a row-group - // boundary, so no survivor has started and each selection is intact. - if pruned_count > 0 { - let selections = self - .rg_plan - .iter() - .map(|e| RowGroupSelection::new(e.rg_index, e.selection.clone())) - .collect(); - builder = builder.with_row_group_selections(selections); - } - if filter_needs_toggle { - let want_filter = desired_filter.expect("filter_needs_toggle ⇒ desired Some"); - if want_filter { - let ctx = self - .row_filter_context - .as_ref() - .expect("filter_needs_toggle ⇒ context set"); - builder = builder.with_row_filter(ctx.build_row_filter()); - if let Some(cap) = ctx.max_predicate_cache_size { - builder = builder.with_max_predicate_cache_size(cap); - } - self.filter_installed = true; - } else { - // Skip per-row filtering for the upcoming fully-matched RG. - builder = builder.with_row_filter(RowFilter::new(vec![])); - self.filter_installed = false; - self.row_filter_skipped_fully_matched.add_one(); + if want_filter { + let ctx = self + .row_filter_context + .as_ref() + .expect("a desired filter implies a context"); + builder = builder.with_row_filter(ctx.build_row_filter()); + if let Some(cap) = ctx.max_predicate_cache_size { + builder = builder.with_max_predicate_cache_size(cap); } + self.filter_installed = true; + } else { + // Skip per-row filtering for the upcoming fully-matched RG. + builder = builder.with_row_filter(RowFilter::new(vec![])); + self.filter_installed = false; + self.row_filter_skipped_fully_matched.add_one(); } self.decoder = Some(builder.build().map_err(DataFusionError::from)?); - Ok(false) + Ok(true) } /// Copies metrics from ArrowReaderMetrics (the metrics collected by the @@ -1038,52 +976,4 @@ mod tests { assert!(!pruner.should_prune(&[1])); assert!(!pruner.should_prune(&[2])); } - - /// A plan whose row group `i` is `100 * (i + 1)` bytes. - fn rg_plan(indexes: impl IntoIterator) -> VecDeque { - indexes - .into_iter() - .map(|rg_index| RgPlanEntry { - rg_index, - fully_matched: false, - bytes: 100 * (rg_index as u64 + 1), - selection: None, - }) - .collect() - } - - #[test] - fn advance_rg_plan_to_pops_up_to_target() { - let mut plan = rg_plan([0usize, 1, 2, 3]); - let bytes_processed = Count::new(); - let mut byte_progress = ByteProgress::new(1_000, Count::clone(&bytes_processed)); - - PushDecoderStreamState::advance_rg_plan_to(&mut plan, 2, &mut byte_progress) - .unwrap(); - - assert_eq!( - plan.iter().map(|e| e.rg_index).collect::>(), - vec![2, 3], - "must pop the entries before `target` and stop at it", - ); - assert_eq!( - bytes_processed.value(), - 300, - "row groups finished without a reader must still credit their bytes", - ); - } - - #[test] - fn advance_rg_plan_to_errors_when_target_absent() { - let mut plan = rg_plan([0usize, 1, 2]); - let mut byte_progress = ByteProgress::new(1_000, Count::new()); - - let err = - PushDecoderStreamState::advance_rg_plan_to(&mut plan, 5, &mut byte_progress) - .expect_err("a target absent from the plan must be an internal error"); - assert!( - err.to_string().contains("diverged"), - "expected a divergence internal error, got: {err}", - ); - } } diff --git a/datafusion/datasource-parquet/src/source.rs b/datafusion/datasource-parquet/src/source.rs index 6f4af5561cb9f..09083cb19de24 100644 --- a/datafusion/datasource-parquet/src/source.rs +++ b/datafusion/datasource-parquet/src/source.rs @@ -791,9 +791,9 @@ impl FileSource for ParquetSource { // predicate is dynamic (e.g. a TopK threshold expression), // the parquet opener will pause the single decoder at row // group boundaries and consult `RowGroupPruner` to drop - // RGs the current threshold proves unwinnable, rebuilding - // the decoder via `into_builder().with_row_group_selections(...)` to - // skip them. The actual pruning count appears as + // RGs the current threshold proves unwinnable, with + // `ParquetPushDecoder::retain_row_groups`. The actual pruning + // count appears as // `row_groups_pruned_dynamic_filter` in EXPLAIN ANALYZE. // We use `contains_dynamic_filter()` (matches both `Watching` // and `AllComplete`) rather than the stricter `Watching(_)` From f0950fca5deb4e6785de080d7cfc29110a525a1a Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Sat, 5 Dec 2026 01:06:36 -0600 Subject: [PATCH 3/6] feat: add the datafusion.execution.parquet.read_ahead_bytes option Parquet read-ahead needs a user-facing switch and a window size. The option must exist in `ParquetOptions` and its protobuf form before the scan can read it. Add `ParquetOptions::read_ahead_bytes` (`Option`, default unset) with its documentation, and carry it through the protobuf conversions. The option has no effect in this commit. The next commit reads it. `ParquetOptions` has public fields, so an exhaustive struct literal must add the new one. The upgrade guide gets an entry for that. Mechanical parts: `datafusion_common.proto` field 44, the generated `prost.rs` and `pbjson.rs` files, `configs.md`, and the `information_schema.slt` listing. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 --- datafusion/common/src/config.rs | 25 ++++++++++++++++++ .../common/src/file_options/parquet_writer.rs | 3 +++ .../datasource-parquet/src/file_format.rs | 3 +++ .../proto/datafusion_common.proto | 4 +++ datafusion/proto-common/src/from_proto/mod.rs | 5 ++++ .../proto-common/src/generated/pbjson.rs | 26 ++++++++++++++++++- .../proto-common/src/generated/prost.rs | 7 +++++ datafusion/proto-common/src/to_proto/mod.rs | 1 + datafusion/proto-models/src/from_proto.rs | 9 +++++++ .../src/generated/datafusion_proto_common.rs | 7 +++++ .../test_files/information_schema.slt | 2 ++ .../library-user-guide/upgrading/index.md | 9 +++++++ docs/source/user-guide/configs.md | 1 + 13 files changed, 101 insertions(+), 1 deletion(-) diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs index d3410dc1da8e3..da12ca634eb1a 100644 --- a/datafusion/common/src/config.rs +++ b/datafusion/common/src/config.rs @@ -1395,6 +1395,31 @@ config_namespace! { /// parquet reader setting. 0 means no caching. pub max_predicate_cache_size: Option, default = None + /// (reading) If set, fetch Parquet data ahead of the decoder, in the + /// order the decoder reads it, up to this many bytes for each file a + /// partition stream reads. If unset, the reader fetches one row group + /// at a time, when the decoder needs it. + /// + /// The window bounds the bytes in flight plus the fetched bytes the + /// decoder still holds, including the gaps between ranges that one + /// request reads through. Bytes the decoder needs are fetched even if + /// the window is full. Read-ahead fetches small row groups whole and + /// large ones in parts, with several requests in flight. + /// + /// The throughput of a partition stream is at most about this window + /// divided by the storage latency. Thus, windows below a few MiB are + /// slow on object storage. + /// + /// With read-ahead, the reader decodes a batch at a time. Scans that + /// return the rows of each row group in reverse order (`reverse_rows`) + /// decode a row group at a time, and read ahead the next row groups. + /// + /// Read-ahead also fetches ranges that a pushed-down filter can make + /// unnecessary. In addition to this window, read-ahead takes only the + /// memory that the memory pool grants. Bytes the decoder needs are + /// fetched even if the pool is full. + pub read_ahead_bytes: Option, default = None + /// Maximum number of input values in an `IN (...)` list eligible for /// min/max pruning. Lists above this cap, or a cap of 0, skip this /// rewrite; other predicates and Bloom-filter pruning remain available. diff --git a/datafusion/common/src/file_options/parquet_writer.rs b/datafusion/common/src/file_options/parquet_writer.rs index e6cd9fd800313..6d6fa3e7faf4d 100644 --- a/datafusion/common/src/file_options/parquet_writer.rs +++ b/datafusion/common/src/file_options/parquet_writer.rs @@ -237,6 +237,7 @@ impl ParquetOptions { coerce_int96_tz: _, // not used for writer props skip_arrow_metadata: _, max_predicate_cache_size: _, + read_ahead_bytes: _, max_in_list_size: _, enable_rle_to_dictionary: _, dictionary_read_max_distinct_values: _, @@ -406,6 +407,7 @@ mod tests { coerce_int96: None, coerce_int96_tz: None, max_predicate_cache_size: defaults.max_predicate_cache_size, + read_ahead_bytes: defaults.read_ahead_bytes, content_defined_chunking: defaults.content_defined_chunking.clone(), enable_rle_to_dictionary: defaults.enable_rle_to_dictionary, dictionary_read_max_distinct_values: defaults @@ -538,6 +540,7 @@ mod tests { bloom_filter_on_read: global_options_defaults.bloom_filter_on_read, max_predicate_cache_size: global_options_defaults .max_predicate_cache_size, + read_ahead_bytes: global_options_defaults.read_ahead_bytes, schema_force_view_types: global_options_defaults.schema_force_view_types, binary_as_string: global_options_defaults.binary_as_string, skip_arrow_metadata: global_options_defaults.skip_arrow_metadata, diff --git a/datafusion/datasource-parquet/src/file_format.rs b/datafusion/datasource-parquet/src/file_format.rs index 0305eb1ab45dc..62199b4d8917b 100644 --- a/datafusion/datasource-parquet/src/file_format.rs +++ b/datafusion/datasource-parquet/src/file_format.rs @@ -909,6 +909,9 @@ impl From<&ParquetFormatFactory> for protobuf::TableParquetOptions { max_predicate_cache_size_opt: global_options.global.max_predicate_cache_size.map(|size| { parquet_options::MaxPredicateCacheSizeOpt::MaxPredicateCacheSize(size as u64) }), + read_ahead_bytes_opt: global_options.global.read_ahead_bytes.map(|size| { + parquet_options::ReadAheadBytesOpt::ReadAheadBytes(size as u64) + }), max_row_group_bytes_opt: global_options.global.max_row_group_bytes.map(|size| { parquet_options::MaxRowGroupBytesOpt::MaxRowGroupBytes(size.get() as u64) }), diff --git a/datafusion/proto-common/proto/datafusion_common.proto b/datafusion/proto-common/proto/datafusion_common.proto index 9685d9f93f6b9..0a6b16d5e5988 100644 --- a/datafusion/proto-common/proto/datafusion_common.proto +++ b/datafusion/proto-common/proto/datafusion_common.proto @@ -633,6 +633,10 @@ message ParquetOptions { uint64 max_predicate_cache_size = 33; } + oneof read_ahead_bytes_opt { + uint64 read_ahead_bytes = 44; + } + oneof max_row_group_bytes_opt { uint64 max_row_group_bytes = 37; } diff --git a/datafusion/proto-common/src/from_proto/mod.rs b/datafusion/proto-common/src/from_proto/mod.rs index 105529169672f..b15efc93ffbad 100644 --- a/datafusion/proto-common/src/from_proto/mod.rs +++ b/datafusion/proto-common/src/from_proto/mod.rs @@ -1329,6 +1329,11 @@ impl TryFrom<&protobuf::ParquetOptions> for ParquetOptions { to_usize(v, "max_predicate_cache_size") } }).transpose()?, + read_ahead_bytes: value.read_ahead_bytes_opt.map(|opt| match opt { + protobuf::parquet_options::ReadAheadBytesOpt::ReadAheadBytes(v) => { + to_usize(v, "read_ahead_bytes") + } + }).transpose()?, max_row_group_bytes: value.max_row_group_bytes_opt.map(|opt| match opt { protobuf::parquet_options::MaxRowGroupBytesOpt::MaxRowGroupBytes(v) => { MaxRowGroupBytes::try_new(to_usize(v, "max_row_group_bytes")?) diff --git a/datafusion/proto-common/src/generated/pbjson.rs b/datafusion/proto-common/src/generated/pbjson.rs index 4dad6d2b118df..dc845e0e10cb9 100644 --- a/datafusion/proto-common/src/generated/pbjson.rs +++ b/datafusion/proto-common/src/generated/pbjson.rs @@ -6584,6 +6584,9 @@ impl serde::Serialize for ParquetOptions { if self.max_predicate_cache_size_opt.is_some() { len += 1; } + if self.read_ahead_bytes_opt.is_some() { + len += 1; + } if self.max_row_group_bytes_opt.is_some() { len += 1; } @@ -6780,6 +6783,15 @@ impl serde::Serialize for ParquetOptions { } } } + if let Some(v) = self.read_ahead_bytes_opt.as_ref() { + match v { + parquet_options::ReadAheadBytesOpt::ReadAheadBytes(v) => { + #[allow(clippy::needless_borrow)] + #[allow(clippy::needless_borrows_for_generic_args)] + struct_ser.serialize_field("readAheadBytes", ToString::to_string(&v).as_str())?; + } + } + } if let Some(v) = self.max_row_group_bytes_opt.as_ref() { match v { parquet_options::MaxRowGroupBytesOpt::MaxRowGroupBytes(v) => { @@ -6881,6 +6893,8 @@ impl<'de> serde::Deserialize<'de> for ParquetOptions { "coerceInt96", "max_predicate_cache_size", "maxPredicateCacheSize", + "read_ahead_bytes", + "readAheadBytes", "max_row_group_bytes", "maxRowGroupBytes", "coerce_int96_tz", @@ -6928,6 +6942,7 @@ impl<'de> serde::Deserialize<'de> for ParquetOptions { BloomFilterNdv, CoerceInt96, MaxPredicateCacheSize, + ReadAheadBytes, MaxRowGroupBytes, CoerceInt96Tz, } @@ -6990,6 +7005,7 @@ impl<'de> serde::Deserialize<'de> for ParquetOptions { "bloomFilterNdv" | "bloom_filter_ndv" => Ok(GeneratedField::BloomFilterNdv), "coerceInt96" | "coerce_int96" => Ok(GeneratedField::CoerceInt96), "maxPredicateCacheSize" | "max_predicate_cache_size" => Ok(GeneratedField::MaxPredicateCacheSize), + "readAheadBytes" | "read_ahead_bytes" => Ok(GeneratedField::ReadAheadBytes), "maxRowGroupBytes" | "max_row_group_bytes" => Ok(GeneratedField::MaxRowGroupBytes), "coerceInt96Tz" | "coerce_int96_tz" => Ok(GeneratedField::CoerceInt96Tz), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), @@ -7050,6 +7066,7 @@ impl<'de> serde::Deserialize<'de> for ParquetOptions { let mut bloom_filter_ndv_opt__ = None; let mut coerce_int96_opt__ = None; let mut max_predicate_cache_size_opt__ = None; + let mut read_ahead_bytes_opt__ = None; let mut max_row_group_bytes_opt__ = None; let mut coerce_int96_tz_opt__ = None; while let Some(k) = map_.next_key()? { @@ -7224,7 +7241,7 @@ impl<'de> serde::Deserialize<'de> for ParquetOptions { if dictionary_read_max_distinct_values__.is_some() { return Err(serde::de::Error::duplicate_field("dictionaryReadMaxDistinctValues")); } - dictionary_read_max_distinct_values__ = + dictionary_read_max_distinct_values__ = map_.next_value::<::std::option::Option<::pbjson::private::NumberDeserialize<_>>>()?.map(|x| x.0) ; } @@ -7306,6 +7323,12 @@ impl<'de> serde::Deserialize<'de> for ParquetOptions { } max_predicate_cache_size_opt__ = map_.next_value::<::std::option::Option<::pbjson::private::NumberDeserialize<_>>>()?.map(|x| parquet_options::MaxPredicateCacheSizeOpt::MaxPredicateCacheSize(x.0)); } + GeneratedField::ReadAheadBytes => { + if read_ahead_bytes_opt__.is_some() { + return Err(serde::de::Error::duplicate_field("readAheadBytes")); + } + read_ahead_bytes_opt__ = map_.next_value::<::std::option::Option<::pbjson::private::NumberDeserialize<_>>>()?.map(|x| parquet_options::ReadAheadBytesOpt::ReadAheadBytes(x.0)); + } GeneratedField::MaxRowGroupBytes => { if max_row_group_bytes_opt__.is_some() { return Err(serde::de::Error::duplicate_field("maxRowGroupBytes")); @@ -7360,6 +7383,7 @@ impl<'de> serde::Deserialize<'de> for ParquetOptions { bloom_filter_ndv_opt: bloom_filter_ndv_opt__, coerce_int96_opt: coerce_int96_opt__, max_predicate_cache_size_opt: max_predicate_cache_size_opt__, + read_ahead_bytes_opt: read_ahead_bytes_opt__, max_row_group_bytes_opt: max_row_group_bytes_opt__, coerce_int96_tz_opt: coerce_int96_tz_opt__, }) diff --git a/datafusion/proto-common/src/generated/prost.rs b/datafusion/proto-common/src/generated/prost.rs index a316ee0b16071..2a8f74dabb809 100644 --- a/datafusion/proto-common/src/generated/prost.rs +++ b/datafusion/proto-common/src/generated/prost.rs @@ -931,6 +931,8 @@ pub struct ParquetOptions { pub max_predicate_cache_size_opt: ::core::option::Option< parquet_options::MaxPredicateCacheSizeOpt, >, + #[prost(oneof = "parquet_options::ReadAheadBytesOpt", tags = "44")] + pub read_ahead_bytes_opt: ::core::option::Option, #[prost(oneof = "parquet_options::MaxRowGroupBytesOpt", tags = "37")] pub max_row_group_bytes_opt: ::core::option::Option< parquet_options::MaxRowGroupBytesOpt, @@ -1000,6 +1002,11 @@ pub mod parquet_options { MaxPredicateCacheSize(u64), } #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Oneof)] + pub enum ReadAheadBytesOpt { + #[prost(uint64, tag = "44")] + ReadAheadBytes(u64), + } + #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Oneof)] pub enum MaxRowGroupBytesOpt { #[prost(uint64, tag = "37")] MaxRowGroupBytes(u64), diff --git a/datafusion/proto-common/src/to_proto/mod.rs b/datafusion/proto-common/src/to_proto/mod.rs index 1c5fce1733203..be9f69810481b 100644 --- a/datafusion/proto-common/src/to_proto/mod.rs +++ b/datafusion/proto-common/src/to_proto/mod.rs @@ -958,6 +958,7 @@ impl TryFrom<&ParquetOptions> for protobuf::ParquetOptions { coerce_int96_opt: value.coerce_int96.map(|v| protobuf::parquet_options::CoerceInt96Opt::CoerceInt96(v.to_string())), coerce_int96_tz_opt: value.coerce_int96_tz.as_ref().map(|v| protobuf::parquet_options::CoerceInt96TzOpt::CoerceInt96Tz(v.to_string())), max_predicate_cache_size_opt: value.max_predicate_cache_size.map(|v| protobuf::parquet_options::MaxPredicateCacheSizeOpt::MaxPredicateCacheSize(v as u64)), + read_ahead_bytes_opt: value.read_ahead_bytes.map(|v| protobuf::parquet_options::ReadAheadBytesOpt::ReadAheadBytes(v as u64)), max_row_group_bytes_opt: value.max_row_group_bytes.map(|v| protobuf::parquet_options::MaxRowGroupBytesOpt::MaxRowGroupBytes(v.get() as u64)), content_defined_chunking: Some((&value.content_defined_chunking).into()), enable_rle_to_dictionary: value.enable_rle_to_dictionary, diff --git a/datafusion/proto-models/src/from_proto.rs b/datafusion/proto-models/src/from_proto.rs index 8d8fef378c62c..d50b703720f1a 100644 --- a/datafusion/proto-models/src/from_proto.rs +++ b/datafusion/proto-models/src/from_proto.rs @@ -496,6 +496,15 @@ impl TryFrom<&ParquetOptionsProto> for ParquetOptions { ) => to_usize(*size, "max_predicate_cache_size"), }) .transpose()?, + read_ahead_bytes: proto + .read_ahead_bytes_opt + .as_ref() + .map(|opt| match opt { + parquet_options::ReadAheadBytesOpt::ReadAheadBytes(size) => { + to_usize(*size, "read_ahead_bytes") + } + }) + .transpose()?, max_row_group_bytes: proto .max_row_group_bytes_opt .as_ref() diff --git a/datafusion/proto-models/src/generated/datafusion_proto_common.rs b/datafusion/proto-models/src/generated/datafusion_proto_common.rs index a316ee0b16071..2a8f74dabb809 100644 --- a/datafusion/proto-models/src/generated/datafusion_proto_common.rs +++ b/datafusion/proto-models/src/generated/datafusion_proto_common.rs @@ -931,6 +931,8 @@ pub struct ParquetOptions { pub max_predicate_cache_size_opt: ::core::option::Option< parquet_options::MaxPredicateCacheSizeOpt, >, + #[prost(oneof = "parquet_options::ReadAheadBytesOpt", tags = "44")] + pub read_ahead_bytes_opt: ::core::option::Option, #[prost(oneof = "parquet_options::MaxRowGroupBytesOpt", tags = "37")] pub max_row_group_bytes_opt: ::core::option::Option< parquet_options::MaxRowGroupBytesOpt, @@ -1000,6 +1002,11 @@ pub mod parquet_options { MaxPredicateCacheSize(u64), } #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Oneof)] + pub enum ReadAheadBytesOpt { + #[prost(uint64, tag = "44")] + ReadAheadBytes(u64), + } + #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Oneof)] pub enum MaxRowGroupBytesOpt { #[prost(uint64, tag = "37")] MaxRowGroupBytes(u64), diff --git a/datafusion/sqllogictest/test_files/information_schema.slt b/datafusion/sqllogictest/test_files/information_schema.slt index d483f6b91fcc6..e33bcec29b81b 100644 --- a/datafusion/sqllogictest/test_files/information_schema.slt +++ b/datafusion/sqllogictest/test_files/information_schema.slt @@ -259,6 +259,7 @@ datafusion.execution.parquet.maximum_parallel_row_group_writers 1 datafusion.execution.parquet.metadata_size_hint 524288 datafusion.execution.parquet.pruning true datafusion.execution.parquet.pushdown_filters false +datafusion.execution.parquet.read_ahead_bytes NULL datafusion.execution.parquet.reorder_filters false datafusion.execution.parquet.row_group_range_assignment start_offset datafusion.execution.parquet.schema_force_view_types true @@ -431,6 +432,7 @@ datafusion.execution.parquet.maximum_parallel_row_group_writers 1 (writing) By d datafusion.execution.parquet.metadata_size_hint 524288 (reading) If specified, the parquet reader will try and fetch the last `size_hint` bytes of the parquet file optimistically. If not specified, two reads are required: One read to fetch the 8-byte parquet footer and another to fetch the metadata length encoded in the footer Default setting to 512 KiB, which should be sufficient for most parquet files, it can reduce one I/O operation per parquet file. If the metadata is larger than the hint, two reads will still be performed. datafusion.execution.parquet.pruning true (reading) If true, the parquet reader attempts to skip entire row groups based on the predicate in the query and the metadata (min/max values) stored in the parquet file datafusion.execution.parquet.pushdown_filters false (reading) If true, filter expressions are be applied during the parquet decoding operation to reduce the number of rows decoded. This optimization is sometimes called "late materialization". +datafusion.execution.parquet.read_ahead_bytes NULL (reading) If set, fetch Parquet data ahead of the decoder, in the order the decoder reads it, up to this many bytes for each file a partition stream reads. If unset, the reader fetches one row group at a time, when the decoder needs it. The window bounds the bytes in flight plus the fetched bytes the decoder still holds, including the gaps between ranges that one request reads through. Bytes the decoder needs are fetched even if the window is full. Read-ahead fetches small row groups whole and large ones in parts, with several requests in flight. The throughput of a partition stream is at most about this window divided by the storage latency. Thus, windows below a few MiB are slow on object storage. With read-ahead, the reader decodes a batch at a time. Scans that return the rows of each row group in reverse order (`reverse_rows`) decode a row group at a time, and read ahead the next row groups. Read-ahead also fetches ranges that a pushed-down filter can make unnecessary. In addition to this window, read-ahead takes only the memory that the memory pool grants. Bytes the decoder needs are fetched even if the pool is full. datafusion.execution.parquet.reorder_filters false (reading) If true, filter expressions evaluated during the parquet decoding operation will be reordered heuristically to minimize the cost of evaluation. If false, the filters are applied in the same order as written in the query datafusion.execution.parquet.row_group_range_assignment start_offset (reading) Which byte range of a split file reads each row group. `start_offset` picks the range containing the row group's start. `midpoint` picks the range containing its midpoint, as Spark does, which spreads large row groups more evenly across ranges. datafusion.execution.parquet.schema_force_view_types true (reading) If true, parquet reader will read columns of `Utf8/Utf8Large` with `Utf8View`, and `Binary/BinaryLarge` with `BinaryView`. The parquet reader is optimized for reading `Utf8View` and `BinaryView`, so such queries are significantly faster than reading `Utf8`/`Binary` and then casting to the view types. diff --git a/docs/source/library-user-guide/upgrading/index.md b/docs/source/library-user-guide/upgrading/index.md index d2372d78e87a2..581723e8c5358 100644 --- a/docs/source/library-user-guide/upgrading/index.md +++ b/docs/source/library-user-guide/upgrading/index.md @@ -76,6 +76,15 @@ the whole dictionary. Benchmark representative data before setting a high cap. Exhaustive Rust and generated protobuf `ParquetOptions` literals must add this field as `None` or use `..Default::default()`. The wire format is compatible. +### New field `read_ahead_bytes` added to `ParquetOptions` + +`ParquetOptions` gained `read_ahead_bytes: Option`. `Some(bytes)` makes a +Parquet scan fetch data ahead of the decoder within a window of that many bytes, +and decode a batch at a time. The default (`None`) does not change scans. + +Exhaustive Rust and generated protobuf `ParquetOptions` literals must add this +field as `None` or use `..Default::default()`. The wire format is compatible. + ### Substrait consumers use explicit scope context Add a final `&SubstraitConsumerContext` argument to custom relation and expression diff --git a/docs/source/user-guide/configs.md b/docs/source/user-guide/configs.md index 49efa6e4ed6b8..162deefd80ebd 100644 --- a/docs/source/user-guide/configs.md +++ b/docs/source/user-guide/configs.md @@ -82,6 +82,7 @@ The following configuration settings are available: | datafusion.execution.parquet.coerce_int96_tz | NULL | (reading) Optional timezone applied to INT96 columns when `coerce_int96` is set. When `Some`, INT96 columns coerce to `Timestamp(, Some())` instead of the default `Timestamp(, None)`. Spark and other systems write INT96 values as UTC-adjusted instants, so callers that need the resulting Arrow type to be timezone-aware (e.g. for Spark `TimestampType` semantics) should set this to `"UTC"`. No effect when `coerce_int96` is `None`, but the value is still validated when it is set. | | datafusion.execution.parquet.bloom_filter_on_read | true | (reading) Use any available bloom filters when reading parquet files | | datafusion.execution.parquet.max_predicate_cache_size | NULL | (reading) The maximum predicate cache size, in bytes. When `pushdown_filters` is enabled, sets the maximum memory used to cache the results of predicate evaluation between filter evaluation and output generation. Decreasing this value will reduce memory usage, but may increase IO and CPU usage. None means use the default parquet reader setting. 0 means no caching. | +| datafusion.execution.parquet.read_ahead_bytes | NULL | (reading) If set, fetch Parquet data ahead of the decoder, in the order the decoder reads it, up to this many bytes for each file a partition stream reads. If unset, the reader fetches one row group at a time, when the decoder needs it. The window bounds the bytes in flight plus the fetched bytes the decoder still holds, including the gaps between ranges that one request reads through. Bytes the decoder needs are fetched even if the window is full. Read-ahead fetches small row groups whole and large ones in parts, with several requests in flight. The throughput of a partition stream is at most about this window divided by the storage latency. Thus, windows below a few MiB are slow on object storage. With read-ahead, the reader decodes a batch at a time. Scans that return the rows of each row group in reverse order (`reverse_rows`) decode a row group at a time, and read ahead the next row groups. Read-ahead also fetches ranges that a pushed-down filter can make unnecessary. In addition to this window, read-ahead takes only the memory that the memory pool grants. Bytes the decoder needs are fetched even if the pool is full. | | datafusion.execution.parquet.max_in_list_size | 20 | Maximum number of input values in an `IN (...)` list eligible for min/max pruning. Lists above this cap, or a cap of 0, skip this rewrite; other predicates and Bloom-filter pruning remain available. Within the cap, nonempty lists of at most 20 values use the existing per-value rewrite. Larger literal lists use a compact representation when the column type is string, variable-length binary, integer, decimal, date, time, timestamp, or duration. This applies to both `IN` and `NOT IN`, including lists with NULL members. `NOT IN` with NULL and all-NULL `IN` lists cannot match any rows. Compact lists containing NULL do not use the fully-matched-row-group optimization. Floating-point and other lists retain the existing per-value rewrite, so raising the cap can make those predicates expensive to build and evaluate. Defaults to 20. | | datafusion.execution.parquet.enable_rle_to_dictionary | false | (reading) If true, top-level string and binary Parquet columns with dictionary pages are inferred and scanned as `Dictionary` / `Dictionary` instead of their plain value type. This applies only when DataFusion infers the table schema. Tables with a user-supplied schema are not promoted because the Parquet footer is not read at DDL time, so dictionary pages cannot be detected per column. Setting `dictionary_read_max_distinct_values` also enables dictionary reads. When both options are set, the cap controls which plain columns are promoted. See | | datafusion.execution.parquet.dictionary_read_max_distinct_values | NULL | (reading) If set, promote top-level plain string and binary columns to dictionaries when every data page is dictionary encoded and the per-file sum of row-group cardinality upper bounds is within this cap. Files without page encoding statistics, such as those written by parquet-rs before 55.0.0 (DataFusion 46 and earlier) or DuckDB 1.1, are not promoted. Missing NDVs use the non-null row count when available and the row count otherwise. Values repeated across row groups may be counted more than once. The cap does not demote a dictionary declared by the same file; mixed dictionary/plain schemas across files still merge as plain. Computed during schema inference. Large row-group dictionaries can be slower because each output batch can retain the whole dictionary. The crossover is workload-dependent: in one 20-million-row group-by benchmark with 40-byte strings and five row groups per file, files with a per-file sum of about 500,000 (100,000 per row group) were faster than plain reads, while files with about 1,460,000 (about 295,000 per row group) were slower. Use a conservative cap and benchmark representative queries. | From 753ebfcebbd2eab93a019be2e4e7aba58bf9430f Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Sat, 5 Dec 2026 01:06:36 -0600 Subject: [PATCH 4/6] feat: read ahead in Parquet scans and decode a batch at a time A Parquet scan buffers a full row group before it decodes a row: the push decoder does not return a batch until every byte that the row group reads has arrived. On object storage, I/O and decoding then alternate, and resident bytes and time to first batch depend on how the file was written (https://github.com/apache/datafusion/issues/18470). With `datafusion.execution.parquet.read_ahead_bytes` set, the scan builds the same `ParquetPushDecoder` with `RequestGranularity::Batch` and drives it with `try_decode` (`transition_streaming`). `ReadAhead` does all fetches of the scan: - Plan: it reads `ParquetPushDecoder::scan_plan` in decode order, as far as the window reaches. After the decoder drops row groups or is rebuilt, it takes a new plan. - Runs: it merges planned ranges into one contiguous range per fetch when the gap is at most `clamp(window / 16, 64 KiB, 1 MiB)`. A run never crosses a row group. Each run is one `AsyncFileReader::get_bytes` call and one buffer in the decoder. - Readers: each fetch in flight has its own reader, created with the opener's `ParquetFileReaderFactory::create_reader` call. Custom factories and `bytes_scanned` keep working. - Scheduling: a fetch starts when the window has room for `min(target_part, rest of the next row group)` bytes, with `target_part = clamp(window / 2, 64 KiB, 8 MiB)`. Small row groups are fetched whole and large ones in parts. At most 8 fetches are in flight. - `NeedsData`: a range inside a run in flight waits for that run. Other ranges are fetched at once, concurrently with read-ahead. - Memory: a `ParquetReadAhead[partition]` consumer is charged for every run at its full length, gaps included, while the run is in flight and until `Bytes::is_unique` shows that the decoder released it. Bytes that the decoder asks for use `grow`. Read-ahead uses `try_grow`, so it takes only what the pool grants. - Pruning: read-ahead skips the row groups that the dynamic pruner already prunes, and drops fetched runs of row groups that the decoder does not read. A `reverse_rows` scan buffers a full row group before it returns a row. It keeps the `try_next_reader` driver and `RequestGranularity::RowGroup`, and `ReadAhead` fetches the next row groups while it decodes. The scan loads the page index when a row group is larger than the window, because the decoder then fetches pages. Two metrics are registered only for a file that is read with read-ahead: `read_ahead_bytes_fetched` (bytes fetched before the decoder asked for them, gaps included) and `read_ahead_wait_time` (time the scan waited for fetches of ranges that the decoder asked for). Without the option, the scan is unchanged. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 --- datafusion/datasource-parquet/src/metrics.rs | 37 + .../datasource-parquet/src/opener/mod.rs | 470 +++++- .../datasource-parquet/src/push_decoder.rs | 1357 ++++++++++++++++- datafusion/datasource-parquet/src/source.rs | 5 + 4 files changed, 1830 insertions(+), 39 deletions(-) diff --git a/datafusion/datasource-parquet/src/metrics.rs b/datafusion/datasource-parquet/src/metrics.rs index d4c0615fbc18b..47afcd235dc5a 100644 --- a/datafusion/datasource-parquet/src/metrics.rs +++ b/datafusion/datasource-parquet/src/metrics.rs @@ -176,6 +176,43 @@ impl Drop for ByteProgress { } } +/// Metrics of a file that is read with read-ahead +/// (`datafusion.execution.parquet.read_ahead_bytes`). +/// +/// They are registered only for such a file, so a scan without read-ahead +/// does not show them. +#[derive(Debug, Clone)] +pub(crate) struct ReadAheadMetrics { + /// `read_ahead_bytes_fetched`: bytes that read-ahead fetched before the + /// decoder asked for them, including the gaps between ranges that a + /// fetch reads through. It does not count the fetches that the decoder + /// asked for. With the default reader, `bytes_scanned` counts both. + pub bytes_fetched: Count, + /// `read_ahead_wait_time`: time the scan waited for the fetches of byte + /// ranges that the decoder asked for. This includes the wait for a + /// read-ahead fetch in flight that holds such a range. Read-ahead that + /// keeps ahead of the decoder keeps this near zero. + pub wait_time: Time, +} + +impl ReadAheadMetrics { + pub(crate) fn new( + metrics: &ExecutionPlanMetricsSet, + partition: usize, + filename: &str, + ) -> Self { + let builder = MetricBuilder::new(metrics) + .with_new_label("filename", filename.to_string()) + .with_type(MetricType::Summary); + Self { + bytes_fetched: builder + .clone() + .bytes_counter("read_ahead_bytes_fetched", partition), + wait_time: builder.subset_time("read_ahead_wait_time", partition), + } + } +} + impl ParquetFileMetrics { /// Create new metrics pub fn new( diff --git a/datafusion/datasource-parquet/src/opener/mod.rs b/datafusion/datasource-parquet/src/opener/mod.rs index d0349bd65860d..8a8248d16700e 100644 --- a/datafusion/datasource-parquet/src/opener/mod.rs +++ b/datafusion/datasource-parquet/src/opener/mod.rs @@ -14,11 +14,14 @@ use self::encryption::EncryptionContext; use crate::access_plan::PreparedAccessPlan; use crate::bloom_filter::BloomFilterStatistics; use crate::decoder_projection::DecoderProjection; -use crate::metrics::{ByteProgress, RowFilterSkippedFullyMatchedMetric}; +use crate::metrics::{ + ByteProgress, ReadAheadMetrics, RowFilterSkippedFullyMatchedMetric, +}; use crate::page_filter::PagePruningAccessPlanFilter; use crate::push_decoder::{ - DecoderBuilderConfig, InitialDecoderState, PushDecoderStreamState, RgPlanEntry, - RowFilterContext, RowGroupPruner, RowGroupReverser, + DecoderBuilderConfig, InitialDecoderState, PushDecoderStreamState, ReadAhead, + ReadAheadMemory, ReaderFactory, RgPlanEntry, RowFilterContext, RowGroupPruner, + RowGroupReverser, }; use crate::row_group_filter::{RowGroupAccessPlanFilter, row_group_in_range}; use crate::{ @@ -75,6 +78,7 @@ use parquet::arrow::arrow_reader::{ }; use parquet::arrow::async_reader::AsyncFileReader; use parquet::arrow::parquet_column; +use parquet::arrow::push_decoder::RequestGranularity; use parquet::bloom_filter::Sbbf; use parquet::file::metadata::{PageIndexPolicy, ParquetMetaDataReader, RowGroupMetaData}; @@ -295,12 +299,16 @@ pub(super) struct ParquetMorselizer { /// How row groups are assigned to the byte ranges of a split file. Sourced /// from `datafusion.execution.parquet.row_group_range_assignment`. pub row_group_range_assignment: RowGroupRangeAssignment, + /// Read-ahead window in bytes. If set, decode a batch at a time. Sourced + /// from `datafusion.execution.parquet.read_ahead_bytes`. + pub read_ahead_bytes: Option, /// Whether to read row groups in reverse order pub reverse_row_groups: bool, /// Whether to also reverse the rows of each row group, making a reversed /// scan exactly ordered. Buffers one decoded row group at a time. pub reverse_rows: bool, - /// Pool charged for the row group a `reverse_rows` scan buffers. + /// Pool charged for the row group a `reverse_rows` scan buffers, and for + /// read-ahead buffers. pub memory_pool: Option>, /// Optional sort order used to reorder row groups by their min/max statistics. pub sort_order_for_reorder: Option, @@ -491,6 +499,7 @@ struct PreparedParquetOpen { max_in_list_size: usize, enable_rle_to_dictionary: bool, row_group_range_assignment: RowGroupRangeAssignment, + read_ahead_bytes: Option, reverse_row_groups: bool, reverse_rows: bool, memory_pool: Option>, @@ -644,7 +653,24 @@ impl ParquetOpenState { if prepared_row_groups.row_groups.is_fully_pruned() { return Ok(ParquetOpenState::Done); } - if prepared_row_groups.should_load_page_index()? { + // A batch-granular scan fetches pages when an offset index + // exists, so also load it when a row group is larger than the + // read-ahead window. + let loaded = &prepared_row_groups.prepared.loaded; + let fetches_pages = match loaded.prepared.read_ahead_bytes { + Some(window) + if loaded.prepared.enable_page_index + && !loaded.prepared.reverse_rows => + { + let metadata = loaded.reader_metadata.metadata(); + prepared_row_groups + .row_groups + .row_group_indexes() + .any(|idx| row_group_bytes(metadata.row_group(idx)) > window) + } + _ => false, + }; + if fetches_pages || prepared_row_groups.should_load_page_index()? { Ok(ParquetOpenState::LoadPageIndex( prepared_row_groups.load_page_index().boxed(), )) @@ -1000,6 +1026,7 @@ impl ParquetMorselizer { max_in_list_size: self.max_in_list_size, enable_rle_to_dictionary: self.enable_rle_to_dictionary, row_group_range_assignment: self.row_group_range_assignment, + read_ahead_bytes: self.read_ahead_bytes, reverse_row_groups: self.reverse_row_groups, reverse_rows: self.reverse_rows, memory_pool: self.memory_pool.clone(), @@ -1734,6 +1761,8 @@ impl RowGroupsPrunedParquetOpen { None => DecoderReadPlans::try_new(&prepared, &reader_metadata)?, }; + let read_ahead_bytes = prepared.read_ahead_bytes; + // Lazily-registered suppression counter shared by the open-time first-RG // skip below and the stream's per-RG toggle (registered on first use so // scans that never suppress don't carry a zero-valued counter). @@ -1827,6 +1856,12 @@ impl RowGroupsPrunedParquetOpen { } } + // A `reverse_rows` scan buffers a full row group before it + // returns a row, so it decodes a row group at a time. + if read_ahead_bytes.is_some() && !prepared.reverse_rows { + builder = builder.with_request_granularity(RequestGranularity::Batch); + } + InitialDecoderState { decoder: builder.build()?, rg_plan, @@ -1897,11 +1932,57 @@ impl RowGroupsPrunedParquetOpen { .file_metrics .row_groups_pruned_dynamic_filter .clone(); + // Read-ahead does all fetches of the scan with its own readers, so + // it takes the opener's reader. Each further reader comes from the + // factory, with the call the opener makes. + let (reader, read_ahead) = match read_ahead_bytes { + Some(window) => { + let factory = Arc::clone(&prepared.parquet_file_reader_factory); + let partition_index = prepared.partition_index; + let file = prepared.partitioned_file.clone(); + let metadata_size_hint = prepared.metadata_size_hint; + let reader_metrics = prepared.metrics.clone(); + let new_reader: ReaderFactory = Box::new(move || { + let reader: Box = factory.create_reader( + partition_index, + file.clone(), + metadata_size_hint, + &reader_metrics, + )?; + Ok(reader) + }); + let metadata = reader_metadata.metadata(); + let whole_chunks = PushDecoderStreamState::whole_chunk_leaves( + metadata.file_metadata().schema_descr().num_columns(), + prepared.reverse_rows, + row_filter_context.as_ref().filter(|_| filter_installed), + ); + let read_ahead = ReadAhead::new( + window, + decoder.scan_plan(), + metadata, + whole_chunks, + prepared.async_file_reader, + new_reader, + ReadAheadMemory::new( + prepared.memory_pool.clone(), + prepared.partition_index, + ), + ReadAheadMetrics::new( + &prepared.metrics, + prepared.partition_index, + &prepared.file_name, + ), + ); + (None, Some(read_ahead)) + } + None => (Some(prepared.async_file_reader), None), + }; let stream = PushDecoderStreamState { decoder: Some(decoder), active_reader: None, rg_plan, - reader: prepared.async_file_reader, + reader, decoder_projection, arrow_reader_metrics, predicate_cache_inner_records, @@ -1923,6 +2004,7 @@ impl RowGroupsPrunedParquetOpen { }); RowGroupReverser::new(prepared.limit, reservation) }), + read_ahead, } .into_stream(); @@ -2259,6 +2341,7 @@ mod test { max_in_list_size: usize, enable_rle_to_dictionary: bool, row_group_range_assignment: RowGroupRangeAssignment, + read_ahead_bytes: Option, reverse_row_groups: bool, reverse_rows: bool, memory_pool: Option>, @@ -2481,6 +2564,7 @@ mod test { max_in_list_size: MAX_IN_LIST_SIZE, enable_rle_to_dictionary: false, row_group_range_assignment: RowGroupRangeAssignment::default(), + read_ahead_bytes: None, reverse_row_groups: false, reverse_rows: false, memory_pool: None, @@ -2581,6 +2665,12 @@ mod test { self } + /// Set the read-ahead window (`read_ahead_bytes`). + fn with_read_ahead_bytes(mut self, bytes: u64) -> Self { + self.read_ahead_bytes = Some(bytes); + self + } + /// Set a row limit. fn with_limit(mut self, limit: usize) -> Self { self.limit = Some(limit); @@ -2707,6 +2797,7 @@ mod test { max_in_list_size: self.max_in_list_size, enable_rle_to_dictionary: self.enable_rle_to_dictionary, row_group_range_assignment: self.row_group_range_assignment, + read_ahead_bytes: self.read_ahead_bytes, reverse_row_groups: self.reverse_row_groups, reverse_rows: self.reverse_rows, memory_pool: self.memory_pool.clone(), @@ -6444,4 +6535,371 @@ mod test { &DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Binary)) ); } + + /// Read-ahead (`read_ahead_bytes`) and its accounting in the memory pool. + mod read_ahead { + use super::*; + use std::ops::Range; + use std::sync::Mutex; + + use bytes::Bytes; + + use arrow::array::Int64Array; + use arrow::compute::concat_batches; + use datafusion_execution::memory_pool::{ + GreedyMemoryPool, MemoryPool, PeakRecordingPool, + }; + use futures::future::BoxFuture; + use parquet::arrow::arrow_reader::ArrowReaderOptions; + use parquet::arrow::async_reader::AsyncFileReader; + + const WINDOW: u64 = 1024 * 1024; + const ROWS: i64 = 400_000; + + /// Records the bytes of every data fetch of the readers it creates. + #[derive(Debug)] + struct RecordingReaderFactory { + inner: DefaultParquetFileReaderFactory, + fetches: Arc>>, + } + + struct RecordingReader { + inner: Box, + fetches: Arc>>, + } + + impl ParquetFileReaderFactory for RecordingReaderFactory { + fn create_reader( + &self, + partition_index: usize, + partitioned_file: PartitionedFile, + metadata_size_hint: Option, + metrics: &ExecutionPlanMetricsSet, + ) -> Result> { + Ok(Box::new(RecordingReader { + inner: self.inner.create_reader( + partition_index, + partitioned_file, + metadata_size_hint, + metrics, + )?, + fetches: Arc::clone(&self.fetches), + })) + } + } + + impl AsyncFileReader for RecordingReader { + fn get_bytes( + &mut self, + range: Range, + ) -> BoxFuture<'_, parquet::errors::Result> { + self.fetches.lock().unwrap().push(range.end - range.start); + self.inner.get_bytes(range) + } + + fn get_byte_ranges( + &mut self, + ranges: Vec>, + ) -> BoxFuture<'_, parquet::errors::Result>> { + let bytes = ranges.iter().map(|r| r.end - r.start).sum(); + self.fetches.lock().unwrap().push(bytes); + self.inner.get_byte_ranges(ranges) + } + + fn get_metadata<'a>( + &'a mut self, + options: Option<&'a ArrowReaderOptions>, + ) -> BoxFuture<'a, parquet::errors::Result>> + { + self.inner.get_metadata(options) + } + } + + /// A file of several MB: `a` is `0..ROWS`, `b` does not compress. + /// Ten row groups of several pages each. + async fn write_file(store: &Arc) -> (SchemaRef, usize) { + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int64, false), + Field::new("b", DataType::Int64, false), + ])); + let a: Vec = (0..ROWS).collect(); + let b: Vec = a + .iter() + .map(|v| v.wrapping_mul(0x9E37_79B9_7F4A_7C15_u64 as i64)) + .collect(); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int64Array::from(a)), Arc::new(Int64Array::from(b))], + ) + .unwrap(); + let props = WriterProperties::builder() + .set_dictionary_enabled(false) + .set_max_row_group_row_count(Some(ROWS as usize / 10)) + .set_data_page_row_count_limit(4096) + .set_write_batch_size(4096) + .build(); + let len = write_parquet_batches( + Arc::clone(store), + "read_ahead.parquet", + vec![batch], + Some(props), + ) + .await; + (schema, len) + } + + struct Scan { + /// The metrics of the scan. + metrics: ExecutionPlanMetricsSet, + batches: Vec, + /// Bytes of each data fetch. + fetches: Vec, + /// `pool.reserved()` after each batch. + reserved: Vec, + } + + /// Scan the file, with read-ahead if `pool` is set. + async fn scan( + pool: Option>, + predicate: Option>, + ) -> Scan { + scan_rows(pool, predicate, false).await + } + + /// [`scan`], with each row group's rows in reverse order if + /// `reverse_rows`. + async fn scan_rows( + pool: Option>, + predicate: Option>, + reverse_rows: bool, + ) -> Scan { + let store = Arc::new(InMemory::new()) as Arc; + let (schema, len) = write_file(&store).await; + let fetches = Arc::new(Mutex::new(vec![])); + let factory = RecordingReaderFactory { + inner: DefaultParquetFileReaderFactory::new(Arc::clone(&store)), + fetches: Arc::clone(&fetches), + }; + let metrics = ExecutionPlanMetricsSet::new(); + let mut builder = ParquetMorselizerBuilder::new() + .with_store(Arc::clone(&store)) + .with_schema(Arc::clone(&schema)) + .with_projection_indices(&[0, 1]) + .with_metrics(metrics.clone()) + .with_parquet_file_reader_factory(Arc::new(factory)) + .with_reverse_rows(reverse_rows); + if let Some(predicate) = predicate { + builder = builder + .with_predicate(predicate) + .with_pushdown_filters(true); + } + if let Some(pool) = &pool { + builder = builder + .with_read_ahead_bytes(WINDOW) + .with_memory_pool(Arc::clone(pool)); + } + let morselizer = builder.build(); + let file = PartitionedFile::new("read_ahead.parquet".to_string(), len as u64); + let mut stream = open_file(&morselizer, file).await.unwrap(); + let mut batches = vec![]; + let mut reserved = vec![]; + while let Some(batch) = stream.next().await { + batches.push(batch.unwrap()); + reserved.extend(pool.as_ref().map(|p| p.reserved())); + } + drop(stream); + drop(morselizer); + if let Some(pool) = &pool { + assert_eq!(pool.reserved(), 0, "the stream returns all it reserved"); + } + let fetches = fetches.lock().unwrap().clone(); + Scan { + metrics, + batches, + fetches, + reserved, + } + } + + fn concat(batches: &[RecordBatch]) -> RecordBatch { + concat_batches(&batches[0].schema(), batches).unwrap() + } + + fn a_lt(value: i64) -> Arc { + let schema = Schema::new(vec![Field::new("a", DataType::Int64, false)]); + logical2physical(&col("a").lt(lit(value)), &schema) + } + + /// A pool far smaller than the file cannot stop the scan: the bytes + /// the decoder needs are always granted. + #[tokio::test] + async fn small_pool_scan_is_correct_and_releases_all() { + let expected = scan(None, None).await; + let pool: Arc = Arc::new(GreedyMemoryPool::new(64 * 1024)); + let actual = scan(Some(pool), None).await; + assert_eq!(concat(&actual.batches), concat(&expected.batches)); + assert_eq!(concat(&actual.batches).num_rows(), ROWS as usize); + } + + /// With room in the pool, the reservation follows what read-ahead + /// holds and stays within the window plus one required fetch. + #[tokio::test] + async fn reservation_is_bounded_by_window() { + let recorder = Arc::new(PeakRecordingPool::new(Arc::new( + GreedyMemoryPool::new(1 << 30), + ))); + let pool: Arc = Arc::clone(&recorder) as _; + let actual = scan(Some(pool), None).await; + // A required fetch is at most the largest fetch. + let largest_fetch = *actual.fetches.iter().max().unwrap(); + let peak = recorder.max_reserved() as u64; + assert!(actual.reserved.iter().any(|&r| r > 0)); + assert!( + peak <= WINDOW + largest_fetch, + "peak {peak}, largest fetch {largest_fetch}" + ); + } + + /// A filter that rejects every row: without read-ahead the scan never + /// reads `b`. Read-ahead fetches `b` ahead, unless the pool has no + /// room for it. + #[tokio::test] + async fn ranges_a_filter_makes_unnecessary_are_read_ahead_within_the_pool() { + let bytes = |scan: &Scan| scan.fetches.iter().sum::(); + let baseline = scan(None, Some(a_lt(-1))).await; + assert_eq!( + baseline.batches.iter().map(|b| b.num_rows()).sum::(), + 0 + ); + + let unbounded: Arc = Arc::new(GreedyMemoryPool::new(1 << 30)); + let ahead = scan(Some(unbounded), Some(a_lt(-1))).await; + let full: Arc = Arc::new(GreedyMemoryPool::new(1)); + let required_only = scan(Some(full), Some(a_lt(-1))).await; + assert!(bytes(&ahead) > bytes(&baseline)); + assert_eq!(bytes(&required_only), bytes(&baseline)); + } + + /// The value of a metric of the scan, or `None` if the scan did not + /// register it. + fn metric(scan: &Scan, name: &str) -> Option { + scan.metrics + .clone_inner() + .sum_by_name(name) + .map(|value| value.as_usize()) + } + + /// `read_ahead_bytes_fetched` counts the bytes fetched before the + /// decoder asked for them. A scan without read-ahead registers + /// neither read-ahead metric. + #[tokio::test] + async fn metrics_report_the_bytes_fetched_ahead() { + let bytes = |scan: &Scan| scan.fetches.iter().sum::() as usize; + let baseline = scan(None, Some(a_lt(-1))).await; + assert_eq!(metric(&baseline, "read_ahead_bytes_fetched"), None); + assert_eq!(metric(&baseline, "read_ahead_wait_time"), None); + + // The filter rejects every row, so the decoder never asks for + // `b`. All the bytes above the baseline were fetched ahead. + let unbounded: Arc = Arc::new(GreedyMemoryPool::new(1 << 30)); + let ahead = scan(Some(unbounded), Some(a_lt(-1))).await; + let fetched_ahead = metric(&ahead, "read_ahead_bytes_fetched").unwrap(); + assert!(fetched_ahead >= bytes(&ahead) - bytes(&baseline)); + assert!(fetched_ahead <= bytes(&ahead)); + assert!(metric(&ahead, "read_ahead_wait_time").is_some()); + + // A pool with no room grants no speculative bytes. + let full: Arc = Arc::new(GreedyMemoryPool::new(1)); + let required_only = scan(Some(full), Some(a_lt(-1))).await; + assert_eq!(metric(&required_only, "read_ahead_bytes_fetched"), Some(0)); + } + + /// A `reverse_rows` scan decodes a row group at a time. Read-ahead + /// fetches the next row groups while it does, and the rows are the + /// same as without read-ahead. + #[tokio::test] + async fn reverse_rows_scan_reads_ahead() { + let expected = scan_rows(None, Some(a_lt(300_000)), true).await; + let pool: Arc = Arc::new(GreedyMemoryPool::new(1 << 30)); + let actual = scan_rows(Some(pool), Some(a_lt(300_000)), true).await; + let expected = concat(&expected.batches); + assert_eq!(expected.num_rows(), 300_000); + let first = expected + .column(0) + .as_primitive::() + .value(0); + assert_eq!(first, 39_999, "row group 0, last row first"); + assert_eq!(concat(&actual.batches), expected); + assert!(metric(&actual, "read_ahead_bytes_fetched").unwrap() > 0); + } + + /// A filter toggled off for a fully matched row group and on again + /// for the next one: the rebuilt decoders release and then read the + /// filter column again. Read-ahead fetches it again, so the decoder + /// never waits on a fetch of its own after the first one. + #[tokio::test] + async fn filter_toggle_refetches_released_ranges_ahead() { + let store = Arc::new(InMemory::new()) as Arc; + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int64, false), + Field::new("b", DataType::Int64, false), + ])); + // `a >= 500` matches half of row groups 0 and 2, and all of 1. + let batches = [0, 10_000, 0].map(|base: i64| { + let a: Vec = (base..base + 1000).collect(); + let b: Vec = a.iter().map(|v| v * 3).collect(); + RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int64Array::from(a)), Arc::new(Int64Array::from(b))], + ) + .unwrap() + }); + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(1000)) + .build(); + let len = write_parquet_batches( + Arc::clone(&store), + "toggle.parquet", + batches.to_vec(), + Some(props), + ) + .await; + let fetches = Arc::new(Mutex::new(vec![])); + let factory = RecordingReaderFactory { + inner: DefaultParquetFileReaderFactory::new(Arc::clone(&store)), + fetches: Arc::clone(&fetches), + }; + let metrics = ExecutionPlanMetricsSet::new(); + let predicate = logical2physical(&col("a").gt_eq(lit(500i64)), &schema); + let morselizer = ParquetMorselizerBuilder::new() + .with_store(Arc::clone(&store)) + .with_schema(Arc::clone(&schema)) + .with_projection_indices(&[1]) + .with_predicate(predicate) + .with_pushdown_filters(true) + .with_row_group_stats_pruning(true) + .with_metrics(metrics.clone()) + .with_parquet_file_reader_factory(Arc::new(factory)) + .with_read_ahead_bytes(64 * 1024 * 1024) + .build(); + let file = PartitionedFile::new("toggle.parquet".to_string(), len as u64); + let (_, rows) = + count_batches_and_rows(open_file(&morselizer, file).await.unwrap()).await; + assert_eq!(rows, 2000); + assert_eq!( + counter_metric_value(&metrics, "row_filter_skipped_fully_matched"), + 1 + ); + let fetches = fetches.lock().unwrap().clone(); + let fetched: u64 = fetches.iter().sum(); + let ahead = metrics + .clone_inner() + .sum_by_name("read_ahead_bytes_fetched") + .unwrap() + .as_usize() as u64; + // The first fetch is the filter column of row group 0, which + // the decoder asks for. All later fetches are read-ahead. + assert_eq!(fetched - ahead, fetches[0], "fetches: {fetches:?}"); + } + } } diff --git a/datafusion/datasource-parquet/src/push_decoder.rs b/datafusion/datasource-parquet/src/push_decoder.rs index 8998afe3e86bc..5777949d7debb 100644 --- a/datafusion/datasource-parquet/src/push_decoder.rs +++ b/datafusion/datasource-parquet/src/push_decoder.rs @@ -21,14 +21,16 @@ //! The opener constructs both halves and hands the state off to //! [`PushDecoderStreamState::into_stream`] for consumption. -use std::collections::{HashSet, VecDeque}; +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; +use std::ops::Range; use std::sync::Arc; use arrow::array::{RecordBatch, UInt32Array}; use arrow::compute::take_record_batch; use arrow::datatypes::SchemaRef; -use futures::StreamExt; +use bytes::Bytes; use futures::stream::BoxStream; +use futures::{FutureExt, StreamExt}; use log::debug; use parquet::DecodeResult; use parquet::arrow::ProjectionMask; @@ -38,21 +40,29 @@ use parquet::arrow::arrow_reader::{ }; use parquet::arrow::async_reader::AsyncFileReader; use parquet::arrow::push_decoder::{ - ParquetPushDecoder, ParquetPushDecoderBuilder, RowGroupSelection, + ParquetPushDecoder, ParquetPushDecoderBuilder, PlannedRange, RowGroupSelection, + ScanPlan, }; use parquet::file::metadata::ParquetMetaData; -use datafusion_common::{DataFusionError, Result}; -use datafusion_execution::memory_pool::MemoryReservation; +use datafusion_common::{DataFusionError, Result, internal_err}; +use datafusion_common_runtime::SpawnedTask; +use datafusion_execution::memory_pool::{ + MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation, UnboundedMemoryPool, +}; use datafusion_physical_expr::expressions::DynamicFilterTracking; use datafusion_physical_expr_common::physical_expr::PhysicalExpr; -use datafusion_physical_plan::metrics::{BaselineMetrics, Count, Gauge}; +use datafusion_physical_plan::metrics::{ + BaselineMetrics, Count, Gauge, ScopedTimerGuard, +}; use datafusion_pruning::{PruningPredicate, PruningPredicateBuilder}; use crate::ParquetFileMetrics; use crate::decoder_projection::DecoderProjection; use crate::metadata::missing_null_counts_are_zero; -use crate::metrics::{ByteProgress, RowFilterSkippedFullyMatchedMetric}; +use crate::metrics::{ + ByteProgress, ReadAheadMetrics, RowFilterSkippedFullyMatchedMetric, +}; use crate::row_filter::{ PrebuiltRowFilterCandidate, prebuild_row_filter_candidates, row_filter_from_prebuilt, }; @@ -274,7 +284,8 @@ pub(crate) struct PushDecoderStreamState { pub(crate) decoder: Option, pub(crate) active_reader: Option, pub(crate) rg_plan: VecDeque, - pub(crate) reader: Box, + /// The file reader. `None` with read-ahead, which owns the readers. + pub(crate) reader: Option>, /// Per-file projection: the mask installed on every decoder and the /// per-batch transform applied by [`Self::project_batch`]. pub(crate) decoder_projection: DecoderProjection, @@ -313,6 +324,10 @@ pub(crate) struct PushDecoderStreamState { /// row group is decoded in full before any of it is returned, so one /// decoded row group is held in memory at a time. pub(crate) reverser: Option, + /// Read-ahead, set by `read_ahead_bytes`. It does all fetches of the + /// scan. Without [`Self::reverser`], [`Self::transition_streaming`] + /// drives the decoder a batch at a time. + pub(crate) read_ahead: Option, } /// A reusable, `Arc`-shared list of prebuilt row-filter candidates. @@ -435,6 +450,9 @@ impl PushDecoderStreamState { // Cloning `Time` shares the underlying counter and keeps the guard // from borrowing `self`. The guard records on drop, which covers // every return. + if self.read_ahead.is_some() && self.reverser.is_none() { + return self.transition_streaming().await; + } let elapsed_compute = self.baseline_metrics.elapsed_compute().clone(); let mut timer = elapsed_compute.timer(); loop { @@ -482,12 +500,22 @@ impl PushDecoderStreamState { } } - // Step 2: row-group boundary work (pruning, filter toggle). + // Step 2: row-group boundary work (pruning, filter toggle), then + // read-ahead (after pruning). + if self.read_ahead.is_some() + && let Err(e) = self.land_ready() + { + return Some((Err(e), self)); + } match self.handle_row_group_boundary() { Ok(true) => return None, Ok(false) => {} Err(e) => return Some((Err(e), self)), } + self.sync_memory(); + if let Err(e) = self.start_read_ahead() { + return Some((Err(e), self)); + } // Step 3: drive the decoder. let decoder = self.decoder.as_mut().expect("decoder present"); @@ -495,26 +523,8 @@ impl PushDecoderStreamState { self.follow_decoder(); match decoded { Ok(DecodeResult::NeedsData(ranges)) => { - // I/O, not compute. - timer.stop(); - let data = self - .reader - .get_byte_ranges(ranges.clone()) - .await - .map_err(DataFusionError::from); - timer.restart(); - match data { - Ok(data) => { - if let Err(e) = self - .decoder - .as_mut() - .expect("decoder present") - .push_ranges(ranges, data) - { - return Some((Err(DataFusionError::from(e)), self)); - } - } - Err(e) => return Some((Err(e), self)), + if let Err(e) = self.fetch(ranges, &mut timer).await { + return Some((Err(e), self)); } } Ok(DecodeResult::Data(reader)) => { @@ -531,8 +541,33 @@ impl PushDecoderStreamState { } } - /// Row-group boundary work. Returns `Ok(true)` when the stream should - /// finish. + /// Fetch `ranges` for the default driver and push them into the decoder, + /// through read-ahead if it is set. Pauses `compute` while it waits. + async fn fetch( + &mut self, + ranges: Vec>, + compute: &mut ScopedTimerGuard<'_>, + ) -> Result<()> { + if self.read_ahead.is_some() { + return self.fetch_needed(ranges, compute).await; + } + compute.stop(); + let data = self + .reader + .as_mut() + .expect("the reader is set without read-ahead") + .get_byte_ranges(ranges.clone()) + .await; + compute.restart(); + self.decoder + .as_mut() + .expect("decoder present") + .push_ranges(ranges, data?)?; + Ok(()) + } + + /// Row-group boundary work, shared by both drivers. Returns `Ok(true)` + /// when the stream should finish. /// /// At a row-group boundary, drop every queued row group that the pruner /// proves cannot contribute, then toggle the per-row `RowFilter` for the @@ -549,11 +584,14 @@ impl PushDecoderStreamState { if !at_boundary || self.rg_plan.is_empty() { return Ok(false); } - self.prune_row_groups()?; + let pruned = self.prune_row_groups()?; if self.rg_plan.is_empty() { return Ok(true); } - self.toggle_row_filter()?; + let toggled = self.toggle_row_filter()?; + if pruned > 0 || toggled { + self.reset_read_ahead_plan(); + } Ok(false) } @@ -578,6 +616,15 @@ impl PushDecoderStreamState { for entry in self.rg_plan.drain(..=idx) { self.byte_progress.credit(entry.bytes); } + if let Some(read_ahead) = self.read_ahead.as_mut() { + let live: HashSet = self + .rg_plan + .iter() + .map(|entry| entry.rg_index) + .chain([active]) + .collect(); + read_ahead.covered.retain(|_, rg, _| live.contains(&rg)); + } } /// Credit the row groups that the decoder will not read: it has finished. @@ -672,6 +719,29 @@ impl PushDecoderStreamState { Ok(true) } + /// Follow a decoder that dropped row groups or was rebuilt: a held + /// [`ScanPlan`] is a snapshot of the row groups queued when it was made. + fn reset_read_ahead_plan(&mut self) { + let Some(read_ahead) = self.read_ahead.as_mut() else { + return; + }; + let decoder = self.decoder.as_ref().expect("decoder present"); + let filter = self + .row_filter_context + .as_ref() + .filter(|_| self.filter_installed); + let whole_chunks = Self::whole_chunk_leaves( + read_ahead.whole_chunks.len(), + self.reverser.is_some(), + filter, + ); + let projection = self.decoder_projection.projection_mask(); + read_ahead.reset_plan(decoder.scan_plan(), whole_chunks, |leaf| { + projection.leaf_included(leaf) + || filter.is_some_and(|ctx| ctx.reads_leaf(leaf)) + }); + } + /// Copies metrics from ArrowReaderMetrics (the metrics collected by the /// arrow-rs parquet reader) to the parquet file metrics for DataFusion fn copy_arrow_reader_metrics(&self) { @@ -787,6 +857,834 @@ impl RowGroupReverser { } } +// `datafusion.execution.parquet.read_ahead_bytes`: a batch-granular push +// decoder (`RequestGranularity::Batch`) plus [`ReadAhead`], which fetches +// [`ParquetPushDecoder::scan_plan`] ranges within a byte window. + +/// The most fetches that read-ahead keeps in flight for a file, and so the +/// most readers it holds. The window in bytes is the main limit. +const MAX_FETCHES_IN_FLIGHT: usize = 8; + +const KIB: u64 = 1024; +const MIB: u64 = 1024 * KIB; + +/// Creates a reader for the file, with the call that the opener makes. Each +/// fetch in flight uses its own reader. +pub(crate) type ReaderFactory = Box Result> + Send>; + +/// The largest gap between two ranges that one fetch reads through. The gap +/// costs bytes, a separate fetch costs a round trip. +fn gap_limit(window: u64) -> u64 { + (window / 16).clamp(64 * KIB, MIB) +} + +/// The size of a read-ahead fetch: large enough to be worth a round trip, +/// small enough that several fit in the window. +fn target_part(window: u64) -> u64 { + (window / 2).clamp(64 * KIB, 8 * MIB) +} + +/// The smallest range pushed into the decoder: a planned range, or the +/// byte-contiguous planned ranges of a column chunk that the decoder requests +/// as one range. The decoder serves a request only from one pushed buffer +/// that contains all of it. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Unit { + range: Range, + row_group: usize, + column: usize, +} + +impl Unit { + fn len(&self) -> u64 { + self.range.end - self.range.start + } +} + +/// The units of one row group that read-ahead has not taken, in plan order. +struct PlannedRowGroup { + row_group: usize, + units: VecDeque, + /// Total length of `units`. + bytes: u64, +} + +/// The units of one row group's planned ranges, in plan order. The ranges of +/// a column in `whole_chunks` merge into units of byte-contiguous ranges, at +/// the place of the first of them. +fn units_of(ranges: Vec, whole_chunks: &[bool]) -> Vec { + let mut units: Vec = Vec::with_capacity(ranges.len()); + // The index in `units` of the last unit of each whole-chunk column. + let mut last: HashMap = HashMap::new(); + for planned in ranges { + let column = planned.column; + if whole_chunks.get(column).copied().unwrap_or(false) { + if let Some(&idx) = last.get(&column) + && units[idx].range.end == planned.range.start + { + units[idx].range.end = planned.range.end; + continue; + } + last.insert(column, units.len()); + } + units.push(Unit { + range: planned.range, + row_group: planned.row_group, + column, + }); + } + units +} + +/// Merges ranges, sorted by start, into runs. A run takes the next range if +/// both are in the same row group, the gap between them is at most +/// `gap_limit`, and the run stays within `max_len` bytes. +fn merge_runs( + ranges: impl IntoIterator, usize)>, + gap_limit: u64, + max_len: u64, +) -> Vec<(Range, usize)> { + let mut runs: Vec<(Range, usize)> = vec![]; + for (range, row_group) in ranges { + if let Some((run, run_row_group)) = runs.last_mut() + && *run_row_group == row_group + && range.start <= run.end.saturating_add(gap_limit) + && range.end.max(run.end) - run.start <= max_len + { + run.end = run.end.max(range.end); + continue; + } + runs.push((range, row_group)); + } + runs +} + +/// One fetch: a contiguous byte range of one row group, read with one +/// [`AsyncFileReader::get_bytes`] call and pushed into the decoder as one +/// buffer. It includes the gaps between the units it was made for. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Run { + range: Range, + row_group: usize, + /// The decoder asked for bytes of this run, so it is pushed even if its + /// row group is no longer live. + required: bool, +} + +impl Run { + fn len(&self) -> u64 { + self.range.end - self.range.start + } + + fn contains(&self, range: &Range) -> bool { + self.range.start <= range.start && range.end <= self.range.end + } +} + +/// What a background fetch returns: the reader and the data. +type FetchResult = (Box, parquet::errors::Result); + +struct InFlight { + id: u64, + run: Run, + task: SpawnedTask, +} + +/// A run pushed into the decoder. The decoder holds slices of `data` until +/// it releases them. +struct Landed { + data: Bytes, + row_group: usize, +} + +/// Byte ranges that are fetched or in flight, so that read-ahead does not +/// fetch them again. +#[derive(Default)] +struct Coverage { + /// Keyed by `(start, end)`. The value is the row group and, for a + /// planned unit, its column. A range the decoder asked for has no column. + ranges: BTreeMap<(u64, u64), (usize, Option)>, + /// At least the length of the longest range in `ranges`, so that a + /// lookup stops after the ranges that can contain the requested range. + max_len: u64, +} + +impl Coverage { + fn insert(&mut self, range: &Range, row_group: usize, column: Option) { + self.max_len = self.max_len.max(range.end - range.start); + self.ranges + .insert((range.start, range.end), (row_group, column)); + } + + /// Whether one range in the coverage contains all of `range`. + fn contains(&self, range: &Range) -> bool { + self.ranges + .range(..=(range.start, u64::MAX)) + .rev() + .take_while(|((start, _), _)| start.saturating_add(self.max_len) >= range.end) + .any(|((_, end), _)| *end >= range.end) + } + + fn retain(&mut self, mut keep: impl FnMut(Range, usize, Option) -> bool) { + self.ranges + .retain(|&(start, end), &mut (row_group, column)| { + keep(start..end, row_group, column) + }); + } +} + +/// Accounts read-ahead in the [`MemoryPool`]: the runs pushed into the +/// decoder that it still holds, plus the runs in flight, each at its full +/// length including gaps. Bytes the decoder asks for are always reserved. +/// Speculative read-ahead takes only what the pool can grant. +pub(crate) struct ReadAheadMemory { + pool: Arc, + reservation: MemoryReservation, +} + +impl ReadAheadMemory { + /// Register a consumer in `pool`, or in an unbounded pool if `None`. + pub(crate) fn new(pool: Option>, partition: usize) -> Self { + let pool = pool.unwrap_or_else(|| Arc::new(UnboundedMemoryPool::default())); + let reservation = + MemoryConsumer::new(format!("ParquetReadAhead[{partition}]")).register(&pool); + Self { pool, reservation } + } + + /// Reserve bytes the decoder needs. Never fails and can exceed the pool + /// limit: the decoder cannot continue without these bytes. + fn reserve_required(&self, bytes: u64) { + self.reservation.grow(to_usize(bytes)); + } + + /// Bytes the pool can grant now. Unlimited if the pool has no limit or + /// does not report one (then [`Self::try_reserve_speculative`] decides). + fn available(&self) -> u64 { + match self.pool.memory_limit() { + MemoryLimit::Finite(limit) => { + limit.saturating_sub(self.pool.reserved()) as u64 + } + MemoryLimit::Infinite | MemoryLimit::Unknown => u64::MAX, + } + } + + /// Reserve bytes for speculative read-ahead. `false` if the pool refuses. + fn try_reserve_speculative(&self, bytes: u64) -> bool { + self.reservation.try_grow(to_usize(bytes)).is_ok() + } + + /// Set the reservation to what is held plus what is in flight. + fn sync(&self, held: u64, in_flight: u64) { + self.reservation + .resize(to_usize(held.saturating_add(in_flight))); + } +} + +fn to_usize(bytes: u64) -> usize { + usize::try_from(bytes).unwrap_or(usize::MAX) +} + +/// Read-ahead for a scan with `read_ahead_bytes`. It owns the fetching: it +/// reads the decoder's [`ScanPlan`] as far as the window reaches, merges the +/// planned ranges into runs, fetches each run with its own reader, and pushes +/// each run into the decoder as one buffer. It also fetches the ranges that +/// the decoder asks for. +/// +/// The window bounds the bytes of runs in flight plus the bytes of landed +/// runs that the decoder still holds. A read-ahead fetch starts when the +/// window has room for `min(target_part, rest of the next row group)` +/// bytes, so a small row group is fetched whole, and a large one in parts of +/// about [`target_part`] bytes. +pub(crate) struct ReadAhead { + window: u64, + /// The rest of the decoder's plan, after `lookahead`. + plan: ScanPlan, + /// The first planned range of the row group after the last one in + /// `planned`. + lookahead: Option, + /// Row groups pulled from `plan`, in plan order. + planned: VecDeque, + /// Per leaf column: the decoder requests the column chunk as one range. + whole_chunks: Vec, + covered: Coverage, + in_flight: Vec, + next_id: u64, + landed: Vec, + /// Idle readers. + readers: Vec>, + new_reader: ReaderFactory, + /// The first byte of each row group, sorted by it. + row_group_starts: Vec<(u64, usize)>, + /// No fetch has been made yet. + first_fetch: bool, + memory: ReadAheadMemory, + metrics: ReadAheadMetrics, +} + +impl ReadAhead { + #[expect(clippy::too_many_arguments)] + pub(crate) fn new( + window: u64, + plan: ScanPlan, + metadata: &ParquetMetaData, + whole_chunks: Vec, + reader: Box, + new_reader: ReaderFactory, + memory: ReadAheadMemory, + metrics: ReadAheadMetrics, + ) -> Self { + let mut row_group_starts: Vec<(u64, usize)> = metadata + .row_groups() + .iter() + .enumerate() + .filter_map(|(idx, row_group)| { + let start = row_group + .columns() + .iter() + .map(|column| column.byte_range().0) + .min()?; + Some((start, idx)) + }) + .collect(); + row_group_starts.sort_unstable(); + Self { + window, + plan, + lookahead: None, + planned: VecDeque::new(), + whole_chunks, + covered: Coverage::default(), + in_flight: vec![], + next_id: 0, + landed: vec![], + readers: vec![reader], + new_reader, + row_group_starts, + first_fetch: true, + memory, + metrics, + } + } + + /// Follow a rebuilt decoder: its plan covers only the row groups it + /// still reads, and lists the ranges it holds too. + /// + /// Building the decoder released the buffered bytes of the leaf columns + /// it does not read (`reads_leaf`), so their coverage goes. A later + /// rebuild that reads them again plans them, and read-ahead fetches them + /// again. A run in flight lands after the rebuild and stays buffered, + /// so its coverage stays. The ranges the decoder asked for belong to the + /// row group that just ended. + fn reset_plan( + &mut self, + plan: ScanPlan, + whole_chunks: Vec, + reads_leaf: impl Fn(usize) -> bool, + ) { + self.plan = plan; + self.lookahead = None; + self.planned.clear(); + self.whole_chunks = whole_chunks; + let in_flight = &self.in_flight; + self.covered.retain(|range, _, column| { + column.is_some_and(&reads_leaf) + || in_flight.iter().any(|fetch| fetch.run.contains(&range)) + }); + } + + /// The row group that contains byte `offset`. + fn row_group_of(&self, offset: u64) -> usize { + let idx = self + .row_group_starts + .partition_point(|&(start, _)| start <= offset); + self.row_group_starts + .get(idx.saturating_sub(1)) + .map_or(0, |&(_, row_group)| row_group) + } + + /// Pull the next row group from the plan into `planned`. `false` at the + /// end of the plan. + fn pull_row_group(&mut self) -> bool { + let Some(first) = self.lookahead.take().or_else(|| self.plan.next()) else { + return false; + }; + let row_group = first.row_group; + let mut ranges = vec![first]; + for next in self.plan.by_ref() { + if next.row_group != row_group { + self.lookahead = Some(next); + break; + } + ranges.push(next); + } + let units: VecDeque = units_of(ranges, &self.whole_chunks) + .into_iter() + .filter(|unit| !self.covered.contains(&unit.range)) + .collect(); + let bytes = units.iter().map(Unit::len).sum(); + self.planned.push_back(PlannedRowGroup { + row_group, + units, + bytes, + }); + true + } + + /// Whether the rest of the plan fits in `limit` bytes. Pulls at most + /// `limit` bytes of plan. + fn rest_fits(&mut self, limit: u64) -> bool { + let mut bytes = 0u64; + let mut idx = 0; + loop { + if idx == self.planned.len() && !self.pull_row_group() { + return true; + } + bytes = bytes.saturating_add(self.planned[idx].bytes); + if bytes > limit { + return false; + } + idx += 1; + } + } + + /// The bytes left to read ahead in the next row group that `keep` + /// accepts. Row groups before it are dropped. + fn next_row_group(&mut self, keep: &mut impl FnMut(usize) -> bool) -> Option { + loop { + if self.planned.is_empty() && !self.pull_row_group() { + return None; + } + let front = &self.planned[0]; + if front.bytes == 0 || !keep(front.row_group) { + self.planned.pop_front(); + continue; + } + return Some(front.bytes); + } + } + + /// Take units of the next row group in plan order: the first unit if it + /// fits in `free` bytes, then more while all fit in `limit` bytes. + fn take(&mut self, free: u64, limit: u64) -> Vec { + let Some(front) = self.planned.front_mut() else { + return vec![]; + }; + let mut taken = vec![]; + let mut bytes = 0u64; + while let Some(unit) = front.units.front() { + let len = unit.len(); + if self.covered.contains(&unit.range) { + front.bytes -= len; + front.units.pop_front(); + continue; + } + let max = if taken.is_empty() { free } else { limit }; + if bytes + len > max { + break; + } + bytes += len; + front.bytes -= len; + taken.extend(front.units.pop_front()); + } + taken + } + + /// Return units that [`Self::take`] took, in the order it took them. + fn untake(&mut self, units: Vec) { + let front = self.planned.front_mut().expect("units were taken from it"); + for unit in units.into_iter().rev() { + front.bytes += unit.len(); + front.units.push_front(unit); + } + } + + /// The runs that fetch `units`. + fn runs_of(&self, units: &[Unit]) -> Vec<(Range, usize)> { + let mut ranges: Vec<(Range, usize)> = units + .iter() + .map(|unit| (unit.range.clone(), unit.row_group)) + .collect(); + ranges.sort_by_key(|(range, _)| range.start); + merge_runs(ranges, gap_limit(self.window), u64::MAX) + } + + /// The bytes of landed runs plus the bytes of runs in flight. + fn charged(&self) -> (u64, u64) { + let landed = self.landed.iter().map(|l| l.data.len() as u64).sum(); + let in_flight = self.in_flight.iter().map(|f| f.run.len()).sum(); + (landed, in_flight) + } + + /// Start read-ahead fetches while the window has room. Ranges of row + /// groups that `keep` rejects are skipped: the decoder asks for them if + /// it reads them after all. + fn start_fetches(&mut self, mut keep: impl FnMut(usize) -> bool) -> Result<()> { + // The first fetch is made for `NeedsData`, see `fetch_required`. + if self.first_fetch { + return Ok(()); + } + let target = target_part(self.window); + while self.in_flight.len() < MAX_FETCHES_IN_FLIGHT { + let (landed, in_flight) = self.charged(); + let free = self + .window + .saturating_sub(landed + in_flight) + .min(self.memory.available()); + let Some(row_group_bytes) = self.next_row_group(&mut keep) else { + break; + }; + if free < target.min(row_group_bytes) { + break; + } + let mut units = self.take(free, free.min(target)); + if units.is_empty() { + if self.planned.front().is_some_and(|front| front.bytes == 0) { + continue; + } + break; + } + // The runs include the gaps between the units. + let runs = loop { + let runs = self.runs_of(&units); + let bytes: u64 = runs.iter().map(|(r, _)| r.end - r.start).sum(); + if bytes <= free || units.len() == 1 { + break runs; + } + let last = units.pop().expect("more than one unit"); + self.untake(vec![last]); + }; + let bytes = runs.iter().map(|(r, _)| r.end - r.start).sum(); + if !self.memory.try_reserve_speculative(bytes) { + self.untake(units); + break; + } + for unit in &units { + self.covered + .insert(&unit.range, unit.row_group, Some(unit.column)); + } + self.metrics.bytes_fetched.add(to_usize(bytes)); + for (range, row_group) in runs { + self.spawn(Run { + range, + row_group, + required: false, + })?; + } + } + Ok(()) + } + + /// Start fetches for the ranges that the decoder asked for and that no + /// fetch in flight contains. Returns the fetches to wait for: these and + /// the fetches in flight that contain the other ranges. + fn fetch_required(&mut self, needed: Vec>) -> Result> { + let mut wait = vec![]; + let mut missing = vec![]; + for range in needed { + match self.in_flight.iter().find(|f| f.run.contains(&range)) { + Some(fetch) => wait.push(fetch.id), + None => missing.push(range), + } + } + missing.sort_by_key(|range| range.start); + let missing: Vec<(Range, usize)> = missing + .into_iter() + .map(|range| { + let row_group = self.row_group_of(range.start); + (range, row_group) + }) + .collect(); + let runs = merge_runs(missing, gap_limit(self.window), target_part(self.window)); + for (range, row_group) in runs { + self.memory.reserve_required(range.end - range.start); + self.covered.insert(&range, row_group, None); + wait.push(self.spawn(Run { + range, + row_group, + required: true, + })?); + } + wait.sort_unstable(); + wait.dedup(); + Ok(wait) + } + + fn spawn(&mut self, run: Run) -> Result { + let mut reader = match self.readers.pop() { + Some(reader) => reader, + None => (self.new_reader)()?, + }; + let range = run.range.clone(); + let task = SpawnedTask::spawn(async move { + let data = reader.get_bytes(range).await; + (reader, data) + }); + let id = self.next_id; + self.next_id += 1; + self.in_flight.push(InFlight { id, run, task }); + Ok(id) + } + + fn return_reader(&mut self, reader: Box) { + if self.readers.len() < MAX_FETCHES_IN_FLIGHT { + self.readers.push(reader); + } + } + + /// Take the result of the finished fetch of `run`: keep its reader, and + /// push its data into `decoder` as one buffer if `push`. + fn land( + &mut self, + decoder: &mut ParquetPushDecoder, + run: Run, + joined: std::result::Result, + push: bool, + ) -> Result<()> { + let (reader, data) = + joined.map_err(|e| DataFusionError::External(Box::new(e)))?; + self.return_reader(reader); + let data = data?; + if data.len() as u64 != run.len() { + return internal_err!( + "fetched {} bytes for the {} bytes of {:?}", + data.len(), + run.len(), + run.range + ); + } + if push { + decoder.push_range(run.range, data.clone())?; + self.landed.push(Landed { + data, + row_group: run.row_group, + }); + } + Ok(()) + } + + /// Set the reservation to the landed runs the decoder still holds plus + /// the runs in flight. + fn sync(&mut self, live: impl Fn(usize) -> bool) { + // `data` is unique once the decoder released all its slices. Data + // that the reader shares with others (a cache, an in-memory store) is + // never unique: it is released with its row group. + self.landed + .retain(|landed| !landed.data.is_unique() && live(landed.row_group)); + let (landed, in_flight) = self.charged(); + self.memory.sync(landed, in_flight); + } +} + +/// Whether read-ahead should fetch ranges of `row_group`: it is the row +/// group being read, or it is still in the plan and the dynamic row-group +/// pruner (whose predicate only tightens) does not already prune it. +fn keep_row_group<'a>( + current_row_group: Option, + rg_plan: &'a VecDeque, + mut pruner: Option<&'a mut RowGroupPruner>, +) -> impl FnMut(usize) -> bool + 'a { + move |row_group| { + current_row_group == Some(row_group) + || (rg_plan.iter().any(|entry| entry.rg_index == row_group) + && !pruner + .as_deref_mut() + .is_some_and(|pruner| pruner.should_prune(&[row_group]))) + } +} + +/// Whether the decoder still reads `row_group`. +fn row_group_live( + current_row_group: Option, + rg_plan: &VecDeque, + row_group: usize, +) -> bool { + current_row_group == Some(row_group) + || rg_plan.iter().any(|entry| entry.rg_index == row_group) +} + +impl PushDecoderStreamState { + /// Driver for `read_ahead_bytes`: [`Self::transition`] with + /// `try_decode` and [`ReadAhead`]. + async fn transition_streaming(mut self) -> Option<(Result, Self)> { + let elapsed_compute = self.baseline_metrics.elapsed_compute().clone(); + let mut timer = elapsed_compute.timer(); + loop { + // Step 1: push the read-ahead fetches that have landed. Does not + // wait. + if let Err(e) = self.land_ready() { + return Some((Err(e), self)); + } + + // Step 2: row-group boundary work, then read-ahead (after pruning). + match self.handle_row_group_boundary() { + Ok(true) => return None, + Ok(false) => {} + Err(e) => return Some((Err(e), self)), + } + self.sync_memory(); + if let Err(e) = self.start_read_ahead() { + return Some((Err(e), self)); + } + + // Step 3: decode the next batch, or fetch what it needs. + let decoded = self.decoder.as_mut().expect("decoder present").try_decode(); + self.follow_decoder(); + match decoded { + Ok(DecodeResult::Data(batch)) => { + // Decoding can release buffered bytes. + self.sync_memory(); + self.copy_arrow_reader_metrics(); + let result = self.project_batch(&batch); + return Some((result, self)); + } + Ok(DecodeResult::NeedsData(ranges)) => { + if let Err(e) = self.fetch_needed(ranges, &mut timer).await { + return Some((Err(e), self)); + } + } + Ok(DecodeResult::Finished) => { + self.finish_row_groups(); + return None; + } + Err(e) => return Some((Err(DataFusionError::from(e)), self)), + } + } + } + + /// Push the fetches that have landed into the decoder. Does not wait. + fn land_ready(&mut self) -> Result<()> { + let mut idx = 0; + loop { + let read_ahead = self.read_ahead.as_mut().expect("read-ahead is set"); + let Some(fetch) = read_ahead.in_flight.get_mut(idx) else { + break; + }; + match (&mut fetch.task).now_or_never() { + Some(joined) => { + let fetch = read_ahead.in_flight.swap_remove(idx); + self.land(fetch.run, joined)?; + } + None => idx += 1, + } + } + self.sync_memory(); + Ok(()) + } + + /// Wait for the fetches `ids` and push them into the decoder. + async fn land_fetches(&mut self, ids: &[u64]) -> Result<()> { + for &id in ids { + let read_ahead = self.read_ahead.as_mut().expect("read-ahead is set"); + let Some(idx) = read_ahead.in_flight.iter().position(|f| f.id == id) else { + continue; + }; + let mut fetch = read_ahead.in_flight.swap_remove(idx); + let joined = (&mut fetch.task).await; + self.land(fetch.run, joined)?; + } + Ok(()) + } + + /// Push a finished fetch into the decoder, unless read-ahead fetched it + /// for a row group that the decoder does not read. + fn land( + &mut self, + run: Run, + joined: std::result::Result, + ) -> Result<()> { + let push = run.required + || row_group_live(self.active_row_group(), &self.rg_plan, run.row_group); + let decoder = self.decoder.as_mut().expect("decoder present"); + let read_ahead = self.read_ahead.as_mut().expect("read-ahead is set"); + read_ahead.land(decoder, run, joined, push) + } + + /// The row group the decoder reads. `rg_plan` does not hold it. + fn active_row_group(&self) -> Option { + self.decoder.as_ref().and_then(|d| d.active_row_group()) + } + + /// Start read-ahead fetches while the window has room. + fn start_read_ahead(&mut self) -> Result<()> { + let current = self.active_row_group(); + let Some(read_ahead) = self.read_ahead.as_mut() else { + return Ok(()); + }; + read_ahead.start_fetches(keep_row_group( + current, + &self.rg_plan, + self.row_group_pruner.as_mut(), + )) + } + + /// Fetch what the decoder asked for and wait for it, while read-ahead + /// fetches go on. A range that a read-ahead fetch in flight contains is + /// not fetched again. The first fetch of a plan larger than the window + /// starts no read-ahead until it lands, for time to first batch. + /// + /// The wait is I/O: it pauses `compute` and counts as + /// `read_ahead_wait_time`. + async fn fetch_needed( + &mut self, + needed: Vec>, + compute: &mut ScopedTimerGuard<'_>, + ) -> Result<()> { + let read_ahead = self.read_ahead.as_mut().expect("read-ahead is set"); + let wait = read_ahead.fetch_required(needed)?; + if !read_ahead.first_fetch || read_ahead.rest_fits(read_ahead.window) { + read_ahead.first_fetch = false; + self.start_read_ahead()?; + } + let wait_time = self + .read_ahead + .as_ref() + .expect("read-ahead is set") + .metrics + .wait_time + .clone(); + compute.stop(); + let wait_timer = wait_time.timer(); + let result = self.land_fetches(&wait).await; + wait_timer.done(); + compute.restart(); + self.read_ahead + .as_mut() + .expect("read-ahead is set") + .first_fetch = false; + self.sync_memory(); + result + } + + /// Set the read-ahead memory reservation to the landed runs that the + /// decoder still holds plus the runs in flight. + fn sync_memory(&mut self) { + let current = self.active_row_group(); + let Some(read_ahead) = self.read_ahead.as_mut() else { + return; + }; + let rg_plan = &self.rg_plan; + read_ahead.sync(|row_group| row_group_live(current, rg_plan, row_group)); + } + + /// Per leaf column: whether the decoder requests the column chunk as one + /// range. With [`RequestGranularity::RowGroup`] it requests every column + /// that way. Otherwise only the columns of a [`RowFilter`], which it reads + /// a row group at a time. + /// + /// [`RequestGranularity::RowGroup`]: parquet::arrow::push_decoder::RequestGranularity::RowGroup + pub(crate) fn whole_chunk_leaves( + num_leaves: usize, + row_group_granularity: bool, + filter: Option<&RowFilterContext>, + ) -> Vec { + (0..num_leaves) + .map(|leaf| { + row_group_granularity || filter.is_some_and(|ctx| ctx.reads_leaf(leaf)) + }) + .collect() + } +} + /// Returns `batch` with its rows in reverse order. fn reverse_batch_rows(batch: &RecordBatch) -> Result { let num_rows = u32::try_from(batch.num_rows()).map_err(|_| { @@ -976,4 +1874,397 @@ mod tests { assert!(!pruner.should_prune(&[1])); assert!(!pruner.should_prune(&[2])); } + + #[test] + fn read_ahead_memory_tracks_held_and_in_flight() { + use datafusion_execution::memory_pool::GreedyMemoryPool; + let pool: Arc = Arc::new(GreedyMemoryPool::new(100)); + let memory = ReadAheadMemory::new(Some(Arc::clone(&pool)), 0); + // Required bytes can exceed the limit; speculative bytes cannot. + memory.reserve_required(150); + assert_eq!(pool.reserved(), 150); + assert_eq!(memory.available(), 0); + assert!(!memory.try_reserve_speculative(1)); + memory.sync(40, 20); + assert_eq!(pool.reserved(), 60); + assert_eq!(memory.available(), 40); + assert!(memory.try_reserve_speculative(40)); + assert!(!memory.try_reserve_speculative(1)); + assert_eq!(pool.reserved(), 100); + drop(memory); + assert_eq!(pool.reserved(), 0); + } + + /// Read-ahead scheduling, fetching and accounting, on in-memory files. + mod read_ahead { + use super::*; + use std::sync::Mutex; + + use datafusion_execution::memory_pool::GreedyMemoryPool; + use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet; + use futures::future::BoxFuture; + use parquet::arrow::arrow_reader::ArrowReaderOptions; + use parquet::arrow::push_decoder::RequestGranularity; + use parquet::file::metadata::PageIndexPolicy; + use parquet::schema::types::ColumnPath; + + /// Serves a file from memory and records the range of every call. + struct MemoryReader { + file: Bytes, + gets: Arc>>>, + /// Return a copy, which the caller owns alone, or a slice of + /// `file`, which is never unique. + copy: bool, + } + + impl AsyncFileReader for MemoryReader { + fn get_bytes( + &mut self, + range: Range, + ) -> BoxFuture<'_, parquet::errors::Result> { + self.gets.lock().unwrap().push(range.clone()); + let data = self.file.slice(range.start as usize..range.end as usize); + let data = if self.copy { + Bytes::copy_from_slice(&data) + } else { + data + }; + async move { Ok(data) }.boxed() + } + + fn get_byte_ranges( + &mut self, + _ranges: Vec>, + ) -> BoxFuture<'_, parquet::errors::Result>> { + panic!("read-ahead fetches one range per call") + } + + fn get_metadata<'a>( + &'a mut self, + _options: Option<&'a ArrowReaderOptions>, + ) -> BoxFuture<'a, parquet::errors::Result>> + { + panic!("read-ahead does not read metadata") + } + } + + /// `rows` rows of the `Int64` columns `names`, in row groups of + /// `row_group_rows` rows and pages of 1024 rows. Only the columns in + /// `dictionary` are dictionary encoded. + fn file( + names: &[&str], + dictionary: &[&str], + rows: i64, + row_group_rows: usize, + ) -> (Bytes, ArrowReaderMetadata) { + let schema = Arc::new(Schema::new( + names + .iter() + .map(|name| Field::new(*name, DataType::Int64, false)) + .collect::>(), + )); + let columns = names + .iter() + .enumerate() + .map(|(idx, _)| { + Arc::new(Int64Array::from_iter_values( + (0..rows).map(|v| v.wrapping_mul(idx as i64 + 7919)), + )) as _ + }) + .collect(); + let batch = RecordBatch::try_new(Arc::clone(&schema), columns).unwrap(); + let mut props = WriterProperties::builder() + .set_dictionary_enabled(false) + .set_max_row_group_row_count(Some(row_group_rows)) + .set_data_page_row_count_limit(1024) + .set_write_batch_size(1024); + for name in dictionary { + props = + props.set_column_dictionary_enabled(ColumnPath::from(*name), true); + } + let mut buf = Vec::new(); + let mut writer = + ArrowWriter::try_new(&mut buf, schema, Some(props.build())).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + let file = Bytes::from(buf); + let options = ArrowReaderOptions::new() + .with_page_index_policy(PageIndexPolicy::Required); + let metadata = ArrowReaderMetadata::load(&file, options).unwrap(); + (file, metadata) + } + + struct Setup { + decoder: ParquetPushDecoder, + read_ahead: ReadAhead, + pool: Arc, + gets: Arc>>>, + } + + /// A batch-granular decoder of `leaves` and a read-ahead for it, + /// past its first fetch. + fn setup( + file: &Bytes, + metadata: &ArrowReaderMetadata, + leaves: &[usize], + window: u64, + copy: bool, + ) -> Setup { + let projection = ProjectionMask::leaves( + metadata.metadata().file_metadata().schema_descr(), + leaves.iter().copied(), + ); + let decoder = ParquetPushDecoderBuilder::new_with_metadata(metadata.clone()) + .with_projection(projection) + .with_request_granularity(RequestGranularity::Batch) + .build() + .unwrap(); + let gets = Arc::new(Mutex::new(vec![])); + let new_reader: ReaderFactory = { + let (file, gets) = (file.clone(), Arc::clone(&gets)); + Box::new(move || { + Ok(Box::new(MemoryReader { + file: file.clone(), + gets: Arc::clone(&gets), + copy, + })) + }) + }; + let pool: Arc = Arc::new(GreedyMemoryPool::new(1 << 30)); + let num_leaves = metadata + .metadata() + .file_metadata() + .schema_descr() + .num_columns(); + let mut read_ahead = ReadAhead::new( + window, + decoder.scan_plan(), + metadata.metadata(), + vec![false; num_leaves], + new_reader().unwrap(), + new_reader, + ReadAheadMemory::new(Some(Arc::clone(&pool)), 0), + ReadAheadMetrics::new(&ExecutionPlanMetricsSet::new(), 0, "file"), + ); + read_ahead.first_fetch = false; + Setup { + decoder, + read_ahead, + pool, + gets, + } + } + + impl Setup { + /// The ranges of the fetches in flight, sorted. + fn in_flight(&self) -> Vec> { + let mut runs: Vec<_> = self + .read_ahead + .in_flight + .iter() + .map(|fetch| fetch.run.range.clone()) + .collect(); + runs.sort_by_key(|range| range.start); + runs + } + + /// Wait for the fetches in flight and push them into the decoder. + async fn land_all(&mut self) { + for fetch in std::mem::take(&mut self.read_ahead.in_flight) { + let joined = fetch.task.await; + self.read_ahead + .land(&mut self.decoder, fetch.run, joined, true) + .unwrap(); + } + } + + /// The ranges fetched so far, sorted. + fn gets(&self) -> Vec> { + let mut gets = self.gets.lock().unwrap().clone(); + gets.sort_by_key(|range| range.start); + gets + } + } + + /// The byte range of column `column` of row group `row_group`. + fn chunk( + metadata: &ArrowReaderMetadata, + row_group: usize, + column: usize, + ) -> Range { + let (start, len) = metadata + .metadata() + .row_group(row_group) + .column(column) + .byte_range(); + start..start + len + } + + /// Row groups that fit in a part are fetched whole, one fetch each, + /// up to `MAX_FETCHES_IN_FLIGHT`. + #[tokio::test] + async fn small_row_groups_are_fetched_whole() { + let (file, metadata) = file(&["a"], &[], 10_000, 1_000); + let mut setup = setup(&file, &metadata, &[0], MIB, true); + setup.read_ahead.start_fetches(|_| true).unwrap(); + let expected: Vec<_> = (0..MAX_FETCHES_IN_FLIGHT) + .map(|row_group| chunk(&metadata, row_group, 0)) + .collect(); + assert_eq!(setup.in_flight(), expected); + setup.land_all().await; + assert_eq!(setup.gets(), expected); + + // The two row groups left start once fetches land. + setup.read_ahead.start_fetches(|_| true).unwrap(); + assert_eq!( + setup.in_flight(), + vec![chunk(&metadata, 8, 0), chunk(&metadata, 9, 0)] + ); + } + + /// A row group larger than a part is fetched in parts of at most + /// `target_part` bytes, while the window has room for a part. + #[tokio::test] + async fn large_row_group_is_fetched_in_parts() { + let (file, metadata) = file(&["a"], &[], 200_000, 200_000); + let window = 256 * KIB; + let target = target_part(window); + assert_eq!(target, 128 * KIB); + let mut setup = setup(&file, &metadata, &[0], window, true); + setup.read_ahead.start_fetches(|_| true).unwrap(); + + // The parts are whole pages, taken while they fit in the target. + let pages = metadata + .metadata() + .page_index_for_row_group(0) + .page_locations(0) + .unwrap() + .clone(); + let mut parts: Vec> = vec![]; + let mut part: Option> = None; + for page in &pages { + let range = page.offset as u64 + ..page.offset as u64 + page.compressed_page_size as u64; + part = match part { + Some(p) if range.end - p.start <= target => Some(p.start..range.end), + Some(p) => { + parts.push(p); + Some(range) + } + None => Some(range), + }; + } + parts.extend(part); + let first_two = parts[..2].to_vec(); + assert!(first_two.iter().all(|p| p.end - p.start <= target)); + assert!(first_two[0].end - first_two[0].start > target - 16 * KIB); + // The window has room for two parts only. + assert_eq!(setup.in_flight(), first_two); + assert_eq!( + setup.pool.reserved() as u64, + first_two.iter().map(|p| p.end - p.start).sum::() + ); + setup.land_all().await; + assert_eq!(setup.gets(), first_two); + // The decoder holds both parts, so the window is still full. + setup.read_ahead.sync(|_| true); + setup.read_ahead.start_fetches(|_| true).unwrap(); + assert_eq!(setup.in_flight(), vec![]); + } + + /// A column that is not read and is smaller than the gap limit is + /// fetched through, and its bytes are charged. + #[tokio::test] + async fn gap_is_fetched_and_charged() { + let (file, metadata) = file(&["a", "b", "c"], &["b"], 4_000, 4_000); + let (a, b, c) = ( + chunk(&metadata, 0, 0), + chunk(&metadata, 0, 1), + chunk(&metadata, 0, 2), + ); + assert_eq!((a.end, b.end), (b.start, c.start)); + assert!(b.end - b.start < gap_limit(MIB)); + let mut setup = setup(&file, &metadata, &[0, 2], MIB, true); + setup.read_ahead.start_fetches(|_| true).unwrap(); + assert_eq!(setup.in_flight(), vec![a.start..c.end]); + assert_eq!(setup.pool.reserved() as u64, c.end - a.start); + setup.land_all().await; + assert_eq!(setup.gets(), vec![a.start..c.end]); + } + + /// Decode `decoder` to the end. + fn decode_all(decoder: &mut ParquetPushDecoder) -> usize { + let mut rows = 0; + loop { + match decoder.try_decode().unwrap() { + DecodeResult::Data(batch) => rows += batch.num_rows(), + DecodeResult::NeedsData(ranges) => { + panic!("read-ahead fetched the whole file, not {ranges:?}") + } + DecodeResult::Finished => return rows, + } + } + } + + /// A landed run stays charged until the decoder releases it. + #[tokio::test] + async fn reservation_drops_after_the_decoder_releases() { + let (file, metadata) = file(&["a"], &[], 4_000, 4_000); + let whole = chunk(&metadata, 0, 0); + let mut setup = setup(&file, &metadata, &[0], MIB, true); + setup.read_ahead.start_fetches(|_| true).unwrap(); + setup.land_all().await; + setup.read_ahead.sync(|_| true); + assert_eq!(setup.pool.reserved() as u64, whole.end - whole.start); + assert_eq!(decode_all(&mut setup.decoder), 4_000); + setup.read_ahead.sync(|_| true); + assert_eq!(setup.pool.reserved(), 0); + } + + /// A reader that shares its data with others returns data that is + /// never unique. It stays charged until its row group is done. + #[tokio::test] + async fn shared_data_is_released_with_its_row_group() { + let (file, metadata) = file(&["a"], &[], 4_000, 4_000); + let whole = chunk(&metadata, 0, 0); + let mut setup = setup(&file, &metadata, &[0], MIB, false); + setup.read_ahead.start_fetches(|_| true).unwrap(); + setup.land_all().await; + assert_eq!(decode_all(&mut setup.decoder), 4_000); + setup.read_ahead.sync(|_| true); + assert_eq!(setup.pool.reserved() as u64, whole.end - whole.start); + setup.read_ahead.sync(|_| false); + assert_eq!(setup.pool.reserved(), 0); + } + + /// A requested range inside a fetch in flight waits for that fetch. + /// Other requested ranges are fetched, always reserved. + #[tokio::test] + async fn required_ranges_reuse_fetches_in_flight() { + let (file, metadata) = file(&["a"], &[], 10_000, 1_000); + let pool: Arc = Arc::new(GreedyMemoryPool::new(1)); + let mut setup = setup(&file, &metadata, &[0], MIB, true); + setup.read_ahead.memory = ReadAheadMemory::new(Some(Arc::clone(&pool)), 0); + setup.read_ahead.first_fetch = true; + let rg0 = chunk(&metadata, 0, 0); + let inner = rg0.start + 10..rg0.end - 10; + let wait = setup + .read_ahead + .fetch_required([inner.clone()].to_vec()) + .unwrap(); + assert_eq!(wait.len(), 1); + assert_eq!(setup.in_flight(), vec![inner.clone()]); + assert_eq!(pool.reserved() as u64, inner.end - inner.start); + // The pool has no room for speculative bytes. + setup.read_ahead.first_fetch = false; + setup.read_ahead.start_fetches(|_| true).unwrap(); + assert_eq!(setup.in_flight(), vec![inner.clone()]); + let again = setup + .read_ahead + .fetch_required(std::iter::once(inner.start + 1..inner.end - 1).collect()) + .unwrap(); + assert_eq!(again, wait); + assert_eq!(setup.in_flight(), vec![inner]); + } + } } diff --git a/datafusion/datasource-parquet/src/source.rs b/datafusion/datasource-parquet/src/source.rs index 09083cb19de24..d59a322cf1b70 100644 --- a/datafusion/datasource-parquet/src/source.rs +++ b/datafusion/datasource-parquet/src/source.rs @@ -658,6 +658,11 @@ impl FileSource for ParquetSource { .table_parquet_options .global .row_group_range_assignment, + read_ahead_bytes: self + .table_parquet_options + .global + .read_ahead_bytes + .map(|bytes| bytes as u64), reverse_row_groups: self.reverse_row_groups, reverse_rows: self.reverse_rows, memory_pool: self.memory_pool.clone(), From 5be02a23c3c301012ac4de64437ac4ded3038d4d Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:07:52 -0600 Subject: [PATCH 5/6] Fetch Parquet dictionary pages as runs of their own The decoder holds each column chunk's dictionary page until the row group ends. A run that merged the dictionary page with data pages stayed allocated, and charged in the read-ahead window, as long as the decoder held any slice of it. On large row groups this filled the window: read-ahead stopped and the decoder fell back to small per-batch fetches. TPC-H Q6 on 128 MB row groups with a 4 MiB window took 11.9 s with 3,057 GETs under 64 KiB, and 2.9 s with 304 such GETs when dictionary pages are fetched alone. `merge_runs` now never merges a dictionary-page unit with a neighbour. `ReadAhead` records the dictionary pages of the plan per file, and a requested range that is a dictionary page is a run of its own too. The units of whole-chunk columns are unchanged: the decoder requests their dictionary page with the column chunk. Co-Authored-By: Claude Opus 5.5 --- .../datasource-parquet/src/push_decoder.rs | 168 ++++++++++++++++-- 1 file changed, 158 insertions(+), 10 deletions(-) diff --git a/datafusion/datasource-parquet/src/push_decoder.rs b/datafusion/datasource-parquet/src/push_decoder.rs index 5777949d7debb..a97e4c3213aa6 100644 --- a/datafusion/datasource-parquet/src/push_decoder.rs +++ b/datafusion/datasource-parquet/src/push_decoder.rs @@ -40,8 +40,8 @@ use parquet::arrow::arrow_reader::{ }; use parquet::arrow::async_reader::AsyncFileReader; use parquet::arrow::push_decoder::{ - ParquetPushDecoder, ParquetPushDecoderBuilder, PlannedRange, RowGroupSelection, - ScanPlan, + PageKind, ParquetPushDecoder, ParquetPushDecoderBuilder, PlannedRange, + RowGroupSelection, ScanPlan, }; use parquet::file::metadata::ParquetMetaData; @@ -893,6 +893,8 @@ struct Unit { range: Range, row_group: usize, column: usize, + /// A dictionary page, which is fetched as its own run. See [`merge_runs`]. + dictionary: bool, } impl Unit { @@ -911,7 +913,8 @@ struct PlannedRowGroup { /// The units of one row group's planned ranges, in plan order. The ranges of /// a column in `whole_chunks` merge into units of byte-contiguous ranges, at -/// the place of the first of them. +/// the place of the first of them. The dictionary page of such a column is +/// inside its unit, as it is inside the decoder's request. fn units_of(ranges: Vec, whole_chunks: &[bool]) -> Vec { let mut units: Vec = Vec::with_capacity(ranges.len()); // The index in `units` of the last unit of each whole-chunk column. @@ -923,6 +926,7 @@ fn units_of(ranges: Vec, whole_chunks: &[bool]) -> Vec { && units[idx].range.end == planned.range.start { units[idx].range.end = planned.range.end; + units[idx].dictionary = false; continue; } last.insert(column, units.len()); @@ -931,6 +935,7 @@ fn units_of(ranges: Vec, whole_chunks: &[bool]) -> Vec { range: planned.range, row_group: planned.row_group, column, + dictionary: planned.kind == PageKind::Dictionary, }); } units @@ -939,14 +944,24 @@ fn units_of(ranges: Vec, whole_chunks: &[bool]) -> Vec { /// Merges ranges, sorted by start, into runs. A run takes the next range if /// both are in the same row group, the gap between them is at most /// `gap_limit`, and the run stays within `max_len` bytes. +/// +/// A dictionary page (the `bool`) is always a run of its own. The decoder +/// holds a column chunk's dictionary page until the row group ends, and any +/// slice it holds keeps the whole run's allocation, and its charge, alive. +/// Merged with data pages, the dictionary page would keep the window full +/// for the rest of a large row group. fn merge_runs( - ranges: impl IntoIterator, usize)>, + ranges: impl IntoIterator, usize, bool)>, gap_limit: u64, max_len: u64, ) -> Vec<(Range, usize)> { let mut runs: Vec<(Range, usize)> = vec![]; - for (range, row_group) in ranges { - if let Some((run, run_row_group)) = runs.last_mut() + // Whether the last run is a dictionary page. + let mut last_alone = false; + for (range, row_group, alone) in ranges { + if !alone + && !last_alone + && let Some((run, run_row_group)) = runs.last_mut() && *run_row_group == row_group && range.start <= run.end.saturating_add(gap_limit) && range.end.max(run.end) - run.start <= max_len @@ -955,6 +970,7 @@ fn merge_runs( continue; } runs.push((range, row_group)); + last_alone = alone; } runs } @@ -1115,6 +1131,11 @@ pub(crate) struct ReadAhead { new_reader: ReaderFactory, /// The first byte of each row group, sorted by it. row_group_starts: Vec<(u64, usize)>, + /// The `(start, end)` of the dictionary-page units of the row groups in + /// `pulled`, so that a requested dictionary page is a run of its own too. + dictionaries: HashSet<(u64, u64)>, + /// The row groups pulled from a plan so far. + pulled: HashSet, /// No fetch has been made yet. first_fetch: bool, memory: ReadAheadMemory, @@ -1160,6 +1181,8 @@ impl ReadAhead { readers: vec![reader], new_reader, row_group_starts, + dictionaries: HashSet::new(), + pulled: HashSet::new(), first_fetch: true, memory, metrics, @@ -1217,7 +1240,15 @@ impl ReadAhead { } ranges.push(next); } - let units: VecDeque = units_of(ranges, &self.whole_chunks) + self.pulled.insert(row_group); + let units = units_of(ranges, &self.whole_chunks); + self.dictionaries.extend( + units + .iter() + .filter(|unit| unit.dictionary) + .map(|unit| (unit.range.start, unit.range.end)), + ); + let units: VecDeque = units .into_iter() .filter(|unit| !self.covered.contains(&unit.range)) .collect(); @@ -1300,11 +1331,11 @@ impl ReadAhead { /// The runs that fetch `units`. fn runs_of(&self, units: &[Unit]) -> Vec<(Range, usize)> { - let mut ranges: Vec<(Range, usize)> = units + let mut ranges: Vec<(Range, usize, bool)> = units .iter() - .map(|unit| (unit.range.clone(), unit.row_group)) + .map(|unit| (unit.range.clone(), unit.row_group, unit.dictionary)) .collect(); - ranges.sort_by_key(|(range, _)| range.start); + ranges.sort_by_key(|(range, _, _)| range.start); merge_runs(ranges, gap_limit(self.window), u64::MAX) } @@ -1394,6 +1425,18 @@ impl ReadAhead { (range, row_group) }) .collect(); + // Pull the plan through the requested row groups to learn their + // dictionary pages. + for (_, row_group) in &missing { + while !self.pulled.contains(row_group) && self.pull_row_group() {} + } + let missing: Vec<(Range, usize, bool)> = missing + .into_iter() + .map(|(range, row_group)| { + let dictionary = self.dictionaries.contains(&(range.start, range.end)); + (range, row_group, dictionary) + }) + .collect(); let runs = merge_runs(missing, gap_limit(self.window), target_part(self.window)); for (range, row_group) in runs { self.memory.reserve_required(range.end - range.start); @@ -2100,6 +2143,111 @@ mod tests { start..start + len } + /// One row group of 400,000 rows of a dictionary-encoded column with + /// 1,000 distinct values, in pages of 1024 rows. + fn dictionary_file() -> (Bytes, ArrowReaderMetadata) { + let schema = + Arc::new(Schema::new(vec![Field::new("a", DataType::Int64, false)])); + let a = Int64Array::from_iter_values((0..400_000).map(|v| v % 1000)); + let batch = + RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(a)]).unwrap(); + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(400_000)) + .set_data_page_row_count_limit(1024) + .set_write_batch_size(1024) + .build(); + let mut buf = Vec::new(); + let mut writer = ArrowWriter::try_new(&mut buf, schema, Some(props)).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + let file = Bytes::from(buf); + let options = ArrowReaderOptions::new() + .with_page_index_policy(PageIndexPolicy::Required); + let metadata = ArrowReaderMetadata::load(&file, options).unwrap(); + (file, metadata) + } + + /// The dictionary page and the data pages of column 0 of row group 0. + fn dictionary_and_pages( + metadata: &ArrowReaderMetadata, + ) -> (Range, Vec>) { + let pages: Vec> = metadata + .metadata() + .page_index_for_row_group(0) + .page_locations(0) + .unwrap() + .iter() + .map(|page| { + page.offset as u64 + ..page.offset as u64 + page.compressed_page_size as u64 + }) + .collect(); + let dictionary = chunk(metadata, 0, 0).start..pages[0].start; + assert!(!dictionary.is_empty()); + (dictionary, pages) + } + + /// A dictionary page is fetched as a run of its own. The decoder holds + /// it until the row group ends, but releases the data runs before + /// that, and their charge with them. + #[tokio::test] + async fn dictionary_page_is_its_own_run() { + let (file, metadata) = dictionary_file(); + let (dictionary, pages) = dictionary_and_pages(&metadata); + let whole = chunk(&metadata, 0, 0); + // Two parts fit in the window, and the row group does not. + let window = (whole.end - whole.start) / 2; + let target = target_part(window); + assert_eq!(target, window / 2); + let mut setup = setup(&file, &metadata, &[0], window, true); + setup.read_ahead.start_fetches(|_| true).unwrap(); + let runs = setup.in_flight(); + assert_eq!(runs.len(), 3, "{runs:?}"); + assert_eq!(runs[0], dictionary); + // The data runs are whole pages, in order, from the first page. + assert_eq!(runs[1].start, pages[0].start); + assert_eq!(runs[2].start, runs[1].end); + assert!(pages.iter().any(|page| page.end == runs[1].end)); + assert!(pages.iter().any(|page| page.end == runs[2].end)); + setup.land_all().await; + + // Decode up to the first page that was not fetched. + loop { + match setup.decoder.try_decode().unwrap() { + DecodeResult::Data(_) => {} + DecodeResult::NeedsData(ranges) => { + assert_eq!(ranges[0].start, runs[2].end); + break; + } + DecodeResult::Finished => panic!("the row group was not fetched"), + } + } + setup.read_ahead.sync(|_| true); + let landed: Vec = setup + .read_ahead + .landed + .iter() + .map(|landed| landed.data.len() as u64) + .collect(); + let len = |range: &Range| range.end - range.start; + assert_eq!(landed[0], len(&dictionary)); + assert!(!landed.contains(&len(&runs[1])), "{landed:?}"); + assert_eq!(setup.pool.reserved() as u64, landed.iter().sum::()); + + // A requested dictionary page is a run of its own too. + let mut setup = setup_for(&file, &metadata, window); + let needed = vec![dictionary.clone(), pages[0].clone()]; + setup.read_ahead.fetch_required(needed).unwrap(); + assert_eq!(setup.in_flight(), vec![dictionary, pages[0].clone()]); + } + + /// [`setup`] of column 0, before its first fetch. + fn setup_for(file: &Bytes, metadata: &ArrowReaderMetadata, window: u64) -> Setup { + let mut setup = setup(file, metadata, &[0], window, true); + setup.read_ahead.first_fetch = true; + setup + } + /// Row groups that fit in a part are fetched whole, one fetch each, /// up to `MAX_FETCHES_IN_FLIGHT`. #[tokio::test] From 786b643486b24a45b6c8cc2ca3520158ad076185 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:11:57 -0600 Subject: [PATCH 6/6] Read ahead a whole Parquet row group when it fits in the free window A read-ahead take was capped at `target_part = min(8 MiB, window / 2)`, so a row group larger than that was split even when the window had room for all of it. Each part costs one GET per column chunk it reads. With a 1 MiB window, `target_part` is 512 KiB while a TPC-H row group projection is about 868 KiB, and TPC-H Q6 on small row groups made 3,161 GETs where `main` makes 525. A take now includes the rest of the next row group when it fits in the free window, whatever `target_part` is. Row groups larger than the free window are still read in parts of `target_part`. The start condition is unchanged: `free >= min(target_part, rest of the next row group)`. The rest of the plan is never smaller than the rest of that row group, so it does not lower the bound. Co-Authored-By: Claude Opus 5.5 --- .../datasource-parquet/src/push_decoder.rs | 47 +++++++++++++++++-- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/datafusion/datasource-parquet/src/push_decoder.rs b/datafusion/datasource-parquet/src/push_decoder.rs index a97e4c3213aa6..4234dce99cf1d 100644 --- a/datafusion/datasource-parquet/src/push_decoder.rs +++ b/datafusion/datasource-parquet/src/push_decoder.rs @@ -878,8 +878,9 @@ fn gap_limit(window: u64) -> u64 { (window / 16).clamp(64 * KIB, MIB) } -/// The size of a read-ahead fetch: large enough to be worth a round trip, -/// small enough that several fit in the window. +/// The size of a read-ahead fetch of a row group that does not fit in the +/// free window: large enough to be worth a round trip, small enough that +/// several fit in the window. fn target_part(window: u64) -> u64 { (window / 2).clamp(64 * KIB, 8 * MIB) } @@ -1109,8 +1110,8 @@ fn to_usize(bytes: u64) -> usize { /// The window bounds the bytes of runs in flight plus the bytes of landed /// runs that the decoder still holds. A read-ahead fetch starts when the /// window has room for `min(target_part, rest of the next row group)` -/// bytes, so a small row group is fetched whole, and a large one in parts of -/// about [`target_part`] bytes. +/// bytes. It takes the rest of the row group if that fits in the free +/// window, and a part of about [`target_part`] bytes if not. pub(crate) struct ReadAhead { window: u64, /// The rest of the decoder's plan, after `lookahead`. @@ -1364,10 +1365,19 @@ impl ReadAhead { let Some(row_group_bytes) = self.next_row_group(&mut keep) else { break; }; + // The rest of the plan is at least the rest of this row group, + // so it does not lower this bound. if free < target.min(row_group_bytes) { break; } - let mut units = self.take(free, free.min(target)); + // Split a row group into parts only if it does not fit: each + // part costs a GET per column chunk it reads. + let limit = if row_group_bytes <= free { + free + } else { + free.min(target) + }; + let mut units = self.take(free, limit); if units.is_empty() { if self.planned.front().is_some_and(|front| front.bytes == 0) { continue; @@ -2248,6 +2258,33 @@ mod tests { setup } + /// A row group larger than a part but within the free window is + /// fetched whole, one GET per column chunk, not in parts. + #[tokio::test] + async fn row_group_that_fits_the_window_is_fetched_whole() { + let (file, metadata) = file(&["a", "b", "c", "d", "e"], &[], 10_000, 10_000); + let window = 384 * KIB; + let target = target_part(window); + let (a, c, e) = ( + chunk(&metadata, 0, 0), + chunk(&metadata, 0, 2), + chunk(&metadata, 0, 4), + ); + let len = |range: &Range| range.end - range.start; + let projected = len(&a) + len(&c) + len(&e); + assert!(target < projected && projected <= window, "{projected}"); + // `b` and `d` are gaps too large to read through. + assert!(len(&chunk(&metadata, 0, 1)) > gap_limit(window)); + assert!(len(&chunk(&metadata, 0, 3)) > gap_limit(window)); + let mut setup = setup(&file, &metadata, &[0, 2, 4], window, true); + setup.read_ahead.start_fetches(|_| true).unwrap(); + let expected = vec![a, c, e]; + assert_eq!(setup.in_flight(), expected); + setup.land_all().await; + assert_eq!(setup.gets(), expected); + assert_eq!(setup.pool.reserved() as u64, projected); + } + /// Row groups that fit in a part are fetched whole, one fetch each, /// up to `MAX_FETCHES_IN_FLIGHT`. #[tokio::test]