Repository navigation
[Data] [4/11] Add Parquet footer types and the online bin packer - #65210
goutamvenkat-anyscale merged 4 commits into
Conversation
Groundwork for footer-based Parquet chunking: the data types describing a file's row groups, and the packer that groups them into read units. `OnlineBinPacker` is a streaming, locality-preserving bin packer. Light colours (files whose total size fits the bin budget) share First-Fit bins; heavy colours get dedicated monochromatic Next-Fit bins, so a large file's row groups stay contiguous instead of being scattered across every open bin. Bins are sealed and evicted as they fill, which bounds memory over an unbounded file stream. `coalesce_row_groups` merges runs of consecutive row groups into ~target-byte chunks, breaking on a change in match class, an index gap, or once the accumulator is full. It gets its own module rather than living beside the footer-reading actor, since it is pure and worth testing alone. All of it is unused so far and needs no Ray cluster to test. `ParquetRowGroupChunkMetadata` is added alongside the existing `ParquetFileChunkMetadata`; the size-based chunker still needs its own metadata type until the read path switches over. Signed-off-by: Goutam <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a footer-based Parquet chunking and online bin-packing implementation, including row-group coalescing logic, streaming bin-packing algorithms, and corresponding unit tests. Feedback on the changes highlights an issue in the best-fit bin selection logic (_best_open_bin), where the packer should prioritize maximizing the number of units packed before minimizing the leftover gap to align with its intended behavior.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Reviewed by Cursor Bugbot for commit dc134d7. Configure here.
Signed-off-by: Goutam <[email protected]>
| def _place(self, item: BinItem) -> None: | ||
| item_bytes = item.uncompressed_size | ||
| seen_bytes = self._seen_bytes_by_path.get(item.path, 0) | ||
| self._seen_bytes_by_path[item.path] = seen_bytes + item_bytes |
There was a problem hiding this comment.
why do we add uncompressed size and compressed size for a path?
There was a problem hiding this comment.
no it should be adding only uncompressed sizes for a path
| # file was light -- otherwise a splittable oversized run would scatter | ||
| # across shared bins. | ||
| self._heavy.switch_to(item.path) | ||
| self._pack(item, self._heavy) |
There was a problem hiding this comment.
do we have a test case covering the last else condition?
There was a problem hiding this comment.
I did not fully understand this one
There was a problem hiding this comment.
I clarified it in the comments.
There was a problem hiding this comment.
And yes there are a few tests that test this else clause.
abhishekverma-ray
left a comment
There was a problem hiding this comment.
Left a few comments, please check. Otherwise looks good to me.
Signed-off-by: Goutam <[email protected]>
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces a streaming, footer-based Parquet chunking and bin-packing mechanism, including row-group coalescing and an online bin packer to group chunks into partitions. The reviewer suggests adding validation checks across several new dataclasses and classes, specifically ensuring that row-group metadata sizes match counts for coalesced runs, validating that configuration parameters like bin bytes and open bin limits are positive, and verifying that the coalescing target size is non-negative.
| rg_sizes: Tuple[int, ...] = () | ||
| rg_rows: Tuple[int, ...] = () |
There was a problem hiding this comment.
For defensive programming and to prevent malformed metadata from causing silent issues downstream, we should validate that rg_sizes and rg_rows are populated and match rg_count when rg_count > 1.
| rg_sizes: Tuple[int, ...] = () | |
| rg_rows: Tuple[int, ...] = () | |
| rg_sizes: Tuple[int, ...] = () | |
| rg_rows: Tuple[int, ...] = () | |
| def __post_init__(self) -> None: | |
| if self.rg_count > 1: | |
| if not self.rg_sizes or len(self.rg_sizes) != self.rg_count: | |
| raise ValueError(f"rg_sizes must have length {self.rg_count} for coalesced runs") | |
| if not self.rg_rows or len(self.rg_rows) != self.rg_count: | |
| raise ValueError(f"rg_rows must have length {self.rg_count} for coalesced runs") |
| rg_sizes: Tuple[int, ...] = () | ||
| rg_rows: Tuple[int, ...] = () |
There was a problem hiding this comment.
Similar to RowGroupInfo, we should validate that rg_sizes and rg_rows are populated and match rg_count when rg_count > 1 in BinItem to ensure metadata integrity.
| rg_sizes: Tuple[int, ...] = () | |
| rg_rows: Tuple[int, ...] = () | |
| rg_sizes: Tuple[int, ...] = () | |
| rg_rows: Tuple[int, ...] = () | |
| def __post_init__(self) -> None: | |
| if self.rg_count > 1: | |
| if not self.rg_sizes or len(self.rg_sizes) != self.rg_count: | |
| raise ValueError(f"rg_sizes must have length {self.rg_count} for coalesced runs") | |
| if not self.rg_rows or len(self.rg_rows) != self.rg_count: | |
| raise ValueError(f"rg_rows must have length {self.rg_count} for coalesced runs") |
| def __init__( | ||
| self, | ||
| max_bin_bytes: int, | ||
| *, | ||
| max_shared_open_bins: int = 16, | ||
| split_coalesced: bool = False, | ||
| ): |
There was a problem hiding this comment.
Add validation for max_bin_bytes and max_shared_open_bins to prevent division by zero, infinite loops, or ValueError when calling max() on an empty sequence of bins.
| def __init__( | |
| self, | |
| max_bin_bytes: int, | |
| *, | |
| max_shared_open_bins: int = 16, | |
| split_coalesced: bool = False, | |
| ): | |
| def __init__( | |
| self, | |
| max_bin_bytes: int, | |
| *, | |
| max_shared_open_bins: int = 16, | |
| split_coalesced: bool = False, | |
| ): | |
| if max_bin_bytes <= 0: | |
| raise ValueError("max_bin_bytes must be positive") | |
| if max_shared_open_bins <= 0: | |
| raise ValueError("max_shared_open_bins must be at least 1") |
| if not target: | ||
| return tuple(per_rg) |
There was a problem hiding this comment.
|
@abhishekverma-ray in a follow up PR, I'll decouple the indexer from partitioner that way I can reuse the |
…ner (#65214) ## Why A metadata-aware indexer wants the pushed-down predicate, projection, and limit at **listing** time — to prune files by their statistics, size only the projected columns, and stop listing early once enough rows are found. (The footer-based Parquet indexer, later in this split, is the first such consumer.) ## Flow ```mermaid flowchart TD R["rule loop: projection → predicate → limit → count<br/>(runs to a fixed point)"] --> S["ReadFiles.scanner<br/>final accepted state"] S -->|"pushed_predicate / pruned_column_names / pushed_limit"| D["DeriveListFilesPushdown<br/>_post_optimize, runs last"] D -->|"overwrite, unconditionally, both directions"| L["ListFiles.predicate / projected_columns / limit"] L --> P[plan_list_files_op] --> I["FileIndexer.list_files(...)<br/>plain indexer ignores them"] ``` `DeriveListFilesPushdown` recomputes every `ListFiles`' constraints from the scanner of the `ReadFiles` that consumes it. Unconditional in both directions: a `ListFiles` whose consumer is *not* a `ReadFiles` — e.g. after `PushdownCountFiles` rewrites the plan — has its constraints cleared. So a rule that weakens a scanner's predicate automatically weakens listing too, and the worst a future rule can cause is listing *more* than it needs to. It runs in `LogicalOptimizer._post_optimize`, after the rule loop reaches a fixed point, rather than as a `_LOGICAL_RULESET` entry. `get_logical_ruleset().add()` is a `@DeveloperAPI`, so a caller-registered rule could otherwise be topologically ordered *after* it and strand a stale predicate. ## What changed **The rule and its inputs** (the substance — start here): | File | Change | | --- | --- | | `logical/rules/derive_list_files_pushdown.py` | **new** — the rule | | `datasource_v2/logical_optimizers.py` | read-back accessors `pushed_predicate()` / `pushed_limit()`, plus the `derive_list_files_pushdown(scanner)` helper that `isinstance`-guards each mixin | | `datasource_v2/scanners/arrow_file_scanner.py` | implements both accessors | | `logical/operators/read_operator.py` | `ListFiles` gains `predicate` / `projected_columns` / `limit` | | `logical/optimizers.py`, `logical/rules/__init__.py` | register and export the rule | **Plumbing so an indexer can consume it** (no consumer yet): | File | Change | | --- | --- | | `datasource_v2/listing/file_indexer.py` | `list_files()` accepts the three as kwargs (the plain indexer documents that it ignores them); new `produces_partitioned_manifests` property, default `False` | | `datasource_v2/listing/listing_utils.py` | forwards the kwargs | | `planner/plan_list_files_op.py`, `read_api.py` | forward the constraints, and honor `produces_partitioned_manifests` by skipping the partitioner and listing in a single task | **Tests:** `tests/unit/datasource_v2/test_derive_list_files_pushdown.py` (new, 9 tests). Both new accessors are **concrete, defaulting to `None`**, not abstract — these are `@DeveloperAPI` mixins, and an out-of-tree scanner should keep working (just without listing-time pruning) rather than fail to instantiate on upgrade. `None` is always the safe answer. **Inert on its own** — nothing reads the derived state yet. It is separated precisely because it is the soundness argument for the feature, and much easier to review on its own than buried in a read-path rewrite. ## Stack Step 3 of an 11-step split of #64985, which was 43 files / +3234 −719 and not reviewable as one unit. - #65167 — `[1/11]` Extract `FileIndexer.list_file_infos` ✅ merged - #65168 — `[2/11]` Push limit into `ReadFiles` when `Limit` sits directly on it ✅ merged - **this PR** — `[3/11]`, unblocked by the two above (it extends the same files) - #65210 — `[4/11]` Footer types + online bin packer (open, independent) - #65169 — `[9/11]` Pin the Parquet footer actor pool to 1 in tests (open, independent) --------- Signed-off-by: Goutam <[email protected]>
…ner (ray-project#65214) ## Why A metadata-aware indexer wants the pushed-down predicate, projection, and limit at **listing** time — to prune files by their statistics, size only the projected columns, and stop listing early once enough rows are found. (The footer-based Parquet indexer, later in this split, is the first such consumer.) ## Flow ```mermaid flowchart TD R["rule loop: projection → predicate → limit → count<br/>(runs to a fixed point)"] --> S["ReadFiles.scanner<br/>final accepted state"] S -->|"pushed_predicate / pruned_column_names / pushed_limit"| D["DeriveListFilesPushdown<br/>_post_optimize, runs last"] D -->|"overwrite, unconditionally, both directions"| L["ListFiles.predicate / projected_columns / limit"] L --> P[plan_list_files_op] --> I["FileIndexer.list_files(...)<br/>plain indexer ignores them"] ``` `DeriveListFilesPushdown` recomputes every `ListFiles`' constraints from the scanner of the `ReadFiles` that consumes it. Unconditional in both directions: a `ListFiles` whose consumer is *not* a `ReadFiles` — e.g. after `PushdownCountFiles` rewrites the plan — has its constraints cleared. So a rule that weakens a scanner's predicate automatically weakens listing too, and the worst a future rule can cause is listing *more* than it needs to. It runs in `LogicalOptimizer._post_optimize`, after the rule loop reaches a fixed point, rather than as a `_LOGICAL_RULESET` entry. `get_logical_ruleset().add()` is a `@DeveloperAPI`, so a caller-registered rule could otherwise be topologically ordered *after* it and strand a stale predicate. ## What changed **The rule and its inputs** (the substance — start here): | File | Change | | --- | --- | | `logical/rules/derive_list_files_pushdown.py` | **new** — the rule | | `datasource_v2/logical_optimizers.py` | read-back accessors `pushed_predicate()` / `pushed_limit()`, plus the `derive_list_files_pushdown(scanner)` helper that `isinstance`-guards each mixin | | `datasource_v2/scanners/arrow_file_scanner.py` | implements both accessors | | `logical/operators/read_operator.py` | `ListFiles` gains `predicate` / `projected_columns` / `limit` | | `logical/optimizers.py`, `logical/rules/__init__.py` | register and export the rule | **Plumbing so an indexer can consume it** (no consumer yet): | File | Change | | --- | --- | | `datasource_v2/listing/file_indexer.py` | `list_files()` accepts the three as kwargs (the plain indexer documents that it ignores them); new `produces_partitioned_manifests` property, default `False` | | `datasource_v2/listing/listing_utils.py` | forwards the kwargs | | `planner/plan_list_files_op.py`, `read_api.py` | forward the constraints, and honor `produces_partitioned_manifests` by skipping the partitioner and listing in a single task | **Tests:** `tests/unit/datasource_v2/test_derive_list_files_pushdown.py` (new, 9 tests). Both new accessors are **concrete, defaulting to `None`**, not abstract — these are `@DeveloperAPI` mixins, and an out-of-tree scanner should keep working (just without listing-time pruning) rather than fail to instantiate on upgrade. `None` is always the safe answer. **Inert on its own** — nothing reads the derived state yet. It is separated precisely because it is the soundness argument for the feature, and much easier to review on its own than buried in a read-path rewrite. ## Stack Step 3 of an 11-step split of ray-project#64985, which was 43 files / +3234 −719 and not reviewable as one unit. - ray-project#65167 — `[1/11]` Extract `FileIndexer.list_file_infos` ✅ merged - ray-project#65168 — `[2/11]` Push limit into `ReadFiles` when `Limit` sits directly on it ✅ merged - **this PR** — `[3/11]`, unblocked by the two above (it extends the same files) - ray-project#65210 — `[4/11]` Footer types + online bin packer (open, independent) - ray-project#65169 — `[9/11]` Pin the Parquet footer actor pool to 1 in tests (open, independent) --------- Signed-off-by: Goutam <[email protected]>
…-project#65210) ## Why Groundwork for footer-based Parquet chunking (the rest of the split of ray-project#64985). Everything here is pure logic with no Ray dependency, landed on its own so it can be reviewed as an algorithm rather than as part of a read-path rewrite. Today `ParquetFileChunker` splits each file by `ceil(file_size / 1 GiB)` *without reading the footer*, and the partitioner bin-packs those guesses using a fixed encoding-ratio estimate. Bin sizes are inaccurate because the compression ratio is unknown until the footer is read. Replacing that needs a packer that works from real row-group metadata, arrives as a stream, and bounds its own memory. **Nothing calls this yet** — it is unused until the footer indexer lands. ## Flow ### The default path: pack the row groups themselves Out of the box **both coalescing and splitting are off** (`coalesce_bytes = 0`, `split_coalesced = False`). One bin item is one physical row group, and `OnlineBinPacker` First-Fits those whole items into big bins of `max_bin_bytes`. One big bin becomes one read task. Nothing is ever cut. ```mermaid flowchart LR RG["physical row groups<br/>from the footer"] --> IT["one bin item<br/>per row group"] IT --> P["OnlineBinPacker<br/>First-Fit, items stay whole"] P --> SEAL["seal + evict full big bins<br/>(max_bin_bytes)"] SEAL --> M["one big bin = one read task<br/>FileManifest + ParquetRowGroupChunkMetadata"] ``` ### Optional: a second, smaller bin size underneath Setting `coalesce_bytes > 0` inserts a **first** packing pass upstream, in the footer reader: `coalesce_row_groups` packs consecutive row groups into contiguous runs of ~`coalesce_bytes`. Each run is a *small bin*, and the packer then packs small bins into big bins instead of packing row groups directly. Fewer, larger items means fewer descriptors crossing to the driver. That raises one question the default path never has to answer: a small bin is a pre-packed bundle, so what happens when it doesn't fit in the space left in a big bin? `split_coalesced` is that answer, and it is **also opt-in**: ```mermaid flowchart TD RG["physical row groups"] -->|"optional level 1: coalesce_bytes"| SB["small bins<br/>contiguous row-group runs"] SB --> FIT{"fits in an open big bin?"} FIT -->|yes| PUT["drop it in whole"] FIT -->|"no — split_coalesced = false (default)"| NEW["keep it intact,<br/>start a new big bin"] FIT -->|"no — split_coalesced = true"| CUT["break it back into its row groups:<br/>fill the leftover space,<br/>carry the remainder onward"] PUT --> SEAL["level 2: seal + evict<br/>full big bins (max_bin_bytes)"] NEW --> SEAL CUT --> SEAL SEAL --> M["one big bin = one read task"] ``` So the three configurations are: | `coalesce_bytes` | `split_coalesced` | behaviour | | --- | --- | --- | | `0` (default) | `False` (default) | pack whole row groups into big bins | | `> 0` | `False` | pack whole small bins into big bins | | `> 0` | `True` | pack small bins, breaking one back open when it would otherwise waste the tail of a big bin | Two properties worth checking during review: - **`split_coalesced` cannot change the default path.** Without coalescing there are no small bins to break open — a bin item already *is* one row group — so the flag is inert and packing is plain First-Fit either way. Guarded by `test_split_coalesced_is_noop_without_coalescing`. - **A small bin is only ever cut at the seams it was built from.** Never mid-row-group, so every piece stays a contiguous run with exact sizes and row counts. A run larger than a whole big bin is simply cut across several of them. Orthogonal to all of the above, big bins come from two pools. A file's chunks go to a **shared** pool (mixed files) until that file's cumulative bytes exceed the cap, after which it switches to a **single-file** pool — so a large file's row groups stay contiguous instead of scattering across every open bin. Bins seal and evict as they fill, which bounds memory over an unbounded stream *and* lets read tasks start before every footer has landed. ## What changed | File | Change | | --- | --- | | `chunkers/parquet_footer_types.py` | **new** — `RowGroupInfo`, `FileChunks`, `BinItem`, `Bin`. Frozen dataclasses, no imports beyond `typing`. | | `chunkers/parquet_row_group_coalescing.py` | **new** — `coalesce_row_groups()`. A run breaks on a change in `fully_matched` (never merge across the match-class boundary, or limit push-down miscounts), a gap in `rg_idx` (filter-pruned groups), or once the accumulator is full. `target == 0` disables it. | | `partitioners/online_bin_packer.py` | **new** — `OnlineBinPacker` plus the `_BinPool` / `_SharedBinPool` / `_SingleFileBinPool` hierarchy. A file stays in the shared pool until its cumulative bytes exceed the cap, then switches to a dedicated pool so a large file's row groups stay contiguous instead of scattering across every open bin. Bins seal and evict as they fill, which bounds memory over an unbounded stream *and* lets read tasks start before every footer has landed. | | `chunkers/file_chunker.py` | **adds** `ParquetRowGroupChunkMetadata` alongside the existing `ParquetFileChunkMetadata`. Additive on purpose — the size-based chunker still needs its own metadata type until the read path switches over. | | `tests/unit/datasource_v2/test_online_bin_packer.py` | **new** — 14 tests, no Ray cluster. | 864 insertions, 0 deletions. ## Testing Coverage is aimed at the invariants rather than the happy path: that every row group is covered *exactly once* across all emitted bins (parametrized over `split_coalesced`), that splitting is a no-op without coalescing, that an oversize coalesced run is cut at boundaries and can fill residual shared-bin space, and that a full single-file bin is sealed immediately. ``` $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/test_online_bin_packer.py 14 passed in 0.05s $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/ 74 passed in 0.17s $ python -m pytest -q python/ray/data/_internal/datasource_v2/tests/ 35 passed in 0.75s ``` ## Stack Step 4 of an 11-step split of ray-project#64985, which was 43 files / +3234 −719 and not reviewable as one unit. - ray-project#65167 — `[1/11]` Extract `FileIndexer.list_file_infos` ✅ merged - ray-project#65168 — `[2/11]` Push limit into `ReadFiles` when `Limit` sits directly on it ✅ merged - ray-project#65214 — `[3/11]` Derive `ListFiles` pushdown state from the `ReadFiles` scanner (open) - **this PR** — `[4/11]`, **no merge-order dependency**: it touches a file set disjoint from every other step and applies cleanly to master on its own. - ray-project#65169 — `[9/11]` Pin the Parquet footer actor pool to 1 in tests (open, independent) Step 5 (`FooterReader`) imports `parquet_footer_types` and `parquet_row_group_coalescing` from this PR, so it follows this one. --- Not a duplicate of any open PR (checked `gh pr list --repo ray-project/ray --state open` plus a file-level overlap check; only ray-project#64985, which this replaces). AI assistance was used; every line reviewed by me and tests run locally. --------- Signed-off-by: Goutam <[email protected]>
…ner (ray-project#65214) ## Why A metadata-aware indexer wants the pushed-down predicate, projection, and limit at **listing** time — to prune files by their statistics, size only the projected columns, and stop listing early once enough rows are found. (The footer-based Parquet indexer, later in this split, is the first such consumer.) ## Flow ```mermaid flowchart TD R["rule loop: projection → predicate → limit → count<br/>(runs to a fixed point)"] --> S["ReadFiles.scanner<br/>final accepted state"] S -->|"pushed_predicate / pruned_column_names / pushed_limit"| D["DeriveListFilesPushdown<br/>_post_optimize, runs last"] D -->|"overwrite, unconditionally, both directions"| L["ListFiles.predicate / projected_columns / limit"] L --> P[plan_list_files_op] --> I["FileIndexer.list_files(...)<br/>plain indexer ignores them"] ``` `DeriveListFilesPushdown` recomputes every `ListFiles`' constraints from the scanner of the `ReadFiles` that consumes it. Unconditional in both directions: a `ListFiles` whose consumer is *not* a `ReadFiles` — e.g. after `PushdownCountFiles` rewrites the plan — has its constraints cleared. So a rule that weakens a scanner's predicate automatically weakens listing too, and the worst a future rule can cause is listing *more* than it needs to. It runs in `LogicalOptimizer._post_optimize`, after the rule loop reaches a fixed point, rather than as a `_LOGICAL_RULESET` entry. `get_logical_ruleset().add()` is a `@DeveloperAPI`, so a caller-registered rule could otherwise be topologically ordered *after* it and strand a stale predicate. ## What changed **The rule and its inputs** (the substance — start here): | File | Change | | --- | --- | | `logical/rules/derive_list_files_pushdown.py` | **new** — the rule | | `datasource_v2/logical_optimizers.py` | read-back accessors `pushed_predicate()` / `pushed_limit()`, plus the `derive_list_files_pushdown(scanner)` helper that `isinstance`-guards each mixin | | `datasource_v2/scanners/arrow_file_scanner.py` | implements both accessors | | `logical/operators/read_operator.py` | `ListFiles` gains `predicate` / `projected_columns` / `limit` | | `logical/optimizers.py`, `logical/rules/__init__.py` | register and export the rule | **Plumbing so an indexer can consume it** (no consumer yet): | File | Change | | --- | --- | | `datasource_v2/listing/file_indexer.py` | `list_files()` accepts the three as kwargs (the plain indexer documents that it ignores them); new `produces_partitioned_manifests` property, default `False` | | `datasource_v2/listing/listing_utils.py` | forwards the kwargs | | `planner/plan_list_files_op.py`, `read_api.py` | forward the constraints, and honor `produces_partitioned_manifests` by skipping the partitioner and listing in a single task | **Tests:** `tests/unit/datasource_v2/test_derive_list_files_pushdown.py` (new, 9 tests). Both new accessors are **concrete, defaulting to `None`**, not abstract — these are `@DeveloperAPI` mixins, and an out-of-tree scanner should keep working (just without listing-time pruning) rather than fail to instantiate on upgrade. `None` is always the safe answer. **Inert on its own** — nothing reads the derived state yet. It is separated precisely because it is the soundness argument for the feature, and much easier to review on its own than buried in a read-path rewrite. ## Stack Step 3 of an 11-step split of ray-project#64985, which was 43 files / +3234 −719 and not reviewable as one unit. - ray-project#65167 — `[1/11]` Extract `FileIndexer.list_file_infos` ✅ merged - ray-project#65168 — `[2/11]` Push limit into `ReadFiles` when `Limit` sits directly on it ✅ merged - **this PR** — `[3/11]`, unblocked by the two above (it extends the same files) - ray-project#65210 — `[4/11]` Footer types + online bin packer (open, independent) - ray-project#65169 — `[9/11]` Pin the Parquet footer actor pool to 1 in tests (open, independent) --------- Signed-off-by: Goutam <[email protected]> Signed-off-by: 400Ping <[email protected]>
…-project#65210) ## Why Groundwork for footer-based Parquet chunking (the rest of the split of ray-project#64985). Everything here is pure logic with no Ray dependency, landed on its own so it can be reviewed as an algorithm rather than as part of a read-path rewrite. Today `ParquetFileChunker` splits each file by `ceil(file_size / 1 GiB)` *without reading the footer*, and the partitioner bin-packs those guesses using a fixed encoding-ratio estimate. Bin sizes are inaccurate because the compression ratio is unknown until the footer is read. Replacing that needs a packer that works from real row-group metadata, arrives as a stream, and bounds its own memory. **Nothing calls this yet** — it is unused until the footer indexer lands. ## Flow ### The default path: pack the row groups themselves Out of the box **both coalescing and splitting are off** (`coalesce_bytes = 0`, `split_coalesced = False`). One bin item is one physical row group, and `OnlineBinPacker` First-Fits those whole items into big bins of `max_bin_bytes`. One big bin becomes one read task. Nothing is ever cut. ```mermaid flowchart LR RG["physical row groups<br/>from the footer"] --> IT["one bin item<br/>per row group"] IT --> P["OnlineBinPacker<br/>First-Fit, items stay whole"] P --> SEAL["seal + evict full big bins<br/>(max_bin_bytes)"] SEAL --> M["one big bin = one read task<br/>FileManifest + ParquetRowGroupChunkMetadata"] ``` ### Optional: a second, smaller bin size underneath Setting `coalesce_bytes > 0` inserts a **first** packing pass upstream, in the footer reader: `coalesce_row_groups` packs consecutive row groups into contiguous runs of ~`coalesce_bytes`. Each run is a *small bin*, and the packer then packs small bins into big bins instead of packing row groups directly. Fewer, larger items means fewer descriptors crossing to the driver. That raises one question the default path never has to answer: a small bin is a pre-packed bundle, so what happens when it doesn't fit in the space left in a big bin? `split_coalesced` is that answer, and it is **also opt-in**: ```mermaid flowchart TD RG["physical row groups"] -->|"optional level 1: coalesce_bytes"| SB["small bins<br/>contiguous row-group runs"] SB --> FIT{"fits in an open big bin?"} FIT -->|yes| PUT["drop it in whole"] FIT -->|"no — split_coalesced = false (default)"| NEW["keep it intact,<br/>start a new big bin"] FIT -->|"no — split_coalesced = true"| CUT["break it back into its row groups:<br/>fill the leftover space,<br/>carry the remainder onward"] PUT --> SEAL["level 2: seal + evict<br/>full big bins (max_bin_bytes)"] NEW --> SEAL CUT --> SEAL SEAL --> M["one big bin = one read task"] ``` So the three configurations are: | `coalesce_bytes` | `split_coalesced` | behaviour | | --- | --- | --- | | `0` (default) | `False` (default) | pack whole row groups into big bins | | `> 0` | `False` | pack whole small bins into big bins | | `> 0` | `True` | pack small bins, breaking one back open when it would otherwise waste the tail of a big bin | Two properties worth checking during review: - **`split_coalesced` cannot change the default path.** Without coalescing there are no small bins to break open — a bin item already *is* one row group — so the flag is inert and packing is plain First-Fit either way. Guarded by `test_split_coalesced_is_noop_without_coalescing`. - **A small bin is only ever cut at the seams it was built from.** Never mid-row-group, so every piece stays a contiguous run with exact sizes and row counts. A run larger than a whole big bin is simply cut across several of them. Orthogonal to all of the above, big bins come from two pools. A file's chunks go to a **shared** pool (mixed files) until that file's cumulative bytes exceed the cap, after which it switches to a **single-file** pool — so a large file's row groups stay contiguous instead of scattering across every open bin. Bins seal and evict as they fill, which bounds memory over an unbounded stream *and* lets read tasks start before every footer has landed. ## What changed | File | Change | | --- | --- | | `chunkers/parquet_footer_types.py` | **new** — `RowGroupInfo`, `FileChunks`, `BinItem`, `Bin`. Frozen dataclasses, no imports beyond `typing`. | | `chunkers/parquet_row_group_coalescing.py` | **new** — `coalesce_row_groups()`. A run breaks on a change in `fully_matched` (never merge across the match-class boundary, or limit push-down miscounts), a gap in `rg_idx` (filter-pruned groups), or once the accumulator is full. `target == 0` disables it. | | `partitioners/online_bin_packer.py` | **new** — `OnlineBinPacker` plus the `_BinPool` / `_SharedBinPool` / `_SingleFileBinPool` hierarchy. A file stays in the shared pool until its cumulative bytes exceed the cap, then switches to a dedicated pool so a large file's row groups stay contiguous instead of scattering across every open bin. Bins seal and evict as they fill, which bounds memory over an unbounded stream *and* lets read tasks start before every footer has landed. | | `chunkers/file_chunker.py` | **adds** `ParquetRowGroupChunkMetadata` alongside the existing `ParquetFileChunkMetadata`. Additive on purpose — the size-based chunker still needs its own metadata type until the read path switches over. | | `tests/unit/datasource_v2/test_online_bin_packer.py` | **new** — 14 tests, no Ray cluster. | 864 insertions, 0 deletions. ## Testing Coverage is aimed at the invariants rather than the happy path: that every row group is covered *exactly once* across all emitted bins (parametrized over `split_coalesced`), that splitting is a no-op without coalescing, that an oversize coalesced run is cut at boundaries and can fill residual shared-bin space, and that a full single-file bin is sealed immediately. ``` $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/test_online_bin_packer.py 14 passed in 0.05s $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/ 74 passed in 0.17s $ python -m pytest -q python/ray/data/_internal/datasource_v2/tests/ 35 passed in 0.75s ``` ## Stack Step 4 of an 11-step split of ray-project#64985, which was 43 files / +3234 −719 and not reviewable as one unit. - ray-project#65167 — `[1/11]` Extract `FileIndexer.list_file_infos` ✅ merged - ray-project#65168 — `[2/11]` Push limit into `ReadFiles` when `Limit` sits directly on it ✅ merged - ray-project#65214 — `[3/11]` Derive `ListFiles` pushdown state from the `ReadFiles` scanner (open) - **this PR** — `[4/11]`, **no merge-order dependency**: it touches a file set disjoint from every other step and applies cleanly to master on its own. - ray-project#65169 — `[9/11]` Pin the Parquet footer actor pool to 1 in tests (open, independent) Step 5 (`FooterReader`) imports `parquet_footer_types` and `parquet_row_group_coalescing` from this PR, so it follows this one. --- Not a duplicate of any open PR (checked `gh pr list --repo ray-project/ray --state open` plus a file-level overlap check; only ray-project#64985, which this replaces). AI assistance was used; every line reviewed by me and tests run locally. --------- Signed-off-by: Goutam <[email protected]> Signed-off-by: 400Ping <[email protected]>
## Why Footer IO for the footer-based Parquet chunking path (the rest of the split of #64985). Reading N Parquet footers serially on the driver doesn't scale — it's the step that decides which row groups a read even touches. `FooterReader` runs as a pool of Ray actors, each reading footers on its own thread pool and streaming results back in batches, so footer IO spreads across the cluster instead of bottlenecking on one process. **Nothing constructs it yet** — it's unused until the footer indexer lands in step 6. ## Flow Per file, it produces the row-group descriptors the bin packer (merged in #65210) consumes: ```mermaid flowchart LR B["(path, size) batch"] --> A["FooterReaderActor<br/>SPREAD across the cluster"] A --> R[read footer] R --> F["split_by_row_group(filter)<br/>prune by statistics"] F --> Q["split_by_row_group(~filter)<br/>classify fully_matched"] Q --> C["coalesce_row_groups<br/>(from #65210)"] C --> O["stream List[FileChunks]<br/>batched by result_batch_size"] ``` Three things it decides, each of which the packer and the limit push-down depend on: - **Predicate pruning.** `fragment.split_by_row_group(filter)` drops row groups whose Parquet statistics contradict the pushed filter, so they never reach the packer at all. - **`fully_matched` classification.** A surviving group is *fully* matched iff `~filter` prunes it entirely. Only fully-matched groups have an exact survivor count, and only exact counts may drive limit push-down. Any failure defaults to not-fully-matched, which is always the safe direction. **This is the correctness-critical bit**: nulls are the interesting case, since Parquet min/max stats are computed over non-null values only, so a group whose non-null values all satisfy the filter looks fully matched by bounds alone while its null rows don't survive. - **Projection-scoped sizing.** Byte sizes are accounted over only the projected leaf columns, so bins get sized for what the reader will actually fetch. Nested columns expand to all their leaves. ## What changed Two new files, 368 insertions, 0 deletions: | File | Change | | --- | --- | | `listing/footer_reader.py` | **new** — `FooterReader` plus `FooterReaderActor = ray.remote(FooterReader)`. Kept as a plain class with the actor built via the functional form, so callers can type handles as `ActorProxy[FooterReader]`. `read_footers` is a streaming `@ray.method` generator that yields `List[FileChunks]`, batched by `result_batch_size` — the driver pays one object-store fetch per yielded list, so batching cuts driver-side deserialization roughly proportionally. | | `tests/test_footer_reader.py` | **new** — 14 tests | ## Testing The tests drive the plain class directly against local Parquet fixtures — no actor, no cluster. Coverage is aimed at the decisions above rather than the plumbing: predicate pruning by statistics, the partial-match case (`id >= 30` splitting a row group, which must **not** count as exact), a predicate matching nothing, projection shrinking accounted size while leaving row counts alone, coalescing preserving total rows, nested columns expanding to all leaves, and result batching at several `result_batch_size` values. ``` $ python -m pytest -q python/ray/data/_internal/datasource_v2/tests/test_footer_reader.py 14 passed in 4.30s $ python -m pytest -q python/ray/data/_internal/datasource_v2/tests/ python/ray/data/tests/unit/datasource_v2/ 145 passed in 0.90s ``` ## Stack Step 5 of an 11-step split of #64985, which was 43 files / +3234 −719 and not reviewable as one unit. - #65167 `[1/11]` Extract `FileIndexer.list_file_infos` ✅ merged - #65168 `[2/11]` Push limit into `ReadFiles` when `Limit` sits directly on it ✅ merged - #65214 `[3/11]` Derive `ListFiles` pushdown state from the scanner ✅ merged - #65210 `[4/11]` Parquet footer types + online bin packer ✅ merged - **this PR** `[5/11]` — depends on #65210 for `parquet_footer_types` and `parquet_row_group_coalescing` - #65169 `[9/11]` Pin the Parquet footer actor pool to 1 in tests (open, independent) Step 6 wires this and the packer together behind an opt-in flag, and needs both this and #65214. --- Not a duplicate of any open PR (checked `gh pr list --state open` plus a file-level overlap check against #65142 / #63158 / #64404 — no overlap; only #64985, which this replaces). AI assistance was used; every line reviewed by me and tests run locally. --------- Signed-off-by: Goutam <[email protected]>
…acking as a partitioner (#65596) ## Why Parquet V2 chunks files **blindly**. `ParquetFileChunker` splits each file by `ceil(file_size / 1 GiB)` *without reading the footer*, and `RoundRobinPartitioner` bin-packs those guesses with a fixed encoding-ratio estimate. Bin sizes are inaccurate because the compression ratio is unknown until the footer is read, there is no row-group skipping, and nothing from predicate / limit / projection push-down reaches listing. This wires steps 1–5 into a working read path — the first PR in the split where the footer path is *reachable*. **Default-off.** Gated on `RAY_DATA_PARQUET_ENABLE_FOOTER_INDEXER`; without it every Parquet V2 read behaves exactly as today. Flipping the default and deleting the blind chunker are separate later steps, which keeps this reviewable and leaves a one-line revert lever. ## What this changes **1. `FooterFileIndexer` — listing that reads footers.** New indexer, returned from `_get_file_indexer()` only when the flag is set. It footer-reads files on a `FooterReader` actor pool (step 5) and emits **one listing row per row-group run**, each carrying that run's exact stats: `num_rows`, `uncompressed_size`, per-row-group `rg_sizes` / `rg_rows`, and `fully_matched`. Actor pool is killed in a `finally`, in-flight footer batches are bounded, and listing stops early once `limit` exact-survivor rows are delivered. **2. Bin packing is a `FilePartitioner`, not an indexer detail.** Listing discovers work; the partitioner groups it. `OnlineBinPacker` (step 4) becomes a real `FilePartitioner` supplied via a new `DataSourceV2.get_file_partitioner()` hook, so it runs in the normal partitioner stage and can split runs at exact row-group boundaries. `FileIndexer.produces_partitioned_manifests` is deleted in favor of `FilePartitioner.requires_global_input`, which is what tells `plan_list_files_op` to keep listing on one task. This is not just tidying — it fixes a parallelism bug. `produces_partitioned_manifests` made the planner skip the partitioner stage entirely, so with `shuffle="files"` the footer path read the **whole dataset in a single task**: `shuffle_files` concatenates every sealed bin into one manifest block, and with no partitioner downstream nothing was left to re-split it. **3. `count()` push-down.** `PushdownCountFiles` tried to force whole-file listing by overwriting the indexer's `_file_chunker`, but `FooterFileIndexer` overrides `list_files` outright and ignores its chunker, so the swap was a silent no-op. It now swaps the indexer itself via `as_whole_file_indexer()`. This is what makes (2) safe: once listing emits a row per row-group run, `read_metadata` returns the whole file's row count for *each* row, so a 4-row-group file counts 4×. The hard `assert isinstance(...)` also becomes a debug log and bail-out, so a third-party indexer falls back to the regular read path instead of crashing the optimizer. **4. `skip_paths` on the footer path.** `FooterFileIndexer` was constructed without it, so `read_parquet(..., skip_paths=...)` silently did nothing when the flag was on — excluded files were read, and a path named only in `skip_paths` could fail the listing instead of being ignored. These land together because (3) guards a bug that (2) introduces, and both touch the same listing contract. ## Flow ```mermaid flowchart TD LF[ListFiles] --> FI[FooterFileIndexer] FI --> LI["list_file_infos<br/>(step 1)"] LI --> BA[batch paths] BA --> AP["FooterReaderActor pool<br/>SPREAD (step 5)"] AP -->|one row per row-group run| SH[shuffle_files] SH --> BP["OnlineBinPacker<br/>(step 4), a FilePartitioner"] BP -->|sealed bins| MB[manifest blocks] MB --> RF[ReadFiles] RF --> PR["ParquetFileReader<br/>reads exactly the named row groups"] LF -.->|"predicate / limit / projected_columns<br/>(step 3)"| FI ``` `OnlineBinPacker.requires_global_input = True` keeps listing on a single task, since the packer holds one pool of open bins across all files. ## Files | File | Change | | --- | --- | | `listing/footer_file_indexer.py` | **new** — `FooterFileIndexer`. All knobs re-read in `__init__` so `monkeypatch.setenv` and release-test overrides apply. | | `listing/file_indexer.py` | drops `produces_partitioned_manifests`; adds `as_whole_file_indexer()` | | `partitioners/online_bin_packer.py` | now a `FilePartitioner` (`add_input`, `requires_global_input`) | | `partitioners/file_partitioner.py` | adds `requires_global_input` | | `datasource_v2.py` / `read_api.py` | new `get_file_partitioner()` hook; default stays `RoundRobinPartitioner` | | `parquet_datasource_v2.py` | flag-gated indexer + packer; wires `skip_paths` | | `planner/plan_list_files_op.py` | partitioner stage always runs; single-task listing keys off `requires_global_input` | | `rules/pushdown_count_files.py` | replaces the indexer instead of reconfiguring it | | `chunkers/file_chunker.py` | `ParquetRowGroupChunkMetadata` gains `fully_matched`, `rg_sizes`, `rg_rows` | | `chunkers/parquet_file_chunking_utils.py` | adds `_fragments_from_row_group_ids`, `_with_io_retry` | | `readers/parquet_file_reader.py` | dispatches on metadata type so both chunkers coexist; sizes batches from footer stats already on the manifest | | `readers/file_reader.py` | `_resolve_batch_size(dataset, manifest)` | ## Testing ``` pytest python/ray/data/tests/unit/datasource_v2/test_file_indexer.py \ python/ray/data/tests/unit/datasource_v2/test_online_bin_packer.py \ python/ray/data/_internal/datasource_v2/tests/test_parquet_datasource_v2.py \ python/ray/data/_internal/datasource_v2/tests/test_footer_chunking.py \ python/ray/data/tests/datasource/test_read_parquet_v2.py # 145 passed ``` The two that carry the most weight: - `test_count_matches_rows`, parametrized over `(4 files, 1000 rows, row_group_size=250)`. This is the guard for (3): without `as_whole_file_indexer()` it fails `assert 4800 == 1200`. - `test_e2e_filter_then_limit_with_nulls`, 20 files at 10% non-null over five limits. If a null were ever counted as an exact survivor, listing would stop short and `Limit` would quietly return fewer rows than asked. (The classification behind that landed in #65273.) **Known gap:** `skip_paths` has unit coverage in `test_parquet_datasource_v2.py` but no end-to-end test through `read_parquet` on the footer path. ## Stack Step 6 of an 11-step split of #64985 (43 files, +3234 −719, not reviewable as one unit). - #65167 `[1/11]` `FileIndexer.list_file_infos` ✅ · #65168 `[2/11]` limit into `ReadFiles` ✅ - #65214 `[3/11]` derive `ListFiles` pushdown state ✅ · #65210 `[4/11]` footer types + bin packer ✅ - #65273 `[5/11]` `FooterReader` actor pool ✅ - **this PR** — consumes all of the above; first step that makes the path reachable - #65169 `[9/11]` pin the footer actor pool to 1 in tests (open, independent) This PR **absorbs what was going to be step 7** (`count()` push-down), so the remaining steps renumber down by one. Step 7 can't be split out downstream of this: the packing change is what triggers the over-count, so the fix has to ship at or below it. ## AI assistance AI assistance was used for this change. I have reviewed every changed line and run the tests above locally. Not a duplicate: `gh pr list --repo ray-project/ray --state open --search "FooterFileIndexer"` and `--search "footer indexer parquet"` return only this PR, the stack members listed above, and #64985 — the mega-PR this stack is splitting up, which closes once the stack lands. --------- Signed-off-by: Goutam <[email protected]> Co-authored-by: Cursor <[email protected]>
…65806) ## Why Two independent throughput knobs for the Parquet read task, kept out of the footer-indexer PR because each changes behavior on its own and needs its own justification. **One reader thread per fragment, instead of capping at 4.** The cap existed because the blind `ParquetFileChunker` could put an unbounded number of row groups — and therefore fragments — in a single read task, so an uncapped thread pool was a real risk. Now that #65596 has landed, read units are bin-packed to a byte budget, so the fragment count per task is bounded by construction and the cap only serializes IO that could overlap. **Size Arrow's IO/CPU pools for the read task.** Arrow's defaults (~num cores, 8 IO threads) throttle the concurrent column/range fetches a Parquet scan issues against S3. That hurts most for row-group-scoped fragments, which is exactly what the footer path now produces. ## Flow No structural change — both are sizing knobs on the existing read path: ``` ReadFiles task ├─ pa.set_io_thread_count / set_cpu_count ← new, at reader construction └─ _read_fragment_batches └─ num_workers = len(fragments) ← was min(4, len(fragments)) ``` The sequential path still applies when `DataContext.execution_options.preserve_order` is set, unchanged. ## What changed | File | Change | | --- | --- | | `readers/file_reader.py` | Drop `_DEFAULT_NUM_THREADS` / `RAY_DATA_READ_FILES_NUM_THREADS`; `num_workers = len(fragments_with_offsets)`. Also fixes the `_read_fragment_batches` docstring, which still documented the removed env var. | | `readers/parquet_file_reader.py` | `pa.set_io_thread_count()` / `pa.set_cpu_count()` at reader construction, from `RAY_DATA_PARQUET_READER_IO_THREAD_COUNT` / `RAY_DATA_PARQUET_READER_CPU_COUNT` (default 128 each; `0` disables). | **Two things worth a careful look:** - This **removes** `RAY_DATA_READ_FILES_NUM_THREADS`. It is undocumented and internal, but anyone setting it loses the knob. - `pa.set_io_thread_count` / `set_cpu_count` mutate **process-global** Arrow state from a constructor. That is deliberate — the read task is the process — but it means a non-Parquet reader sharing the worker sees the same pools. ## Stack Step 8 of an 11-step split of #64985. - #65167 `[1/11]` ✅ · #65168 `[2/11]` ✅ · #65214 `[3/11]` ✅ · #65210 `[4/11]` ✅ · #65273 `[5/11]` ✅ - #65596 `[6/11]` ✅ — footer indexer behind the flag, which also absorbed step 7's `count()` fix and moved bin packing into a `FilePartitioner` - **this PR** `[8/11]` — unblocked by #65596: the thread cap can only come off once bins are size-bounded - #65169 `[9/11]` pin the footer actor pool to 1 in tests (open, independent) Remaining after this: release-test tuning, then flipping the default and deleting the old chunker. --------- Signed-off-by: Goutam <[email protected]>
## Why The last step of the split of #64985: flip Parquet V2 to the footer read path, delete the blind one, and tune the release tests so this can be validated by a real release run. Everything it depends on has landed — footer types and the bin packer (#65210), the `FooterReader` actor pool (#65273), the indexer plus `count()` fix and packer-as-partitioner (#65596), reader IO tuning (#65806), and test env pinning (#65169). The path has been reachable behind `RAY_DATA_PARQUET_ENABLE_FOOTER_INDEXER` since #65596; this makes it the only path. ## Flow ```mermaid flowchart LR RP[read_parquet] --> FF["FooterFileIndexer<br/>+ OnlineBinPacker"] RP -.->|deleted| PC["ParquetFileChunker<br/>size-estimated chunks<br/>+ parquet_chunker_target_chunk_size"] style PC stroke-dasharray: 4 4 ``` ## What changed **The flip** — `RAY_DATA_PARQUET_ENABLE_FOOTER_INDEXER` is gone from both call sites. `_get_file_indexer()` always returns `FooterFileIndexer`; `get_file_partitioner()` always returns `OnlineBinPacker`. **The deletions** — `ParquetFileChunker`, `ParquetFileChunkMetadata`, `_calculate_row_group_range`, `_fragments_from_chunk_metadata`, and the tests covering only that path. **The config it left behind** — `DataContext.parquet_chunker_target_chunk_size` and `DEFAULT_PARQUET_CHUNKER_TARGET_CHUNK_SIZE` were read *only* by `ParquetFileChunker.__init__`, so they would otherwise stay declared and documented while doing nothing. Verified dead by grep across `.py` / `.yaml` / `.rst` / `.md`. **Reader pool defaults** — `RAY_DATA_PARQUET_READER_IO_THREAD_COUNT` 128, `RAY_DATA_PARQUET_READER_CPU_COUNT` 32. ## Release tests tuned Budgets are per-test overrides of `RAY_DATA_PARQUET_BIN_PACKING_BYTES` (uncompressed bytes of row-group data per read task; default 128 MiB). The shape of the tuning: reads over few large groups want **large** bins, because small bins shatter the read into short tasks the executor cannot dispatch fast enough and the cluster idles; shuffle-bound reads over many groups want **small** bins. Rows whose variants all share the same tuning are collapsed and marked. | release test | bin budget | other tuning | | --- | --- | --- | | `aggregate_groups_fixed_size_hash_shuffle_column02 column14` | 32 MiB | — | | `aggregate_groups_fixed_size_hash_shuffle_column08 column13 column14` | 128 MiB | — | | `aggregate_groups_fixed_size_shuffle_v2_column02 column14` | 64 MiB | — | | `aggregate_groups_fixed_size_shuffle_v2_column08 column13 column14` | 512 MiB | — | | `aggregate_groups_fixed_size_sort_shuffle_pull_based_column02 column14` | 32 MiB | — | | `aggregate_groups_fixed_size_sort_shuffle_pull_based_column08 column13 column14` | 256 MiB | — | | `count_parquet_fixed_size` | 64 MiB | — | | `cross_az_map_batches_autoscaling_iptable_failure_injection` | 1 GiB | — | | `distributed_training` | — | footer actors `20` | | `flat_map` | 64 MiB | — | | `iceberg_benchmark_overwrite` | 64 MiB | — | | `iter_batches_pyarrow` | 64 MiB | — | | `iter_torch_batches` | 64 MiB | — | | `joins_{{dataset}}_{{join_type}} *(all 4 variants)*` | 1.25 GiB | — | | `map` | 64 MiB | — | | `map_batches_fixed_size_{{compute}}_{{format}}_{{repeat_map_batches}} *(all 7 variants)*` | 1 GiB | scale-up threshold `0.6` | | `map_groups_fixed_size_{{shuffle_strategy}}_{{columns}} *(all 6 variants)*` | 1.25 GiB | — | | `mix` | — | footer actors `4` | | `random_shuffle_fixed_size` | 64 MiB | — | | `read_large_parquet_fixed_size` | 1 GiB | — | | `read_parquet_fixed_size` | 64 MiB | — | | `read_tfrecords` | 64 MiB | — | | `streaming_split` | 64 MiB | footer batch `50`, result batch `50` | | `to_tf` | 64 MiB | — | | `tpch_q1_fixed_size_{{shuffle_strategy}} *(all 2 variants)*` | 192 MiB | — | | `training_ingest_benchmark` | 64 MiB | — | | `wide_schema_pipeline_nested_structs` | 2 MiB | footer batch `1`, footer actors `21`, io threads `5000` | | `wide_schema_pipeline_objects` | 4.2 MiB | footer batch `1`, footer actors `9`, io threads `5000` | | `wide_schema_pipeline_primitives` | 256 KiB | footer batch `1`, footer actors `27`, io threads `5000` | | `wide_schema_pipeline_tensors` | 39 MiB | footer batch `1`, footer actors `22`, io threads `5000` | | `write_parquet` | 1.25 GiB | — | **Three matrices are split**, because a matrix cannot vary `byod.runtime_env` per value and their variants want different budgets: `wide_schema_pipeline_{{data_type}}` into four entries, and one variant each out of `iceberg_benchmark_{{mode}}` and `iter_batches_{{format}}`. `aggregate_groups` keeps its matrix and carries the budget as a matrix dimension with explicit adjustments. **Rendered test names are unchanged — 121 before and after** — so release baselines still line up. **Not carried over** from the original branch: 7 previously-pinned entries no longer exist — the autoscaling variants removed in #65506, plus `tpch_q20` and `tpch_q22`. Any entry gaining its own `runtime_env` re-lists the four `DEFAULTS` guards verbatim: `deep_update` overwrites lists rather than merging them, so declaring one silently drops the OOM / dead-node / object-store checks. (17 entries on master are already missing guards for this reason; pre-existing, not touched here.) `map_benchmark.py` also drops its `use_datasource_v2 = False` pin, which existed because V2 was spilling. > Budgets originally measured against the pre-decoupling design and refined since. Packing moved between stages in #65596 but the packer and its inputs did not, so bins should be unchanged — a release run against this PR is what confirms that. The wide-schema tests are the first place to look. ## Behavior change worth reviewing **Read-task sizing no longer comes from `override_num_blocks` / `read_op_min_num_blocks` for Parquet.** Bins are sized by `RAY_DATA_PARQUET_BIN_PACKING_BYTES`, which is *also* not derived from `DataContext.target_max_block_size`. That decoupling is deliberate — read units are row-group-accurate rather than size-estimated — but it means the two knobs users reach for first no longer affect Parquet read parallelism. Deriving the budget from `target_max_block_size` is worth considering as a follow-up; the per-test overrides above are the evidence that a single global default does not fit every workload. ## Testing ``` $ python -m pytest -q python/ray/data/tests/datasource/test_parquet.py 286 passed, 6 skipped in 521.25s $ python -m pytest -q python/ray/data/tests/datasource/test_read_parquet_v2.py 32 passed $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/ python/ray/data/_internal/datasource_v2/tests/ 181 passed $ python -m pytest -q python/ray/data/tests/test_predicate_pushdown.py \ python/ray/data/tests/test_execution_optimizer_limit_pushdown.py 78 passed ``` The 286-test parquet suite is the one that matters — it runs the full read surface with the footer path as the default rather than behind a flag. The release YAML is additionally checked for parse validity, unresolved `{{...}}` in any pin, duplicate `byod:` keys, and rendered-name stability. ## Stack Final step of an 11-step split of #64985 (43 files / +3234 −719, not reviewable as one unit). - #65167 `[1]` · #65168 `[2]` · #65214 `[3]` · #65210 `[4]` · #65273 `[5]` · #65596 `[6]` · #65806 `[8]` · #65169 `[9]` — all merged - `[7]` (count push-down fix) was absorbed into #65596 - `[10]` (release tuning) is folded into this PR, so a release run exercises the flip and its tuning together - **this PR** `[11/11]` --- Not a duplicate. File-level overlap check: #63158 none; #65142 overlaps `file_indexer.py` / `context.py`; #65406 / #65407 (arrow-rs reader A/B) overlap broadly but are explicitly `[DO NOT MERGE]` benchmark branches carrying the footer work out-of-tree. AI assistance was used; every line reviewed by me and tests run locally. --------- Signed-off-by: Goutam <[email protected]>
…ner (ray-project#65214) ## Why A metadata-aware indexer wants the pushed-down predicate, projection, and limit at **listing** time — to prune files by their statistics, size only the projected columns, and stop listing early once enough rows are found. (The footer-based Parquet indexer, later in this split, is the first such consumer.) ## Flow ```mermaid flowchart TD R["rule loop: projection → predicate → limit → count<br/>(runs to a fixed point)"] --> S["ReadFiles.scanner<br/>final accepted state"] S -->|"pushed_predicate / pruned_column_names / pushed_limit"| D["DeriveListFilesPushdown<br/>_post_optimize, runs last"] D -->|"overwrite, unconditionally, both directions"| L["ListFiles.predicate / projected_columns / limit"] L --> P[plan_list_files_op] --> I["FileIndexer.list_files(...)<br/>plain indexer ignores them"] ``` `DeriveListFilesPushdown` recomputes every `ListFiles`' constraints from the scanner of the `ReadFiles` that consumes it. Unconditional in both directions: a `ListFiles` whose consumer is *not* a `ReadFiles` — e.g. after `PushdownCountFiles` rewrites the plan — has its constraints cleared. So a rule that weakens a scanner's predicate automatically weakens listing too, and the worst a future rule can cause is listing *more* than it needs to. It runs in `LogicalOptimizer._post_optimize`, after the rule loop reaches a fixed point, rather than as a `_LOGICAL_RULESET` entry. `get_logical_ruleset().add()` is a `@DeveloperAPI`, so a caller-registered rule could otherwise be topologically ordered *after* it and strand a stale predicate. ## What changed **The rule and its inputs** (the substance — start here): | File | Change | | --- | --- | | `logical/rules/derive_list_files_pushdown.py` | **new** — the rule | | `datasource_v2/logical_optimizers.py` | read-back accessors `pushed_predicate()` / `pushed_limit()`, plus the `derive_list_files_pushdown(scanner)` helper that `isinstance`-guards each mixin | | `datasource_v2/scanners/arrow_file_scanner.py` | implements both accessors | | `logical/operators/read_operator.py` | `ListFiles` gains `predicate` / `projected_columns` / `limit` | | `logical/optimizers.py`, `logical/rules/__init__.py` | register and export the rule | **Plumbing so an indexer can consume it** (no consumer yet): | File | Change | | --- | --- | | `datasource_v2/listing/file_indexer.py` | `list_files()` accepts the three as kwargs (the plain indexer documents that it ignores them); new `produces_partitioned_manifests` property, default `False` | | `datasource_v2/listing/listing_utils.py` | forwards the kwargs | | `planner/plan_list_files_op.py`, `read_api.py` | forward the constraints, and honor `produces_partitioned_manifests` by skipping the partitioner and listing in a single task | **Tests:** `tests/unit/datasource_v2/test_derive_list_files_pushdown.py` (new, 9 tests). Both new accessors are **concrete, defaulting to `None`**, not abstract — these are `@DeveloperAPI` mixins, and an out-of-tree scanner should keep working (just without listing-time pruning) rather than fail to instantiate on upgrade. `None` is always the safe answer. **Inert on its own** — nothing reads the derived state yet. It is separated precisely because it is the soundness argument for the feature, and much easier to review on its own than buried in a read-path rewrite. ## Stack Step 3 of an 11-step split of ray-project#64985, which was 43 files / +3234 −719 and not reviewable as one unit. - ray-project#65167 — `[1/11]` Extract `FileIndexer.list_file_infos` ✅ merged - ray-project#65168 — `[2/11]` Push limit into `ReadFiles` when `Limit` sits directly on it ✅ merged - **this PR** — `[3/11]`, unblocked by the two above (it extends the same files) - ray-project#65210 — `[4/11]` Footer types + online bin packer (open, independent) - ray-project#65169 — `[9/11]` Pin the Parquet footer actor pool to 1 in tests (open, independent) --------- Signed-off-by: Goutam <[email protected]>
…-project#65210) ## Why Groundwork for footer-based Parquet chunking (the rest of the split of ray-project#64985). Everything here is pure logic with no Ray dependency, landed on its own so it can be reviewed as an algorithm rather than as part of a read-path rewrite. Today `ParquetFileChunker` splits each file by `ceil(file_size / 1 GiB)` *without reading the footer*, and the partitioner bin-packs those guesses using a fixed encoding-ratio estimate. Bin sizes are inaccurate because the compression ratio is unknown until the footer is read. Replacing that needs a packer that works from real row-group metadata, arrives as a stream, and bounds its own memory. **Nothing calls this yet** — it is unused until the footer indexer lands. ## Flow ### The default path: pack the row groups themselves Out of the box **both coalescing and splitting are off** (`coalesce_bytes = 0`, `split_coalesced = False`). One bin item is one physical row group, and `OnlineBinPacker` First-Fits those whole items into big bins of `max_bin_bytes`. One big bin becomes one read task. Nothing is ever cut. ```mermaid flowchart LR RG["physical row groups<br/>from the footer"] --> IT["one bin item<br/>per row group"] IT --> P["OnlineBinPacker<br/>First-Fit, items stay whole"] P --> SEAL["seal + evict full big bins<br/>(max_bin_bytes)"] SEAL --> M["one big bin = one read task<br/>FileManifest + ParquetRowGroupChunkMetadata"] ``` ### Optional: a second, smaller bin size underneath Setting `coalesce_bytes > 0` inserts a **first** packing pass upstream, in the footer reader: `coalesce_row_groups` packs consecutive row groups into contiguous runs of ~`coalesce_bytes`. Each run is a *small bin*, and the packer then packs small bins into big bins instead of packing row groups directly. Fewer, larger items means fewer descriptors crossing to the driver. That raises one question the default path never has to answer: a small bin is a pre-packed bundle, so what happens when it doesn't fit in the space left in a big bin? `split_coalesced` is that answer, and it is **also opt-in**: ```mermaid flowchart TD RG["physical row groups"] -->|"optional level 1: coalesce_bytes"| SB["small bins<br/>contiguous row-group runs"] SB --> FIT{"fits in an open big bin?"} FIT -->|yes| PUT["drop it in whole"] FIT -->|"no — split_coalesced = false (default)"| NEW["keep it intact,<br/>start a new big bin"] FIT -->|"no — split_coalesced = true"| CUT["break it back into its row groups:<br/>fill the leftover space,<br/>carry the remainder onward"] PUT --> SEAL["level 2: seal + evict<br/>full big bins (max_bin_bytes)"] NEW --> SEAL CUT --> SEAL SEAL --> M["one big bin = one read task"] ``` So the three configurations are: | `coalesce_bytes` | `split_coalesced` | behaviour | | --- | --- | --- | | `0` (default) | `False` (default) | pack whole row groups into big bins | | `> 0` | `False` | pack whole small bins into big bins | | `> 0` | `True` | pack small bins, breaking one back open when it would otherwise waste the tail of a big bin | Two properties worth checking during review: - **`split_coalesced` cannot change the default path.** Without coalescing there are no small bins to break open — a bin item already *is* one row group — so the flag is inert and packing is plain First-Fit either way. Guarded by `test_split_coalesced_is_noop_without_coalescing`. - **A small bin is only ever cut at the seams it was built from.** Never mid-row-group, so every piece stays a contiguous run with exact sizes and row counts. A run larger than a whole big bin is simply cut across several of them. Orthogonal to all of the above, big bins come from two pools. A file's chunks go to a **shared** pool (mixed files) until that file's cumulative bytes exceed the cap, after which it switches to a **single-file** pool — so a large file's row groups stay contiguous instead of scattering across every open bin. Bins seal and evict as they fill, which bounds memory over an unbounded stream *and* lets read tasks start before every footer has landed. ## What changed | File | Change | | --- | --- | | `chunkers/parquet_footer_types.py` | **new** — `RowGroupInfo`, `FileChunks`, `BinItem`, `Bin`. Frozen dataclasses, no imports beyond `typing`. | | `chunkers/parquet_row_group_coalescing.py` | **new** — `coalesce_row_groups()`. A run breaks on a change in `fully_matched` (never merge across the match-class boundary, or limit push-down miscounts), a gap in `rg_idx` (filter-pruned groups), or once the accumulator is full. `target == 0` disables it. | | `partitioners/online_bin_packer.py` | **new** — `OnlineBinPacker` plus the `_BinPool` / `_SharedBinPool` / `_SingleFileBinPool` hierarchy. A file stays in the shared pool until its cumulative bytes exceed the cap, then switches to a dedicated pool so a large file's row groups stay contiguous instead of scattering across every open bin. Bins seal and evict as they fill, which bounds memory over an unbounded stream *and* lets read tasks start before every footer has landed. | | `chunkers/file_chunker.py` | **adds** `ParquetRowGroupChunkMetadata` alongside the existing `ParquetFileChunkMetadata`. Additive on purpose — the size-based chunker still needs its own metadata type until the read path switches over. | | `tests/unit/datasource_v2/test_online_bin_packer.py` | **new** — 14 tests, no Ray cluster. | 864 insertions, 0 deletions. ## Testing Coverage is aimed at the invariants rather than the happy path: that every row group is covered *exactly once* across all emitted bins (parametrized over `split_coalesced`), that splitting is a no-op without coalescing, that an oversize coalesced run is cut at boundaries and can fill residual shared-bin space, and that a full single-file bin is sealed immediately. ``` $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/test_online_bin_packer.py 14 passed in 0.05s $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/ 74 passed in 0.17s $ python -m pytest -q python/ray/data/_internal/datasource_v2/tests/ 35 passed in 0.75s ``` ## Stack Step 4 of an 11-step split of ray-project#64985, which was 43 files / +3234 −719 and not reviewable as one unit. - ray-project#65167 — `[1/11]` Extract `FileIndexer.list_file_infos` ✅ merged - ray-project#65168 — `[2/11]` Push limit into `ReadFiles` when `Limit` sits directly on it ✅ merged - ray-project#65214 — `[3/11]` Derive `ListFiles` pushdown state from the `ReadFiles` scanner (open) - **this PR** — `[4/11]`, **no merge-order dependency**: it touches a file set disjoint from every other step and applies cleanly to master on its own. - ray-project#65169 — `[9/11]` Pin the Parquet footer actor pool to 1 in tests (open, independent) Step 5 (`FooterReader`) imports `parquet_footer_types` and `parquet_row_group_coalescing` from this PR, so it follows this one. --- Not a duplicate of any open PR (checked `gh pr list --repo ray-project/ray --state open` plus a file-level overlap check; only ray-project#64985, which this replaces). AI assistance was used; every line reviewed by me and tests run locally. --------- Signed-off-by: Goutam <[email protected]>
) ## Why Footer IO for the footer-based Parquet chunking path (the rest of the split of ray-project#64985). Reading N Parquet footers serially on the driver doesn't scale — it's the step that decides which row groups a read even touches. `FooterReader` runs as a pool of Ray actors, each reading footers on its own thread pool and streaming results back in batches, so footer IO spreads across the cluster instead of bottlenecking on one process. **Nothing constructs it yet** — it's unused until the footer indexer lands in step 6. ## Flow Per file, it produces the row-group descriptors the bin packer (merged in ray-project#65210) consumes: ```mermaid flowchart LR B["(path, size) batch"] --> A["FooterReaderActor<br/>SPREAD across the cluster"] A --> R[read footer] R --> F["split_by_row_group(filter)<br/>prune by statistics"] F --> Q["split_by_row_group(~filter)<br/>classify fully_matched"] Q --> C["coalesce_row_groups<br/>(from ray-project#65210)"] C --> O["stream List[FileChunks]<br/>batched by result_batch_size"] ``` Three things it decides, each of which the packer and the limit push-down depend on: - **Predicate pruning.** `fragment.split_by_row_group(filter)` drops row groups whose Parquet statistics contradict the pushed filter, so they never reach the packer at all. - **`fully_matched` classification.** A surviving group is *fully* matched iff `~filter` prunes it entirely. Only fully-matched groups have an exact survivor count, and only exact counts may drive limit push-down. Any failure defaults to not-fully-matched, which is always the safe direction. **This is the correctness-critical bit**: nulls are the interesting case, since Parquet min/max stats are computed over non-null values only, so a group whose non-null values all satisfy the filter looks fully matched by bounds alone while its null rows don't survive. - **Projection-scoped sizing.** Byte sizes are accounted over only the projected leaf columns, so bins get sized for what the reader will actually fetch. Nested columns expand to all their leaves. ## What changed Two new files, 368 insertions, 0 deletions: | File | Change | | --- | --- | | `listing/footer_reader.py` | **new** — `FooterReader` plus `FooterReaderActor = ray.remote(FooterReader)`. Kept as a plain class with the actor built via the functional form, so callers can type handles as `ActorProxy[FooterReader]`. `read_footers` is a streaming `@ray.method` generator that yields `List[FileChunks]`, batched by `result_batch_size` — the driver pays one object-store fetch per yielded list, so batching cuts driver-side deserialization roughly proportionally. | | `tests/test_footer_reader.py` | **new** — 14 tests | ## Testing The tests drive the plain class directly against local Parquet fixtures — no actor, no cluster. Coverage is aimed at the decisions above rather than the plumbing: predicate pruning by statistics, the partial-match case (`id >= 30` splitting a row group, which must **not** count as exact), a predicate matching nothing, projection shrinking accounted size while leaving row counts alone, coalescing preserving total rows, nested columns expanding to all leaves, and result batching at several `result_batch_size` values. ``` $ python -m pytest -q python/ray/data/_internal/datasource_v2/tests/test_footer_reader.py 14 passed in 4.30s $ python -m pytest -q python/ray/data/_internal/datasource_v2/tests/ python/ray/data/tests/unit/datasource_v2/ 145 passed in 0.90s ``` ## Stack Step 5 of an 11-step split of ray-project#64985, which was 43 files / +3234 −719 and not reviewable as one unit. - ray-project#65167 `[1/11]` Extract `FileIndexer.list_file_infos` ✅ merged - ray-project#65168 `[2/11]` Push limit into `ReadFiles` when `Limit` sits directly on it ✅ merged - ray-project#65214 `[3/11]` Derive `ListFiles` pushdown state from the scanner ✅ merged - ray-project#65210 `[4/11]` Parquet footer types + online bin packer ✅ merged - **this PR** `[5/11]` — depends on ray-project#65210 for `parquet_footer_types` and `parquet_row_group_coalescing` - ray-project#65169 `[9/11]` Pin the Parquet footer actor pool to 1 in tests (open, independent) Step 6 wires this and the packer together behind an opt-in flag, and needs both this and ray-project#65214. --- Not a duplicate of any open PR (checked `gh pr list --state open` plus a file-level overlap check against ray-project#65142 / ray-project#63158 / ray-project#64404 — no overlap; only ray-project#64985, which this replaces). AI assistance was used; every line reviewed by me and tests run locally. --------- Signed-off-by: Goutam <[email protected]>
…acking as a partitioner (ray-project#65596) ## Why Parquet V2 chunks files **blindly**. `ParquetFileChunker` splits each file by `ceil(file_size / 1 GiB)` *without reading the footer*, and `RoundRobinPartitioner` bin-packs those guesses with a fixed encoding-ratio estimate. Bin sizes are inaccurate because the compression ratio is unknown until the footer is read, there is no row-group skipping, and nothing from predicate / limit / projection push-down reaches listing. This wires steps 1–5 into a working read path — the first PR in the split where the footer path is *reachable*. **Default-off.** Gated on `RAY_DATA_PARQUET_ENABLE_FOOTER_INDEXER`; without it every Parquet V2 read behaves exactly as today. Flipping the default and deleting the blind chunker are separate later steps, which keeps this reviewable and leaves a one-line revert lever. ## What this changes **1. `FooterFileIndexer` — listing that reads footers.** New indexer, returned from `_get_file_indexer()` only when the flag is set. It footer-reads files on a `FooterReader` actor pool (step 5) and emits **one listing row per row-group run**, each carrying that run's exact stats: `num_rows`, `uncompressed_size`, per-row-group `rg_sizes` / `rg_rows`, and `fully_matched`. Actor pool is killed in a `finally`, in-flight footer batches are bounded, and listing stops early once `limit` exact-survivor rows are delivered. **2. Bin packing is a `FilePartitioner`, not an indexer detail.** Listing discovers work; the partitioner groups it. `OnlineBinPacker` (step 4) becomes a real `FilePartitioner` supplied via a new `DataSourceV2.get_file_partitioner()` hook, so it runs in the normal partitioner stage and can split runs at exact row-group boundaries. `FileIndexer.produces_partitioned_manifests` is deleted in favor of `FilePartitioner.requires_global_input`, which is what tells `plan_list_files_op` to keep listing on one task. This is not just tidying — it fixes a parallelism bug. `produces_partitioned_manifests` made the planner skip the partitioner stage entirely, so with `shuffle="files"` the footer path read the **whole dataset in a single task**: `shuffle_files` concatenates every sealed bin into one manifest block, and with no partitioner downstream nothing was left to re-split it. **3. `count()` push-down.** `PushdownCountFiles` tried to force whole-file listing by overwriting the indexer's `_file_chunker`, but `FooterFileIndexer` overrides `list_files` outright and ignores its chunker, so the swap was a silent no-op. It now swaps the indexer itself via `as_whole_file_indexer()`. This is what makes (2) safe: once listing emits a row per row-group run, `read_metadata` returns the whole file's row count for *each* row, so a 4-row-group file counts 4×. The hard `assert isinstance(...)` also becomes a debug log and bail-out, so a third-party indexer falls back to the regular read path instead of crashing the optimizer. **4. `skip_paths` on the footer path.** `FooterFileIndexer` was constructed without it, so `read_parquet(..., skip_paths=...)` silently did nothing when the flag was on — excluded files were read, and a path named only in `skip_paths` could fail the listing instead of being ignored. These land together because (3) guards a bug that (2) introduces, and both touch the same listing contract. ## Flow ```mermaid flowchart TD LF[ListFiles] --> FI[FooterFileIndexer] FI --> LI["list_file_infos<br/>(step 1)"] LI --> BA[batch paths] BA --> AP["FooterReaderActor pool<br/>SPREAD (step 5)"] AP -->|one row per row-group run| SH[shuffle_files] SH --> BP["OnlineBinPacker<br/>(step 4), a FilePartitioner"] BP -->|sealed bins| MB[manifest blocks] MB --> RF[ReadFiles] RF --> PR["ParquetFileReader<br/>reads exactly the named row groups"] LF -.->|"predicate / limit / projected_columns<br/>(step 3)"| FI ``` `OnlineBinPacker.requires_global_input = True` keeps listing on a single task, since the packer holds one pool of open bins across all files. ## Files | File | Change | | --- | --- | | `listing/footer_file_indexer.py` | **new** — `FooterFileIndexer`. All knobs re-read in `__init__` so `monkeypatch.setenv` and release-test overrides apply. | | `listing/file_indexer.py` | drops `produces_partitioned_manifests`; adds `as_whole_file_indexer()` | | `partitioners/online_bin_packer.py` | now a `FilePartitioner` (`add_input`, `requires_global_input`) | | `partitioners/file_partitioner.py` | adds `requires_global_input` | | `datasource_v2.py` / `read_api.py` | new `get_file_partitioner()` hook; default stays `RoundRobinPartitioner` | | `parquet_datasource_v2.py` | flag-gated indexer + packer; wires `skip_paths` | | `planner/plan_list_files_op.py` | partitioner stage always runs; single-task listing keys off `requires_global_input` | | `rules/pushdown_count_files.py` | replaces the indexer instead of reconfiguring it | | `chunkers/file_chunker.py` | `ParquetRowGroupChunkMetadata` gains `fully_matched`, `rg_sizes`, `rg_rows` | | `chunkers/parquet_file_chunking_utils.py` | adds `_fragments_from_row_group_ids`, `_with_io_retry` | | `readers/parquet_file_reader.py` | dispatches on metadata type so both chunkers coexist; sizes batches from footer stats already on the manifest | | `readers/file_reader.py` | `_resolve_batch_size(dataset, manifest)` | ## Testing ``` pytest python/ray/data/tests/unit/datasource_v2/test_file_indexer.py \ python/ray/data/tests/unit/datasource_v2/test_online_bin_packer.py \ python/ray/data/_internal/datasource_v2/tests/test_parquet_datasource_v2.py \ python/ray/data/_internal/datasource_v2/tests/test_footer_chunking.py \ python/ray/data/tests/datasource/test_read_parquet_v2.py # 145 passed ``` The two that carry the most weight: - `test_count_matches_rows`, parametrized over `(4 files, 1000 rows, row_group_size=250)`. This is the guard for (3): without `as_whole_file_indexer()` it fails `assert 4800 == 1200`. - `test_e2e_filter_then_limit_with_nulls`, 20 files at 10% non-null over five limits. If a null were ever counted as an exact survivor, listing would stop short and `Limit` would quietly return fewer rows than asked. (The classification behind that landed in ray-project#65273.) **Known gap:** `skip_paths` has unit coverage in `test_parquet_datasource_v2.py` but no end-to-end test through `read_parquet` on the footer path. ## Stack Step 6 of an 11-step split of ray-project#64985 (43 files, +3234 −719, not reviewable as one unit). - ray-project#65167 `[1/11]` `FileIndexer.list_file_infos` ✅ · ray-project#65168 `[2/11]` limit into `ReadFiles` ✅ - ray-project#65214 `[3/11]` derive `ListFiles` pushdown state ✅ · ray-project#65210 `[4/11]` footer types + bin packer ✅ - ray-project#65273 `[5/11]` `FooterReader` actor pool ✅ - **this PR** — consumes all of the above; first step that makes the path reachable - ray-project#65169 `[9/11]` pin the footer actor pool to 1 in tests (open, independent) This PR **absorbs what was going to be step 7** (`count()` push-down), so the remaining steps renumber down by one. Step 7 can't be split out downstream of this: the packing change is what triggers the over-count, so the fix has to ship at or below it. ## AI assistance AI assistance was used for this change. I have reviewed every changed line and run the tests above locally. Not a duplicate: `gh pr list --repo ray-project/ray --state open --search "FooterFileIndexer"` and `--search "footer indexer parquet"` return only this PR, the stack members listed above, and ray-project#64985 — the mega-PR this stack is splitting up, which closes once the stack lands. --------- Signed-off-by: Goutam <[email protected]> Co-authored-by: Cursor <[email protected]>
…ay-project#65806) ## Why Two independent throughput knobs for the Parquet read task, kept out of the footer-indexer PR because each changes behavior on its own and needs its own justification. **One reader thread per fragment, instead of capping at 4.** The cap existed because the blind `ParquetFileChunker` could put an unbounded number of row groups — and therefore fragments — in a single read task, so an uncapped thread pool was a real risk. Now that ray-project#65596 has landed, read units are bin-packed to a byte budget, so the fragment count per task is bounded by construction and the cap only serializes IO that could overlap. **Size Arrow's IO/CPU pools for the read task.** Arrow's defaults (~num cores, 8 IO threads) throttle the concurrent column/range fetches a Parquet scan issues against S3. That hurts most for row-group-scoped fragments, which is exactly what the footer path now produces. ## Flow No structural change — both are sizing knobs on the existing read path: ``` ReadFiles task ├─ pa.set_io_thread_count / set_cpu_count ← new, at reader construction └─ _read_fragment_batches └─ num_workers = len(fragments) ← was min(4, len(fragments)) ``` The sequential path still applies when `DataContext.execution_options.preserve_order` is set, unchanged. ## What changed | File | Change | | --- | --- | | `readers/file_reader.py` | Drop `_DEFAULT_NUM_THREADS` / `RAY_DATA_READ_FILES_NUM_THREADS`; `num_workers = len(fragments_with_offsets)`. Also fixes the `_read_fragment_batches` docstring, which still documented the removed env var. | | `readers/parquet_file_reader.py` | `pa.set_io_thread_count()` / `pa.set_cpu_count()` at reader construction, from `RAY_DATA_PARQUET_READER_IO_THREAD_COUNT` / `RAY_DATA_PARQUET_READER_CPU_COUNT` (default 128 each; `0` disables). | **Two things worth a careful look:** - This **removes** `RAY_DATA_READ_FILES_NUM_THREADS`. It is undocumented and internal, but anyone setting it loses the knob. - `pa.set_io_thread_count` / `set_cpu_count` mutate **process-global** Arrow state from a constructor. That is deliberate — the read task is the process — but it means a non-Parquet reader sharing the worker sees the same pools. ## Stack Step 8 of an 11-step split of ray-project#64985. - ray-project#65167 `[1/11]` ✅ · ray-project#65168 `[2/11]` ✅ · ray-project#65214 `[3/11]` ✅ · ray-project#65210 `[4/11]` ✅ · ray-project#65273 `[5/11]` ✅ - ray-project#65596 `[6/11]` ✅ — footer indexer behind the flag, which also absorbed step 7's `count()` fix and moved bin packing into a `FilePartitioner` - **this PR** `[8/11]` — unblocked by ray-project#65596: the thread cap can only come off once bins are size-bounded - ray-project#65169 `[9/11]` pin the footer actor pool to 1 in tests (open, independent) Remaining after this: release-test tuning, then flipping the default and deleting the old chunker. --------- Signed-off-by: Goutam <[email protected]>
…ect#65821) ## Why The last step of the split of ray-project#64985: flip Parquet V2 to the footer read path, delete the blind one, and tune the release tests so this can be validated by a real release run. Everything it depends on has landed — footer types and the bin packer (ray-project#65210), the `FooterReader` actor pool (ray-project#65273), the indexer plus `count()` fix and packer-as-partitioner (ray-project#65596), reader IO tuning (ray-project#65806), and test env pinning (ray-project#65169). The path has been reachable behind `RAY_DATA_PARQUET_ENABLE_FOOTER_INDEXER` since ray-project#65596; this makes it the only path. ## Flow ```mermaid flowchart LR RP[read_parquet] --> FF["FooterFileIndexer<br/>+ OnlineBinPacker"] RP -.->|deleted| PC["ParquetFileChunker<br/>size-estimated chunks<br/>+ parquet_chunker_target_chunk_size"] style PC stroke-dasharray: 4 4 ``` ## What changed **The flip** — `RAY_DATA_PARQUET_ENABLE_FOOTER_INDEXER` is gone from both call sites. `_get_file_indexer()` always returns `FooterFileIndexer`; `get_file_partitioner()` always returns `OnlineBinPacker`. **The deletions** — `ParquetFileChunker`, `ParquetFileChunkMetadata`, `_calculate_row_group_range`, `_fragments_from_chunk_metadata`, and the tests covering only that path. **The config it left behind** — `DataContext.parquet_chunker_target_chunk_size` and `DEFAULT_PARQUET_CHUNKER_TARGET_CHUNK_SIZE` were read *only* by `ParquetFileChunker.__init__`, so they would otherwise stay declared and documented while doing nothing. Verified dead by grep across `.py` / `.yaml` / `.rst` / `.md`. **Reader pool defaults** — `RAY_DATA_PARQUET_READER_IO_THREAD_COUNT` 128, `RAY_DATA_PARQUET_READER_CPU_COUNT` 32. ## Release tests tuned Budgets are per-test overrides of `RAY_DATA_PARQUET_BIN_PACKING_BYTES` (uncompressed bytes of row-group data per read task; default 128 MiB). The shape of the tuning: reads over few large groups want **large** bins, because small bins shatter the read into short tasks the executor cannot dispatch fast enough and the cluster idles; shuffle-bound reads over many groups want **small** bins. Rows whose variants all share the same tuning are collapsed and marked. | release test | bin budget | other tuning | | --- | --- | --- | | `aggregate_groups_fixed_size_hash_shuffle_column02 column14` | 32 MiB | — | | `aggregate_groups_fixed_size_hash_shuffle_column08 column13 column14` | 128 MiB | — | | `aggregate_groups_fixed_size_shuffle_v2_column02 column14` | 64 MiB | — | | `aggregate_groups_fixed_size_shuffle_v2_column08 column13 column14` | 512 MiB | — | | `aggregate_groups_fixed_size_sort_shuffle_pull_based_column02 column14` | 32 MiB | — | | `aggregate_groups_fixed_size_sort_shuffle_pull_based_column08 column13 column14` | 256 MiB | — | | `count_parquet_fixed_size` | 64 MiB | — | | `cross_az_map_batches_autoscaling_iptable_failure_injection` | 1 GiB | — | | `distributed_training` | — | footer actors `20` | | `flat_map` | 64 MiB | — | | `iceberg_benchmark_overwrite` | 64 MiB | — | | `iter_batches_pyarrow` | 64 MiB | — | | `iter_torch_batches` | 64 MiB | — | | `joins_{{dataset}}_{{join_type}} *(all 4 variants)*` | 1.25 GiB | — | | `map` | 64 MiB | — | | `map_batches_fixed_size_{{compute}}_{{format}}_{{repeat_map_batches}} *(all 7 variants)*` | 1 GiB | scale-up threshold `0.6` | | `map_groups_fixed_size_{{shuffle_strategy}}_{{columns}} *(all 6 variants)*` | 1.25 GiB | — | | `mix` | — | footer actors `4` | | `random_shuffle_fixed_size` | 64 MiB | — | | `read_large_parquet_fixed_size` | 1 GiB | — | | `read_parquet_fixed_size` | 64 MiB | — | | `read_tfrecords` | 64 MiB | — | | `streaming_split` | 64 MiB | footer batch `50`, result batch `50` | | `to_tf` | 64 MiB | — | | `tpch_q1_fixed_size_{{shuffle_strategy}} *(all 2 variants)*` | 192 MiB | — | | `training_ingest_benchmark` | 64 MiB | — | | `wide_schema_pipeline_nested_structs` | 2 MiB | footer batch `1`, footer actors `21`, io threads `5000` | | `wide_schema_pipeline_objects` | 4.2 MiB | footer batch `1`, footer actors `9`, io threads `5000` | | `wide_schema_pipeline_primitives` | 256 KiB | footer batch `1`, footer actors `27`, io threads `5000` | | `wide_schema_pipeline_tensors` | 39 MiB | footer batch `1`, footer actors `22`, io threads `5000` | | `write_parquet` | 1.25 GiB | — | **Three matrices are split**, because a matrix cannot vary `byod.runtime_env` per value and their variants want different budgets: `wide_schema_pipeline_{{data_type}}` into four entries, and one variant each out of `iceberg_benchmark_{{mode}}` and `iter_batches_{{format}}`. `aggregate_groups` keeps its matrix and carries the budget as a matrix dimension with explicit adjustments. **Rendered test names are unchanged — 121 before and after** — so release baselines still line up. **Not carried over** from the original branch: 7 previously-pinned entries no longer exist — the autoscaling variants removed in ray-project#65506, plus `tpch_q20` and `tpch_q22`. Any entry gaining its own `runtime_env` re-lists the four `DEFAULTS` guards verbatim: `deep_update` overwrites lists rather than merging them, so declaring one silently drops the OOM / dead-node / object-store checks. (17 entries on master are already missing guards for this reason; pre-existing, not touched here.) `map_benchmark.py` also drops its `use_datasource_v2 = False` pin, which existed because V2 was spilling. > Budgets originally measured against the pre-decoupling design and refined since. Packing moved between stages in ray-project#65596 but the packer and its inputs did not, so bins should be unchanged — a release run against this PR is what confirms that. The wide-schema tests are the first place to look. ## Behavior change worth reviewing **Read-task sizing no longer comes from `override_num_blocks` / `read_op_min_num_blocks` for Parquet.** Bins are sized by `RAY_DATA_PARQUET_BIN_PACKING_BYTES`, which is *also* not derived from `DataContext.target_max_block_size`. That decoupling is deliberate — read units are row-group-accurate rather than size-estimated — but it means the two knobs users reach for first no longer affect Parquet read parallelism. Deriving the budget from `target_max_block_size` is worth considering as a follow-up; the per-test overrides above are the evidence that a single global default does not fit every workload. ## Testing ``` $ python -m pytest -q python/ray/data/tests/datasource/test_parquet.py 286 passed, 6 skipped in 521.25s $ python -m pytest -q python/ray/data/tests/datasource/test_read_parquet_v2.py 32 passed $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/ python/ray/data/_internal/datasource_v2/tests/ 181 passed $ python -m pytest -q python/ray/data/tests/test_predicate_pushdown.py \ python/ray/data/tests/test_execution_optimizer_limit_pushdown.py 78 passed ``` The 286-test parquet suite is the one that matters — it runs the full read surface with the footer path as the default rather than behind a flag. The release YAML is additionally checked for parse validity, unresolved `{{...}}` in any pin, duplicate `byod:` keys, and rendered-name stability. ## Stack Final step of an 11-step split of ray-project#64985 (43 files / +3234 −719, not reviewable as one unit). - ray-project#65167 `[1]` · ray-project#65168 `[2]` · ray-project#65214 `[3]` · ray-project#65210 `[4]` · ray-project#65273 `[5]` · ray-project#65596 `[6]` · ray-project#65806 `[8]` · ray-project#65169 `[9]` — all merged - `[7]` (count push-down fix) was absorbed into ray-project#65596 - `[10]` (release tuning) is folded into this PR, so a release run exercises the flip and its tuning together - **this PR** `[11/11]` --- Not a duplicate. File-level overlap check: ray-project#63158 none; ray-project#65142 overlaps `file_indexer.py` / `context.py`; ray-project#65406 / ray-project#65407 (arrow-rs reader A/B) overlap broadly but are explicitly `[DO NOT MERGE]` benchmark branches carrying the footer work out-of-tree. AI assistance was used; every line reviewed by me and tests run locally. --------- Signed-off-by: Goutam <[email protected]>

Why
Groundwork for footer-based Parquet chunking (the rest of the split of #64985). Everything here is pure logic with no Ray dependency, landed on its own so it can be reviewed as an algorithm rather than as part of a read-path rewrite.
Today
ParquetFileChunkersplits each file byceil(file_size / 1 GiB)without reading the footer, and the partitioner bin-packs those guesses using a fixed encoding-ratio estimate. Bin sizes are inaccurate because the compression ratio is unknown until the footer is read. Replacing that needs a packer that works from real row-group metadata, arrives as a stream, and bounds its own memory.Nothing calls this yet — it is unused until the footer indexer lands.
Flow
The default path: pack the row groups themselves
Out of the box both coalescing and splitting are off (
coalesce_bytes = 0,split_coalesced = False). One bin item is one physical row group, andOnlineBinPackerFirst-Fits those whole items into big bins ofmax_bin_bytes.One big bin becomes one read task. Nothing is ever cut.
Optional: a second, smaller bin size underneath
Setting
coalesce_bytes > 0inserts a first packing pass upstream, in the footerreader:
coalesce_row_groupspacks consecutive row groups into contiguous runs of~
coalesce_bytes. Each run is a small bin, and the packer then packs small bins intobig bins instead of packing row groups directly. Fewer, larger items means fewer
descriptors crossing to the driver.
That raises one question the default path never has to answer: a small bin is a
pre-packed bundle, so what happens when it doesn't fit in the space left in a big bin?
split_coalescedis that answer, and it is also opt-in:flowchart TD RG["physical row groups"] -->|"optional level 1: coalesce_bytes"| SB["small bins<br/>contiguous row-group runs"] SB --> FIT{"fits in an open big bin?"} FIT -->|yes| PUT["drop it in whole"] FIT -->|"no — split_coalesced = false (default)"| NEW["keep it intact,<br/>start a new big bin"] FIT -->|"no — split_coalesced = true"| CUT["break it back into its row groups:<br/>fill the leftover space,<br/>carry the remainder onward"] PUT --> SEAL["level 2: seal + evict<br/>full big bins (max_bin_bytes)"] NEW --> SEAL CUT --> SEAL SEAL --> M["one big bin = one read task"]So the three configurations are:
coalesce_bytessplit_coalesced0(default)False(default)> 0False> 0TrueTwo properties worth checking during review:
split_coalescedcannot change the default path. Without coalescing there are nosmall bins to break open — a bin item already is one row group — so the flag is inert
and packing is plain First-Fit either way. Guarded by
test_split_coalesced_is_noop_without_coalescing.every piece stays a contiguous run with exact sizes and row counts. A run larger than a
whole big bin is simply cut across several of them.
Orthogonal to all of the above, big bins come from two pools. A file's chunks go to a
shared pool (mixed files) until that file's cumulative bytes exceed the cap, after
which it switches to a single-file pool — so a large file's row groups stay contiguous
instead of scattering across every open bin. Bins seal and evict as they fill, which
bounds memory over an unbounded stream and lets read tasks start before every footer has
landed.
What changed
chunkers/parquet_footer_types.pyRowGroupInfo,FileChunks,BinItem,Bin. Frozen dataclasses, no imports beyondtyping.chunkers/parquet_row_group_coalescing.pycoalesce_row_groups(). A run breaks on a change infully_matched(never merge across the match-class boundary, or limit push-down miscounts), a gap inrg_idx(filter-pruned groups), or once the accumulator is full.target == 0disables it.partitioners/online_bin_packer.pyOnlineBinPackerplus the_BinPool/_SharedBinPool/_SingleFileBinPoolhierarchy. A file stays in the shared pool until its cumulative bytes exceed the cap, then switches to a dedicated pool so a large file's row groups stay contiguous instead of scattering across every open bin. Bins seal and evict as they fill, which bounds memory over an unbounded stream and lets read tasks start before every footer has landed.chunkers/file_chunker.pyParquetRowGroupChunkMetadataalongside the existingParquetFileChunkMetadata. Additive on purpose — the size-based chunker still needs its own metadata type until the read path switches over.tests/unit/datasource_v2/test_online_bin_packer.py864 insertions, 0 deletions.
Testing
Coverage is aimed at the invariants rather than the happy path: that every row group is covered exactly once across all emitted bins (parametrized over
split_coalesced), that splitting is a no-op without coalescing, that an oversize coalesced run is cut at boundaries and can fill residual shared-bin space, and that a full single-file bin is sealed immediately.Stack
Step 4 of an 11-step split of #64985, which was 43 files / +3234 −719 and not reviewable as one unit.
[1/11]ExtractFileIndexer.list_file_infos✅ merged[2/11]Push limit intoReadFileswhenLimitsits directly on it ✅ merged[3/11]DeriveListFilespushdown state from theReadFilesscanner (open)[4/11], no merge-order dependency: it touches a file set disjoint from every other step and applies cleanly to master on its own.[9/11]Pin the Parquet footer actor pool to 1 in tests (open, independent)Step 5 (
FooterReader) importsparquet_footer_typesandparquet_row_group_coalescingfrom this PR, so it follows this one.Not a duplicate of any open PR (checked
gh pr list --repo ray-project/ray --state openplus a file-level overlap check; only #64985, which this replaces).AI assistance was used; every line reviewed by me and tests run locally.