Repository navigation
[Data] DataSourceV2: file-affinity partitioning + bounded-memory reads - #64404
abhishekverma-ray wants to merge 25 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a file-affinity partitioning strategy (FileAffinityPartitioner) for DataSourceV2 to preserve file locality, along with a legacy byte-estimate Parquet chunker (ByteEstimateParquetFileChunker) and several configuration knobs in DataContext to control partitioning, batch sizes, and read concurrency. The review feedback points out two key improvements: first, the sort_key extraction in FileAffinityPartitioner should be expanded to support other metadata types (like LineDelimitedFileChunkMetadata and ByteEstimateParquetFileChunkMetadata) so chunks are sorted correctly; second, generic configuration names should be used instead of Parquet-prefixed ones in the generic V2 read path to avoid confusing users of other file formats.
7a3180f to
295630d
Compare
295630d to
cf9ece7
Compare
ae484d3 to
85f43ca
Compare
85f43ca to
bf87db5
Compare
…weights FileAffinityPartitioner.add_input coerced each chunk's estimated in-memory size to an int (_finite_int) before accumulating it into _WeightedBucket's float weight. estimate_in_memory_sizes returns floats (footer hints or on_disk_size * encoding ratio), so per-chunk truncation made the running weight drift below the true total, delaying the max_bucket_size flush. Add _finite_float (mirrors in_memory_size_estimator's _as_finite_float) and use it for the weight argument; _finite_int is now used only for file_size, which is genuinely integral. Also log once (debug) when a chunk falls back to the on_disk_size * ratio estimate due to a missing footer-derived hint, so a missing hint is observable rather than silent. Found by cursor[bot] review on ray-project#64404. Signed-off-by: Abhishek Verma <[email protected]>
eb05a2a to
fab28ff
Compare
3ad99f0 to
fab28ff
Compare
1694172 to
9444137
Compare
…s check Two small fixes from cursor[bot] review on ray-project#64404, both verified against current code before fixing: 1. fragments_to_read_for_manifest emitted all whole-file fragments before any chunked fragments, regardless of the manifest's actual arrival order. A packed partition (FileAffinityPartitioner) mixing a whole-file entry with normal chunked files could therefore emit rows out of order, breaking preserve_order. Now tracks each distinct path's first-appearance order and emits in that order. 2. _estimate_v2_read_size_bytes's "is the sample exact" check compared a raw file count against the sample's row count, but FileManifest rows are per-chunk, not per-file -- a single file with more row-group chunks than the schema-inference sample's cap (16) could satisfy total_files <= len(sample) while the sample only covers a truncated prefix of that file's chunks, silently under-counting its size. Now checks whether the sample was actually truncated by its own cap (len(sample) < sample_max_files), sharing one constant between the sample_files() call and the estimate so they can't drift apart. Signed-off-by: Abhishek Verma <[email protected]>
…idable DEFAULT_PARTITIONER_MAX_BUCKET_SIZE_BYTES was a plain literal, unlike its sibling read-path knobs (DEFAULT_READ_FILES_NUM_THREADS, DEFAULT_ARROW_SCANNER_BATCH_READAHEAD), which are both env_integer-backed -- so there was no way to tune it from the command line; the only path was ctx.partitioner_max_bucket_size_bytes = ... in application code. Wrap it in env_integer, matching the existing pattern, so RAY_DATA_PARTITIONER_MAX_BUCKET_SIZE_BYTES=<bytes> tunes both the overflow- split threshold and the file-packing threshold with no code change on either side. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
cursor[bot] flagged that FileManifest.shuffle permutes individual manifest rows (one row per chunk, not per file), so a multi-row-group file's chunks can arrive at FileAffinityPartitioner non-contiguously when shuffle="files" is active. The partitioner's flush-on-path-change pipelining treats every path change as "previous file complete," so a scattered file can fragment across several small partitions instead of staying in one, even though its total in-memory size never approached max_bucket_size -- confirmed with a concrete repro: a 3-weight file interleaved with two 3-weight files under a cap of 4 split into 3 separate partitions instead of 1. This is an efficiency/locality regression, not a data-correctness bug -- every row group still gets read exactly once (fragments_to_read_for_manifest groups by path and re-sorts row groups from explicit chunk metadata, independent of manifest row order), just via more, smaller read tasks than necessary, each needing its own file open and footer read. Add assume_contiguous_files (default True, preserving current behavior) to FileAffinityPartitioner's constructor; AND it into the existing RAY_DATA_PARTITIONER_PIPELINE_FLUSH kill switch. read_api.py passes assume_contiguous_files=(shuffle is None) at its one production construction site. This costs zero pipelining benefit under shuffle: shuffle_files already materializes the whole manifest into a single block and plan_list_files_op forces should_parallelize=False when shuffling, so the partitioner receives the entire shuffled manifest in at most one add_input() call regardless -- there was never a multi-call streaming window to pipeline across in that mode. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
acb3344 to
eb7dd32
Compare
Raise partitioner_max_bucket_size_bytes default back to 1 GiB so the read-output block count (and thus the hash-shuffle partition count, one map task per read output block) stays bounded to the aggregator pool rather than oversubscribing it. A 1 GiB partition still streams its decode with a capped pre_buffer, so per-task memory stays flat. Bump ReadFiles num_threads 2->4 and arrow scanner batch readahead 4->8 for more in-task I/O overlap, and add debug logging to _resolve_num_read_workers. Signed-off-by: Goutam <[email protected]>
…lback Extract the byte-identical None/NaN->0 coercion helpers (_finite_float in FileAffinityPartitioner and _as_finite_float in the in-memory size estimator, plus the sibling _finite_int) into a shared datasource_v2/coercion.py as finite_int/finite_float so a future fix can't drift between copies. Fix the parquet reader's target_block_size resolution: it used a falsy `x or target_max_block_size`, so an explicitly set 0 was treated as missing. Use `is not None` to match the documented "None falls back" contract and the resolution used for partitioner_max_bucket_size_bytes and parquet_chunker_target_chunk_size. Signed-off-by: Goutam <[email protected]>
test_partitioner_max_bucket_size_bytes_default_is_256_mib asserted the default was 256 MiB and the companion env test hardcoded 256 MiB as the env_integer fallback, but this PR sets the default to 1 GiB. Remove both rather than re-pin them to a magic number that duplicates the module default and would drift again on the next retune. Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
# Conflicts: # python/ray/data/_internal/datasource_v2/listing/file_indexer.py
Drops the plan-time LIST walk that expanded user paths/prefixes into concrete files before sharding across listing tasks, along with the RAY_DATA_LIST_FILES_EXPAND_PATHS / RAY_DATA_LIST_FILES_EXPAND_NUM_WORKERS context flags that gated it. Listing now shards the raw input paths and each task lists + reads footers for its share; per-directory fan-out is handled inside the listing task. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Goutam <[email protected]>
Add a PushdownCountFiles optimizer rule that rewrites Count on top of a DataSourceV2 ReadFiles into a MapBatches over ListFiles that sums per-file row counts from metadata (e.g. Parquet footers), avoiding a full data read. Introduce the SupportsMetadata reader interface and implement it for the Parquet file reader. The rule only fires when no row-reducing pushdown (predicate/limit) would make the footer row count an overcount. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
- file_affinity_partitioner: cast chunk metadata to a plain dict for the runtime key discrimination (base ChunkMetadata TypedDict declares no keys) - pushdown_count_files: narrow reader to SupportsMetadata in the count_rows closure, assert NonSamplingFileIndexer before mutating the chunker, retype the batch as pa.Table, guard Optional num_rows, suppress bad-override - Remove _enable_read_files_fusion_override and read-files fusion plumbing - Benchmark and release-test config tweaks Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
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 d4cf84b. Configure here.
| ) | ||
| # Kill switch: when False, every completed file emits its own | ||
| # standalone partition (pre-packing behavior). | ||
| self._pack_files = env_bool("RAY_DATA_PARTITIONER_PACK_FILES", False) |
There was a problem hiding this comment.
File packing default off
Medium Severity
FileAffinityPartitioner documents that small-file packing is on by default via RAY_DATA_PARTITIONER_PACK_FILES=1, but env_bool uses default False. Without the env var, each small file becomes its own read partition instead of next-fit packing, inflating task count and hurting locality. Unit tests that assume packing at default (e.g. test_file_affinity_contiguous_input_packs_across_runs_pack_enabled) expect the documented behavior.
Reviewed by Cursor Bugbot for commit d4cf84b. Configure here.
| at plan time. | ||
| """ | ||
| return self._ignore_missing_paths | ||
|
|
There was a problem hiding this comment.
Empty resolved path assertion
Medium Severity
Listing assumes len(resolved_paths) == 1 after _resolve_paths_and_filesystem, but resolution can skip invalid paths and return an empty list. With ignore_missing_paths=True, that raises AssertionError instead of skipping the input like _get_file_infos does elsewhere.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit d4cf84b. Configure here.
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
|
This pull request has been automatically closed because there has been no more activity in the 14 days Please feel free to reopen or open a new pull request if you'd still like this to be addressed. Again, you can always ask for help on our discussion forum or Ray's public slack channel. Thanks again for your contribution! |
## 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]>
) ## 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]>


Description
This reshapes the
ParquetDatasourceV2read path to be file-local and memory-bounded, with partition sizing driven by real footer metadata instead of a flat encoding ratio. It builds on the merged row-group-aware Parquet chunker (#64301).The net change removes ~980 lines: the V2 read path collapses to a single, coherent story — row-group-aware chunking + file-affinity partitioning + coalesced single-scan reads — and several experimental knobs/paths are dropped.
Related issues
DATA-2229 - Add abstractions in Datasource V2 to read sub file fragments to evenly distribute the work
Additional information
What changed
1.
FileAffinityPartitioner— the V2 partitioning strategy.Keeps all of a file's chunks in that file's own size-bounded partitions: one read task → one file → one open + one cached footer + sequential I/O (locality), while a large file still splits into multiple partitions (sub-file parallelism). The partition count is data-driven (no
num_buckets). It reuses the shared_WeightedBucketprimitive.2. Footer-derived, type-aware in-memory size estimate.
The chunker already reads each file's footer at listing time (for row-group boundaries); it now also stamps each chunk's decoded Arrow size onto its metadata:
parquet_in_memory_var_width_factor, plus offset/validity buffers.FooterDerivedInMemorySizeEstimatorreads that hint, so the partitioner sizes partitions by the real decoded footprint (per-file compression/encoding) instead of a flat 5× on-disk ratio. It falls back toon-disk × ratioper chunk when no footer hint exists (corrupt footer / non-Parquet).3. Coalesced, streaming reads.
The reader coalesces a partition's contiguous row groups into a single PyArrow scan (one open, shared footer, sequential I/O) rather than one scan per row group. Per-task fragment-read concurrency is keyed on the distinct file count, so same-file sub-scans stay sequential and the decode streams (≈ batch × readahead in flight) instead of materializing the whole partition.
DataContext knobs
partitioner_max_bucket_size_bytesparquet_reader_target_batch_size_bytesparquet_in_memory_var_width_factorread_files_num_threadsarrow_scanner_batch_readaheadRemoved (all were V2-read-path-only and unreleased): the legacy byte-estimate chunker + its
parquet_chunker_row_group_awareflag,parquet_reader_max_coalesced_scan_bytes(contiguous row groups now coalesce unconditionally), and the round-robin partitioner + itspartitioner_strategyknob.Configuring per read
Scope / notes
Tests
Coverage across the chunker (incl. the type-aware in-memory estimate), the partitioner (incl.
FooterDerivedInMemorySizeEstimator), the reader, andDataContext.