Repository navigation
[Data] Footer-based row-group chunking + online bin packing for Parquet V2 - #64985
goutamvenkat-anyscale wants to merge 26 commits into
Conversation
…et V2 Replace the blind, size-based ParquetFileChunker + RoundRobinPartitioner path for Parquet V2 reads with a FooterFileIndexer that reads each file's Parquet footer on a pool of FooterReader actors (SPREAD across the cluster) and packs row groups into read units with an online, locality-preserving bin packer. This makes read units row-group-accurate instead of size-estimated, and adds predicate pushdown + row-group skipping and limit pushdown into listing: the optimizer rules mirror the pushed predicate/projection/limit from the ReadFiles scanner onto the upstream ListFiles (sync_list_files_pushdown), so the footer actors prune row groups by statistics, size only projected columns, and stop listing early under a limit. Optional row-group coalescing + split-packing are supported and gated (no-op by default). The footer indexer reuses the generic FileIndexer abstraction (ListFiles drives it via the ordinary list_files transform, yields_read_units=True so it lists in a single task and skips the partitioner). The blind ParquetFileChunker / ParquetFileChunkMetadata and their size-based row-group range helpers are removed; the reader now reads exactly the row groups a bin names. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Goutam <[email protected]>
LimitPushdownRule._push_limit_down returned early ("no row-preserving ops")
when a Limit was directly above ReadFiles, so it never applied the per-block
limit -> the scanner limit and (footer path) ListFiles.limit were left unset.
The footer indexer then read every file's footer regardless of the limit.
Push the per-block limit into a directly-attached ReadFiles (keeping the Limit
on top for exact enforcement), which also mirrors the limit onto ListFiles via
sync_list_files_pushdown so the footer indexer stops listing early. Scoped to
ReadFiles to keep other sources unchanged.
read_parquet(s3://...).limit(10_000) on a 260-file dataset: ~9.8s -> ~3.1s.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Goutam <[email protected]>
Follow-up refinements on the footer-based row-group chunking path: - Carry projection-scoped uncompressed_size on ParquetRowGroupChunkMetadata so the reader sizes batches from footer stats ListFiles already read, instead of re-reading the footer in the read task. - Read the exact physical row groups a bin assigned via explicit row_group_ids fragments (_fragments_from_row_group_ids), scanning a file's groups together unless row hashing needs per-group offsets. - Size Arrow's process-wide IO/CPU thread pools per read task so a scan can issue many concurrent column/range fetches against S3 (RAY_DATA_PARQUET_READER_IO_THREAD_COUNT / _CPU_COUNT). - Add RAY_DATA_PARQUET_FOOTER_MAX_INFLIGHT_BATCHES to bound the in-flight footer-batch window independently of actor count. - Use a fixed fallback bin budget (RAY_DATA_PARQUET_FOOTER_BIN_BYTES, default 1 GiB) for read-task packing. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces a footer-based Parquet chunking and bin-packing path for Ray Data's DataSourceV2, replacing the estimated size-based chunker with a metadata-aware FooterFileIndexer and an OnlineBinPacker to produce accurate, row-group-aligned read units. The feedback highlights several critical improvements: capping the number of worker threads in FileReader to prevent thread exhaustion, validating num_actors in FooterFileIndexer to avoid a potential division-by-zero error, optimizing actor creation when processing few paths, and immediately evicting full bins in OnlineBinPacker to maintain packing efficiency.
| return | ||
|
|
||
| num_workers = min(_DEFAULT_NUM_THREADS, len(fragments_with_offsets)) | ||
| num_workers = len(fragments_with_offsets) |
There was a problem hiding this comment.
Setting num_workers to len(fragments_with_offsets) without an upper bound can lead to unbounded thread creation when there are many fragments (e.g., hundreds of row groups). This can cause thread exhaustion, high context-switching overhead, or RuntimeError: can't start new thread. Consider capping num_workers to a reasonable maximum (e.g., 32).
| num_workers = len(fragments_with_offsets) | |
| num_workers = min(32, len(fragments_with_offsets)) |
| ) | ||
| self._coalesce_bytes = coalesce_bytes | ||
| self._split_coalesced = split_coalesced | ||
| self._num_actors = num_actors if num_actors is not None else _DEFAULT_NUM_ACTORS |
There was a problem hiding this comment.
If num_actors is configured to 0 (or _DEFAULT_NUM_ACTORS is set to 0 via environment variables), self._num_actors will be 0. This will result in an empty actors list, causing a ZeroDivisionError in _read_and_pack at actors[batch_no % len(actors)]. Please add a validation check to ensure num_actors is at least 1.
self._num_actors = num_actors if num_actors is not None else _DEFAULT_NUM_ACTORS
if self._num_actors < 1:
raise ValueError(f"num_actors must be at least 1, got {self._num_actors}")| actors: List[ActorProxy[FooterReader]] = [ | ||
| FooterReaderActor.options(scheduling_strategy="SPREAD").remote( | ||
| filesystem, | ||
| self._io_concurrency, | ||
| predicate, | ||
| projected_columns, | ||
| self._coalesce_bytes, | ||
| ) | ||
| for _ in range(self._num_actors) | ||
| ] |
There was a problem hiding this comment.
Spawning self._num_actors (default 32) actors upfront can be extremely slow and wasteful when the input contains only a few paths (e.g., a single file). Since paths is a BlockColumn (PyArrow array), we can cheaply check its length and cap the number of spawned actors to len(paths) (with a minimum of 1) to avoid unnecessary actor creation overhead.
num_actors = min(self._num_actors, max(1, len(paths)))
actors: List[ActorProxy[FooterReader]] = [
FooterReaderActor.options(scheduling_strategy="SPREAD").remote(
filesystem,
self._io_concurrency,
predicate,
projected_columns,
self._coalesce_bytes,
)
for _ in range(num_actors)
]A shared bin at or over cap can never accept another positive-size item, so leaving it in the pool just burns one of the max_shared_open_bins slots and delays draining. Seal and evict it immediately from both the whole-item fast path and the best-fit split loop. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
`PushdownCountFiles` rebuilt `ListFiles` by deep-copying the existing indexer and overwriting its `_file_chunker`. `FooterFileIndexer` subclasses `NonSamplingFileIndexer`, so the `isinstance` assert passed -- but it overrides `list_files` outright and never reads the chunker, so the swap was a silent no-op. The result on `count_parquet_fixed_size` (10k files): listing still footer-swept every file, and because `count()` projects to zero columns every row group measured 0 bytes, so the bin cap was never reached and the whole dataset collapsed into one bin -- one manifest block, one count task that then re-read all 10k footers serially. 30.5s -> 219.8s. Build the plain indexer explicitly via a new `NonSamplingFileIndexer.as_whole_file_indexer()`, and bail out rather than assert when the indexer isn't one (the assert was stripped under -O, which is the same failure mode as this bug). This restores one manifest row per file and parallel count tasks, and removes a latent over-count: the bin packer emits one row per path per bin, so a file spanning bins would have been counted more than once. Adds the first test coverage for the rule, including an exact-type assertion on the rebuilt indexer -- an isinstance check is what let the footer indexer through. Also in this commit: - lower the bin-packing default from 1 GiB to 64 MiB - expose `max_shared_open_bins` via `RAY_DATA_PARQUET_BIN_PACKING_MAX_SHARED_OPEN_BINS` - experiment env vars on the `wide_schema_pipeline` release test - `map_benchmark` reads via V2 instead of pinning V1 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
…gets ## Listing parallelism `ListFiles` forced single-task listing whenever the indexer sets `yields_read_units` -- i.e. always, for Parquet V2 -- on the grounds that the bin packer "must see the whole file stream to pack globally". But the V1 partitioner it replaced also runs inside each listing task, so global packing was never the status quo, and the cost is real: a read that hands in explicit paths loses listing parallelism entirely. `distributed_training` passes 200 explicit parquet paths. Master sharded them across 200 listing tasks (3.00s); the footer path did all 200 footer reads in one (5.81s), ~65% of that test's +15% regression, with block count and block size otherwise identical to master. Drop `yields_read_units` from the `should_parallelize` condition. Only the shuffle-RNG case still needs a single task. Reads that pass one directory -- the common case -- shard to one task either way and are unaffected. The footer reader pool is provisioned per `list_files` call, so it is now per listing task rather than cluster-wide. Documented as such on `RAY_DATA_PARQUET_FOOTER_NUM_ACTORS`, and `distributed_training` sets it to 1 since each of its tasks reads a single footer. ## Per-test bin budgets The 64 MiB default is right for some datasets and badly wrong for others, because the useful budget tracks per-file projected bytes -- which ranges from 0.45 MiB to 3.87 GiB across the suite, and varies with the query's projection on the same table. Measured from parquet footers and verified against the V1 partitioner's block counts: - read_large_parquet 4 GiB (3.87 GiB/file; 64 MiB -> 5768 tasks) - write_parquet, joins, 1.25 GiB (~1.17 GiB/file, full schema) aggregate_groups, map_groups - tpch_q20 192 MiB (160 MiB/file, 4-column projection) - streaming_split 36 MiB (V1 landed on ~31 MB blocks here) The map_groups value also fixes four outright failures, not just a slowdown: `map_groups_*_sort_shuffle_pull_based` OOM'd the driver at 64 MiB. Pull-based shuffle holds `input_blocks * output_blocks` object refs on the driver, so at 2500 blocks that is 17.5 GiB (observed 21.6 GiB RSS, cgroup kill). At 1.25 GiB it is ~95 blocks and 0.03 GiB. `wide_schema` gets no budget: those datasets are 10-40 MB total across 9-27 single-row-group files, so every budget from 64 MiB up packs them into one bin. They need a minimum-block-count floor instead. `mix` gets no budget either -- it already matches V1 granularity -- only a narrower reader pool, since it opens 8 datasets over the same 513-file path. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
…tunable ## Revert: parallel listing for the footer indexer 71a1bf2 dropped `yields_read_units` from `should_parallelize` so a read handing in explicit paths would shard listing across tasks. Release build 102070 shows that was wrong. `FooterFileIndexer.list_files` pays a fixed cost *per call* -- provisioning a reader-actor pool, building a packer, serializing manifests -- so N tasks pay it N times instead of splitting it. On `distributed_training` (200 explicit paths) each of 200 listing tasks took 55.9s, 50.7s of it in block generation, against 5.35s for one task doing all 200. Aggregate listing work went 5.35 -> 11,180 task-seconds. `distributed_training.chaos` went +21% -> +463% vs master; `.regular` +15% -> +28%. Restore the original condition. Parallel listing here needs a pool shared across tasks, not one per task, which is a larger change. ## RAY_DATA_PARQUET_FOOTER_RESULT_BATCH_SIZE `read_footers` has always taken `result_batch_size` to amortize driver-side object-store fetches, but the indexer never passed it, so it defaulted to 1: a directory of N files costs N fetches on the single listing task (7.4k for the imagenet dataset). Plumb it through as an env-backed setting, default 1 so behavior is unchanged. Note it batches *within* one `read_footers` call, so it saturates at `RAY_DATA_PARQUET_FOOTER_BATCH_SIZE`; both have to move together. ## Release test config - `streaming_split`: batch sizes 50/50, cutting driver fetches ~7.4k -> ~149. ListFiles dominates this test (15.5s of a 26.6s run) and its cost tracks results pulled back, not footer IO -- raising the actor pool 32 -> 128 left block generation flat at ~7 ms/block. Bin budget reverted to the default: 36 MiB was matching V1's block size, but V1 only lands on ~31 MB blocks because its 5x encoding estimate over-counts by 5x on image data that does not compress. Matching it doubles the block count and makes the dominant cost worse. - `distributed_training`: footer actors 1 -> 20. 200 paths at a batch size of 10 is 20 batches, so actors past the 20th are never dispatched to. Also carried: `@ray.method(num_returns="streaming")` on `read_footers`, re-reading the actor count at construction so env overrides apply after import, a `None`-size guard in `sample_files`, and `None`-safety in the bin packer's heavy path. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
Release-test tuning for the Parquet V2 footer read path, plus one real regression the benchmark itself introduced. map_batches: 26cdef2 added ``num_cpus=0.99`` to ``read_parquet`` in map_benchmark.py. The fusion rule canonicalizes an unspecified ``num_cpus`` to 1, so 0.99 makes the read incompatible with the downstream map_batches ops and they stop fusing. Unfused, every read output crosses the object store: 1.13 TiB on sf1000 lineitem and 484.5s of block serialization against 0.6s fused, taking the test from 141s to 335s vs master. Drop the arg and pin a 1 GiB bin budget -- the 64 MiB default is worst-case on this table (three 24.36 MiB row groups exceed it, so bins take two and sit 24% empty, giving 24,432 read tasks against master's 1,000). aggregate_groups: 32 MiB on both shuffle strategies. First setting to move fixed_size/84-groups/sort_shuffle, stuck at 220-259s across four builds under every other budget; 32 MiB brings it to 192s. This is the opposite direction from map_groups, which wants 1.25 GiB on the same dataset. tpch_q1: 192 MiB, matching q20 on the same table. Also corrects comments that described master's read path as V1. Master is DSv2 with the round-robin partitioner for every suite except map_batches, which is V1 there because DEFAULT_USE_DATASOURCE_V2 is False on master and ray-project#64821 (branch-only) flips it. Tests: pytest python/ray/data/tests/datasource/test_parquet.py::test_parquet_read_spread python/ray/data/tests/test_predicate_pushdown.py -- 51 passed. AI assistance was used for this change. Signed-off-by: Goutam <[email protected]>
aggregate_groups: move the bin budget from the block to a per-variant setting via matrix.adjustments, with bin_packing_bytes as a fourth matrix variable. Only fixed_size/sort_shuffle/84-groups needed retuning -- it ran 211s at 32 MiB in release build #102329 against master's ~145s, and 137s at 256 MiB. The other seven variants keep 32 MiB, where they were measured healthy in that same build (+10.2% to -30.7%), rather than move onto an unmeasured value. The cost being tuned is per-block sort-shuffle overhead, not bytes: at 32 MiB the scan emitted 4x the ListFiles outputs and ~1.5x the blocks into the shuffle (Sort Sample 3050 vs master's 2000) for an identical 20.8GB object-store peak and identical row count. cross_az_map_batches_autoscaling_iptable_failure_injection: pin 1 GiB. These tests moved from the V1 to the V2 read path when the use_datasource_v2=False pin came out of map_benchmark.py; on V2 at the 64 MiB default the object-store peak doubled (310GB -> 616GB) and runtime went 304s -> 725s. The larger budget is a mitigation and is not yet measured. Also request num_cpus=0 for FooterReaderActor. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
Conflict in release/release_data_tests.yaml: master added a third shuffle_strategy (hash_shuffle_v2) to the aggregate_groups matrix, while this branch had converted that block from matrix.setup to matrix.adjustments so each variant can carry its own bin budget. Kept both -- the four new hash_shuffle_v2 variants are enumerated as adjustments alongside the existing eight. The new variants get the 64 MiB branch default rather than the 32 MiB the other variants carry: 32 MiB is a deliberate pin for variants that were measured at it in release build #102329, and hash_shuffle_v2 has never run on this branch. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
…get to 128MiB The Parquet footer indexer's default 32-actor pool times out (and trips Ray's "too many worker processes" warning, polluting doctest output) when many test targets run in parallel under CI. Rather than sprinkling per-module env writes, set the pool size to 1 in one place per test surface: - New python/ray/data/test.bzl wraps py_test/py_test_module_list/doctest to inject RAY_DATA_PARQUET_FOOTER_NUM_ACTORS=1 into every Data test target's env (caller-supplied env still wins). - python/ray/data/tests/conftest.py and doctest_pytest_plugin.py setdefault the same var so non-bazel pytest runs match. - python/ray/train/v2 gets shared _TRAIN_V2_TEST_ENV dicts plus a conftest setdefault, replacing the repeated per-target env literals. - Drops the now-redundant os.environ write from test_predicate_pushdown.py. Also raises the fallback bin-packing budget from 64MiB to 128MiB when target_max_block_size is unset, and fixes the write_lance docstring example to pass SaveMode.OVERWRITE so repeated doctest runs don't fail on an existing dataset. AI assistance was used for this change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
…ault Release build #102597 raised the footer indexer's fallback bin budget from 64 to 128 MiB. Comparing each test's delta-vs-its-own-master between #102329 and #102597, 24 of the 38 tests running on the fallback default got worse and 14 improved. This pins the 24 back to 64 MiB explicitly; the 14 keep following the raised default. The split is directional rather than arbitrary: among Parquet tests the regressions are read-dominated (read_parquet_autoscaling -20.9% -> +3.1%, read_large_parquet_autoscaling -8.1% -> +32.9%, count_parquet_autoscaling -15.4% -> -1.7%) while the improvements are shuffle/sort-heavy (random_shuffle_chaos +67.8% -> +14.9%, sort_fixed_size +22.2% -> +2.1%). Same tension the aggregate_groups and map_groups comments already describe. read_from_uris, iceberg_benchmark and iter_batches are split out of their matrices so only the affected variant is pinned and the others keep following the default. training_ingest_benchmark is pinned at block level with s3_read_images_gpu exempted. Caveats recorded in the per-test comments: - Eight of the 24 pins are inert. read_images_*, read_tfrecords and the s3_url_image_* / s3_read_images_cpu ingest variants do not read Parquet. mix reads 513 single-row-group files of ~88 MB, which pack one file per bin at both 64 and 128 MiB. These tests did move, but not because of this knob. - mix and distributed_training.chaos define their own runtime_env, which replaces the DEFAULTS list, so they already ran without the RAYTEST_* guards (and chaos without FOOTER_NUM_ACTORS=20). Left as-is rather than changed under cover of this commit. - The two builds differ by 46 merged master commits, so these deltas are not a controlled A/B of the budget alone. Verified by expanding the yaml through the same DEFAULTS/variations/matrix logic ray_release.config uses, before and after: test name set identical at 199, all 24 targets at 64 MiB, no non-target budget changed, no test lost or had an env var altered. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
…moke test Extends the pattern from 74e599b to two more test surfaces. The Parquet footer indexer's production default of 32 actors times out and trips Ray's "too many worker processes" warning when many test targets run in parallel under CI. - python/ray/air/BUILD.bazel gets three shared env dicts (_AIR_TEST_ENV, _AIR_TEST_ENV_TRAIN_V1, _AIR_TEST_ENV_TF) replacing the repeated per-target literals, so all 20 py_test targets under python/ray/air/tests get RAY_DATA_PARQUET_FOOTER_NUM_ACTORS=1. The three dicts preserve the existing RAY_TRAIN_V2_ENABLED 1-vs-0 split, which six of those targets depend on. - python/ray/air/tests/conftest.py setdefaults the same var so non-bazel pytest runs match. This also covers tests/execution, which has no conftest of its own. - //release:xgboost_train_batch_inference_benchmark_smoke_test gets the var inline; a shared dict would be indirection for a single target. Verified by resolving each air target's env before and after: 20/20 now set the var and no target had any other env value change. Not included: the py_doctest[air] target, whose glob excludes tests/**, and the four sibling smoke tests in release/BUILD.bazel that carry the same RAY_TRAIN_V2_ENABLED=1 env (air_benchmark_gpu_batch_inference_parquet in particular reads Parquet and will likely want the same treatment). AI assistance was used for this change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
…ld for map_batches release test Signed-off-by: Goutam <[email protected]>
ListFiles.predicate / projected_columns / limit were mirrored onto the op by hand from three separate rules (predicate, projection and limit pushdown). Nothing enforced the invariant those copies rest on -- that ListFiles never prunes by more than the downstream ReadFiles actually applies -- so a future rule that rewrote or dropped the scanner's predicate without re-syncing would leave ListFiles pruning row groups the reader would have kept, dropping rows with no error. Replace the mirroring with DeriveListFilesPushdown, which recomputes every ListFiles' state from its consuming ReadFiles scanner. It runs in LogicalOptimizer._post_optimize, after the rule loop reaches a fixed point, and derives unconditionally in both directions: a ListFiles whose consumer is not a ReadFiles is reset to no constraints. The worst a future rule can now cause is listing more than it needs to. Also replace the getattr(scanner, "predicate", None) access with abstract pushed_predicate() / pushed_limit() accessors on the scanner mixins, mirroring the existing pruned_column_names(), so a field rename is a type error rather than a silent no-op. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
…e_env deep_update merges dicts but overwrites lists, so a test that declares its own cluster.byod.runtime_env replaces the DEFAULTS list rather than extending it. Pinning a bin budget therefore silently dropped RAY_DATA_DEBUG_RESOURCE_MANAGER and all three RAYTEST_FAIL_ON_* flags: 27 tests had stopped failing on worker OOM, dead nodes and spilling. It also split failure semantics across halves of the same test -- read_large_parquet_autoscaling kept the flags while its fixed_size twin lost them. Re-list the four inherited entries in every affected block, leaving the two that override them deliberately (heterogeneous_memory_batch_inference_ multitenancy and cross_az_...) alone. Verified by expanding both configs: the resolved failure flags and cluster_compute of all 199 tests now match master exactly. Also drop the redundant cluster_compute on iter_batches_pyarrow. It pinned the same value DEFAULTS supplies, so the baseline was never broken, but keeping it would stop the variant tracking its former matrix siblings if DEFAULTS moves. Document the list-replacement trap at the DEFAULTS block. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
Nothing exercised the two push-downs together, and nothing used nulls. The combination is where the fully_matched classification matters: listing stops early once the num_rows of fully-matched row groups reaches the pushed limit, so counting a non-surviving row would make Limit return fewer rows than asked for, with no error. Parquet min/max statistics are computed over non-null values only, which makes a group whose non-null values all satisfy the filter look fully matched by bounds alone. Arrow's row-group pruning turns out to be null-aware -- it declines to prune such a group by ~filter, so the classification is already correct -- but that was untested. Add one parameterized end-to-end test. The fixture is deliberately lopsided at 10 survivors per 100 rows: the early stop is evaluated per file, so a fixture with a small shortfall passes even when the classification is wrong, the last file's overshoot covering the deficit. With the misclassification injected, the 100- and 200-row limits fail. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
|
/gemini review |
|
/gemini summary |
There was a problem hiding this comment.
Code Review
This pull request implements a footer-based Parquet chunking and bin-packing path for Ray Data (DataSourceV2), allowing for row-group-aligned reads with predicate, limit, and projection push-downs. It introduces FooterFileIndexer, FooterReader actors, and an OnlineBinPacker to optimize read tasks, alongside a new logical optimizer rule DeriveListFilesPushdown to keep listing constraints in sync with the scanner. Feedback on the changes highlights a few critical issues: a missing import of WholeFileChunker in file_indexer.py that will cause a runtime NameError, potential zero-division and value errors if configuration values like RAY_DATA_PARQUET_FOOTER_NUM_ACTORS or max_shared_open_bins are set to non-positive values, and a potential ordering violation in footer_reader.py when preserve_order is enabled.
| return NonSamplingFileIndexer( | ||
| ignore_missing_paths=self._ignore_missing_paths, | ||
| num_workers=self._num_workers, | ||
| max_paths_per_output=self._max_paths_per_output, | ||
| file_chunker=WholeFileChunker(), | ||
| ) |
There was a problem hiding this comment.
The WholeFileChunker class is used here but it is not imported in this file. This will raise a NameError at runtime when as_whole_file_indexer is called. Import WholeFileChunker inline to avoid circular dependencies.
| return NonSamplingFileIndexer( | |
| ignore_missing_paths=self._ignore_missing_paths, | |
| num_workers=self._num_workers, | |
| max_paths_per_output=self._max_paths_per_output, | |
| file_chunker=WholeFileChunker(), | |
| ) | |
| from ray.data._internal.datasource_v2.chunkers.file_chunker import WholeFileChunker | |
| return NonSamplingFileIndexer( | |
| ignore_missing_paths=self._ignore_missing_paths, | |
| num_workers=self._num_workers, | |
| max_paths_per_output=self._max_paths_per_output, | |
| file_chunker=WholeFileChunker(), | |
| ) |
| self._num_actors = env_integer( | ||
| "RAY_DATA_PARQUET_FOOTER_NUM_ACTORS", _DEFAULT_NUM_ACTORS | ||
| ) |
There was a problem hiding this comment.
If RAY_DATA_PARQUET_FOOTER_NUM_ACTORS is configured to 0 or a negative value, it will cause a ZeroDivisionError during modulo operations in _read_and_pack. Enforce a minimum of 1 actor to prevent this.
| self._num_actors = env_integer( | |
| "RAY_DATA_PARQUET_FOOTER_NUM_ACTORS", _DEFAULT_NUM_ACTORS | |
| ) | |
| self._num_actors = max(1, env_integer( | |
| "RAY_DATA_PARQUET_FOOTER_NUM_ACTORS", _DEFAULT_NUM_ACTORS | |
| )) |
| for finished in as_completed(futures): | ||
| chunk = finished.result() |
There was a problem hiding this comment.
Using as_completed(futures) yields results out-of-order based on network latency, which violates the preserve_order=True setting if requested by the user. Consider passing preserve_order to read_footers and iterating over futures directly when it is True to maintain deterministic ordering.
| for finished in as_completed(futures): | |
| chunk = finished.result() | |
| for finished in (futures if preserve_order else as_completed(futures)): | |
| chunk = finished.result() |
| ): | ||
| # ``max_bin_bytes`` doubles as the "colour turns heavy" isolate threshold. | ||
| self._cap = max_bin_bytes | ||
| self._max_shared_open_bins = max_shared_open_bins |
There was a problem hiding this comment.
If max_shared_open_bins is configured to 0 or a negative value, max() will raise a ValueError when trying to evict the fullest bin. Enforce a minimum of 1 open bin to prevent this.
| self._max_shared_open_bins = max_shared_open_bins | |
| self._max_shared_open_bins = max(1, max_shared_open_bins) |
Summary of ChangesThis pull request introduces a more efficient Parquet V2 reading path by shifting from blind size-based chunking to footer-aware indexing. By reading file footers during the listing phase, the system can now perform predicate pushdown, row-group skipping, and limit pushdown, significantly reducing unnecessary I/O. The changes include a new FooterFileIndexer, an OnlineBinPacker for balanced read units, and updated logical optimizer rules to ensure pushdown constraints are correctly propagated. Highlights
New Features🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Activity
|
…ion test pyrefly resolved `replace(read_files.input_dependencies[0], predicate=...)` against `LogicalOperator` and `read_files.scanner.push_filters(...)` against the base `Scanner`, neither of which carries those fields or methods. Route both through narrowing helpers, and take `Plan` in `_list_files_of` since that is what `Optimizer.optimize` returns. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
…ests A matrix cannot vary ``byod.runtime_env`` per setup value, so the variants that need their own tuning are spelled out. Rendered test names are unchanged. - q1 autoscaling: keep the 192 MiB bin budget of the fixed_size variants and scale up at 60% utilization instead of the 0.75 default. Both autoscaling variants land at 364-385s regardless of shuffle strategy while master runs hash_shuffle in 249s, which points at scale-up latency, not shuffle cost. - q17 autoscaling: 64 MiB. Smaller bins mean more read tasks, which give the autoscaler demand to act on earlier; the fixed_size variant is ~5x faster on the same query at the default budget. - q22 fixed_size/hash_shuffle: 16 MiB. At the 128 MiB default this sf100 scan collapses into a handful of bins and starves a 23-second query of read parallelism (+76.7% vs master in #102732, +72.0% in #102650). Each spelled-out entry re-lists the four inherited RAYTEST_FAIL_ON_* / RAY_DATA_DEBUG_RESOURCE_MANAGER vars, since a test-level runtime_env replaces the DEFAULTS list rather than extending it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
The target ran two full ``TorchTrainer.fit()`` runs (2 workers, 3 epochs) plus a ``ray.init`` per parameterization inside small's 60s budget, and timed out at 60.3s on both attempts in CI. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
…and replication driver Two changes, both aimed at the TODO 1ab phase-1 Linux replication run. 1. `_num_fragment_read_threads` on the arrow-rs path returns `num_fragments` instead of `min(4, num_fragments)`. The cap was guarding a scenario the ray-project#64985 planner does not produce: bins are packed to ~128 MiB of *uncompressed, projection-scoped* bytes, so a bin spans a handful of files at most, and the base path's one-worker-per-fragment pool is already bounded by that geometry. Keeping a narrower cap on our side turned every multi-fragment A/B cell into a pool-width comparison instead of a decode comparison. `RAY_DATA_READ_FILES_NUM_THREADS` still re-caps explicitly if the bin sweep shows arrow-rs USS growing with bin size. 2. `run_replication.sh` — one command on a fresh Linux box for the replication matrix (setup -> pytest gate -> replication fixtures -> matrix), same skeleton as `run_grand_experiment.sh`. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
ray-project#65168) ## Why `LimitPushdownRule._push_limit_down` walks down through num-rows-preserving operators and applies a per-block limit to the deepest one it reaches. When there are none to walk through — i.e. the `Limit` sits *directly* on its input — it returned the plan unchanged. So `ds.limit(n)` immediately after a V2 `read_parquet` never reached the scanner, and the read stayed unbounded: the reader scanned every row group and `Limit` discarded the surplus downstream. Inserting any no-op map in between was enough to make the pushdown fire, which is a surprising cliff. ## Flow `Limit -> ReadFiles` now becomes `Limit -> ReadFiles(scanner.limit=n)`. The `Limit` stays on top for exact enforcement, since a per-block limit is per-block, not global. ## What changed - `logical/rules/limit_pushdown.py`: in the `not num_rows_preserving_ops` branch, apply the per-block limit when the input is a `ReadFiles`, and return `Limit(n, [new_read_files])`. Every other operator type still falls through untouched, and the rule still builds new operators rather than mutating. - `tests/test_execution_optimizer_limit_pushdown.py`: adds `ReadFiles` coverage. That file calls `_push_limit_down` directly but had no `ReadFiles` cases at all, so this branch would otherwise have shipped untested. Covers both the scanner-supports-limit case and the scanner-doesn't case, and asserts the original operator is not mutated. ## Testing ``` $ python -m pytest -q python/ray/data/tests/test_execution_optimizer_limit_pushdown.py 28 passed in 12.14s ``` ## Stack Step 2 of an 11-step split of ray-project#64985. This step has **no merge-order dependency** — it stands alone against master and is independently useful. Signed-off-by: Goutam <[email protected]> Signed-off-by: 400Ping <[email protected]>
## Why `FileIndexer.list_files` mixed three concerns: directory traversal, filtering (zero-size skip + pruners), and chunking files into manifest rows. Consumers that only need paths and sizes had to pay for chunking, and there was no way to observe the pre-chunk file stream at all. Splitting them out is a prerequisite for a metadata-aware indexer (it needs paths + sizes, then does its own chunking), and it removes a real cost today: driver-side schema inference chunks files just to throw the chunks away. ## Flow ```mermaid flowchart LR A[paths] --> B[_get_file_info_iterator<br/>threaded or sequential] B --> C[list_file_infos<br/>skip zero-size, apply pruners] C --> D[list_files<br/>chunk into FileManifest] C --> E[sample_files<br/>schema inference, no chunking] ``` ## What changed - `listing/file_indexer.py`: new abstract `FileIndexer.list_file_infos()`. `NonSamplingFileIndexer.list_file_infos()` now owns the zero-size skip and pruner filtering; `_get_file_info_iterator()` is extracted so both paths share traversal; `list_files()` becomes a thin chunking layer on top; `_process_file_infos_to_manifests()` drops its now-redundant `pruners` argument. - `listing/listing_utils.py`: `sample_files()` consumes `list_file_infos` and builds the manifest directly. - `tests/unit/datasource_v2/test_file_indexer.py`: new `TestListFileInfos` covering the path/size stream, the zero-size skip, pruner application, that it does **not** chunk, and that it stays lazy. There was no direct coverage of this stream before. No behavior change. `NonSamplingFileIndexer` is the only in-tree `FileIndexer`, so the new abstract method breaks nothing. ## Testing ``` $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/test_file_indexer.py 49 passed in 0.16s $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/ python/ray/data/_internal/datasource_v2/tests/ 104 passed in 0.78s $ python -m pytest -q python/ray/data/tests/datasource/test_read_parquet_v2.py 13 passed ``` ## Stack Step 1 of an 11-step split of ray-project#64985, which was 43 files / +3234 −719 and not reviewable as one unit. This step has **no merge-order dependency** — it stands alone against master. --- Not a duplicate of any open PR (checked `gh pr list --repo ray-project/ray --state open --search "..."`; 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]>
…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]>
|
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. |
…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 Groundwork for the footer-based Parquet indexer in #64985, landed separately so that PR stays reviewable. The footer indexer runs a pool of footer-reading actors, sized for real datasets on a real cluster (32). Under Bazel test parallelism that many actors per target times out and trips Ray's "too many worker processes" warning — which also pollutes doctest expected output, since Sphinx `testoutput` blocks match stderr. Tests read tiny fixtures and need exactly one actor. **This is currently a no-op**: nothing reads `RAY_DATA_PARQUET_FOOTER_NUM_ACTORS` until the indexer lands. It is deliberately separated so the feature PR does not also have to carry ~200 lines of BUILD-file churn across three CODEOWNERS teams. ## Flow ```mermaid flowchart LR A["python/ray/data/test.bzl<br/>py_test / py_test_module_list / doctest"] -->|merge env, caller wins| B[bazel targets] C["conftest.py setdefault"] -->|same value| D[plain pytest runs] ``` ## What changed - `python/ray/data/test.bzl` (new): thin wrappers over `py_test`, `py_test_module_list`, and `doctest` that merge `RAY_DATA_PARQUET_FOOTER_NUM_ACTORS=1` into each target's `env`. A caller-supplied value wins, so any target that needs a larger pool can still set one. - `python/ray/data/BUILD.bazel`: point the loads at `:test.bzl`. - `os.environ.setdefault(...)` in `data/tests/conftest.py`, `data/tests/doctest_pytest_plugin.py`, `air/tests/conftest.py`, `train/v2/tests/conftest.py`, so plain `pytest` runs match Bazel. `setdefault` means `monkeypatch.setenv` still wins. - `air/BUILD.bazel`, `train/v2/BUILD.bazel`: hoist the repeated `env` dicts into shared constants and add the var. No existing `RAY_TRAIN_V2_ENABLED` / `TF_USE_LEGACY_KERAS` value changes. - `release/BUILD.bazel`: same var on the xgboost/lightgbm smoke test, which runs in premerge. - `python/ray/data/BUILD.bazel`: `test_predicate_pushdown` `small` → `medium` (it exercises the V2 read path). - `python/ray/data/dataset.py`: fix the `write_lance` doctest, which wrote to a shared `/tmp/data/` with no mode and so failed on re-run. Bundled here rather than sent as a one-line PR. ## Testing ``` $ bazel query 'kind(py_test, //python/ray/data:test_predicate_pushdown)' --output=build | grep -E 'env|size' size = "medium", env = {"RAY_DATA_PARQUET_FOOTER_NUM_ACTORS": "1"}, $ bazel query '//python/ray/air:test_air_usage' --output=build | grep env env = {"RAY_DATA_PARQUET_FOOTER_NUM_ACTORS": "1", "RAY_TRAIN_V2_ENABLED": "0"}, $ bazel query 'kind(py_test, //python/ray/train/v2:all)' # loads clean $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/test_file_indexer.py 40 passed ``` The load swap is the real risk here, not the env var — the wrappers are keyword-only while `bazel/python.bzl`'s `doctest(files, ...)` and `py_test_module_list(files, size, deps, ...)` are positional. All call sites in `python/ray/data/BUILD.bazel` already use keyword arguments, and the `bazel query` above confirms the package loads and the env reaches the target. ## Stack Step 9 of an 11-step split of #64985. This step has **no merge-order dependency** — it touches a disjoint set of files and stands alone against master. --- Not a duplicate of any open PR (checked `gh pr list --repo ray-project/ray --state open --search "..."`; only #64985, which this replaces). AI assistance was used; every line reviewed by me and tests run locally. Signed-off-by: Goutam <[email protected]>
Tunes the Data release tests for the footer path, so this PR can be validated by an actual release run rather than by unit tests alone. Carried over from the tuning measured on the original branch (ray-project#64985), with the stale parts dropped: 7 of the 33 originally-pinned entries no longer exist (the autoscaling variants removed in ray-project#65506, plus tpch_q20 / tpch_q22), and the `{{scaling}}` de-templating is unnecessary because ray-project#65506 already left those entries spelled out. 26 entries get a pin. Most hold the previous 64 MiB behaviour on tests that regressed when the fallback default moved to 128 MiB; a few go the other way (1 GiB / 1.25 GiB) for datasets whose row groups are large enough that the default produces one read task per row group. Three entries are split out of their matrices because a matrix cannot vary `byod.runtime_env` per value and their variants want different budgets: `wide_schema_pipeline_{{data_type}}` into four, and one variant each out of `iceberg_benchmark_{{mode}}` and `iter_batches_{{format}}`. Rendered test names are unchanged -- 121 before and after -- so release baselines still line up. Any entry that gains 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. Also drops `map_benchmark.py`'s `use_datasource_v2 = False` pin, which was there because V2 was spilling; the footer path is the read path now. These budgets were measured against the pre-decoupling design. Packing moved between stages in ray-project#65596 but the packer and its inputs did not, so the bins should be unchanged -- treat these as a starting point to confirm or correct with a release run, not as settled values. 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]>
|
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! |
ray-project#65168) ## Why `LimitPushdownRule._push_limit_down` walks down through num-rows-preserving operators and applies a per-block limit to the deepest one it reaches. When there are none to walk through — i.e. the `Limit` sits *directly* on its input — it returned the plan unchanged. So `ds.limit(n)` immediately after a V2 `read_parquet` never reached the scanner, and the read stayed unbounded: the reader scanned every row group and `Limit` discarded the surplus downstream. Inserting any no-op map in between was enough to make the pushdown fire, which is a surprising cliff. ## Flow `Limit -> ReadFiles` now becomes `Limit -> ReadFiles(scanner.limit=n)`. The `Limit` stays on top for exact enforcement, since a per-block limit is per-block, not global. ## What changed - `logical/rules/limit_pushdown.py`: in the `not num_rows_preserving_ops` branch, apply the per-block limit when the input is a `ReadFiles`, and return `Limit(n, [new_read_files])`. Every other operator type still falls through untouched, and the rule still builds new operators rather than mutating. - `tests/test_execution_optimizer_limit_pushdown.py`: adds `ReadFiles` coverage. That file calls `_push_limit_down` directly but had no `ReadFiles` cases at all, so this branch would otherwise have shipped untested. Covers both the scanner-supports-limit case and the scanner-doesn't case, and asserts the original operator is not mutated. ## Testing ``` $ python -m pytest -q python/ray/data/tests/test_execution_optimizer_limit_pushdown.py 28 passed in 12.14s ``` ## Stack Step 2 of an 11-step split of ray-project#64985. This step has **no merge-order dependency** — it stands alone against master and is independently useful. Signed-off-by: Goutam <[email protected]>
## Why `FileIndexer.list_files` mixed three concerns: directory traversal, filtering (zero-size skip + pruners), and chunking files into manifest rows. Consumers that only need paths and sizes had to pay for chunking, and there was no way to observe the pre-chunk file stream at all. Splitting them out is a prerequisite for a metadata-aware indexer (it needs paths + sizes, then does its own chunking), and it removes a real cost today: driver-side schema inference chunks files just to throw the chunks away. ## Flow ```mermaid flowchart LR A[paths] --> B[_get_file_info_iterator<br/>threaded or sequential] B --> C[list_file_infos<br/>skip zero-size, apply pruners] C --> D[list_files<br/>chunk into FileManifest] C --> E[sample_files<br/>schema inference, no chunking] ``` ## What changed - `listing/file_indexer.py`: new abstract `FileIndexer.list_file_infos()`. `NonSamplingFileIndexer.list_file_infos()` now owns the zero-size skip and pruner filtering; `_get_file_info_iterator()` is extracted so both paths share traversal; `list_files()` becomes a thin chunking layer on top; `_process_file_infos_to_manifests()` drops its now-redundant `pruners` argument. - `listing/listing_utils.py`: `sample_files()` consumes `list_file_infos` and builds the manifest directly. - `tests/unit/datasource_v2/test_file_indexer.py`: new `TestListFileInfos` covering the path/size stream, the zero-size skip, pruner application, that it does **not** chunk, and that it stays lazy. There was no direct coverage of this stream before. No behavior change. `NonSamplingFileIndexer` is the only in-tree `FileIndexer`, so the new abstract method breaks nothing. ## Testing ``` $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/test_file_indexer.py 49 passed in 0.16s $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/ python/ray/data/_internal/datasource_v2/tests/ 104 passed in 0.78s $ python -m pytest -q python/ray/data/tests/datasource/test_read_parquet_v2.py 13 passed ``` ## Stack Step 1 of an 11-step split of ray-project#64985, which was 43 files / +3234 −719 and not reviewable as one unit. This step has **no merge-order dependency** — it stands alone against master. --- Not a duplicate of any open PR (checked `gh pr list --repo ray-project/ray --state open --search "..."`; 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]>
…-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]>
…oject#65169) ## Why Groundwork for the footer-based Parquet indexer in ray-project#64985, landed separately so that PR stays reviewable. The footer indexer runs a pool of footer-reading actors, sized for real datasets on a real cluster (32). Under Bazel test parallelism that many actors per target times out and trips Ray's "too many worker processes" warning — which also pollutes doctest expected output, since Sphinx `testoutput` blocks match stderr. Tests read tiny fixtures and need exactly one actor. **This is currently a no-op**: nothing reads `RAY_DATA_PARQUET_FOOTER_NUM_ACTORS` until the indexer lands. It is deliberately separated so the feature PR does not also have to carry ~200 lines of BUILD-file churn across three CODEOWNERS teams. ## Flow ```mermaid flowchart LR A["python/ray/data/test.bzl<br/>py_test / py_test_module_list / doctest"] -->|merge env, caller wins| B[bazel targets] C["conftest.py setdefault"] -->|same value| D[plain pytest runs] ``` ## What changed - `python/ray/data/test.bzl` (new): thin wrappers over `py_test`, `py_test_module_list`, and `doctest` that merge `RAY_DATA_PARQUET_FOOTER_NUM_ACTORS=1` into each target's `env`. A caller-supplied value wins, so any target that needs a larger pool can still set one. - `python/ray/data/BUILD.bazel`: point the loads at `:test.bzl`. - `os.environ.setdefault(...)` in `data/tests/conftest.py`, `data/tests/doctest_pytest_plugin.py`, `air/tests/conftest.py`, `train/v2/tests/conftest.py`, so plain `pytest` runs match Bazel. `setdefault` means `monkeypatch.setenv` still wins. - `air/BUILD.bazel`, `train/v2/BUILD.bazel`: hoist the repeated `env` dicts into shared constants and add the var. No existing `RAY_TRAIN_V2_ENABLED` / `TF_USE_LEGACY_KERAS` value changes. - `release/BUILD.bazel`: same var on the xgboost/lightgbm smoke test, which runs in premerge. - `python/ray/data/BUILD.bazel`: `test_predicate_pushdown` `small` → `medium` (it exercises the V2 read path). - `python/ray/data/dataset.py`: fix the `write_lance` doctest, which wrote to a shared `/tmp/data/` with no mode and so failed on re-run. Bundled here rather than sent as a one-line PR. ## Testing ``` $ bazel query 'kind(py_test, //python/ray/data:test_predicate_pushdown)' --output=build | grep -E 'env|size' size = "medium", env = {"RAY_DATA_PARQUET_FOOTER_NUM_ACTORS": "1"}, $ bazel query '//python/ray/air:test_air_usage' --output=build | grep env env = {"RAY_DATA_PARQUET_FOOTER_NUM_ACTORS": "1", "RAY_TRAIN_V2_ENABLED": "0"}, $ bazel query 'kind(py_test, //python/ray/train/v2:all)' # loads clean $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/test_file_indexer.py 40 passed ``` The load swap is the real risk here, not the env var — the wrappers are keyword-only while `bazel/python.bzl`'s `doctest(files, ...)` and `py_test_module_list(files, size, deps, ...)` are positional. All call sites in `python/ray/data/BUILD.bazel` already use keyword arguments, and the `bazel query` above confirms the package loads and the env reaches the target. ## Stack Step 9 of an 11-step split of ray-project#64985. This step has **no merge-order dependency** — it touches a disjoint set of files and stands alone against master. --- Not a duplicate of any open PR (checked `gh pr list --repo ray-project/ray --state open --search "..."`; 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]>
…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
Parquet V2 reads currently chunk files blindly:
ParquetFileChunkersplits each file by size (ceil(file_size / 1 GiB)) without reading the footer, andRoundRobinPartitionerbin-packs those guesses with a fixed encoding-ratio estimate. Bin sizes are inaccurate (compression ratio is unknown until the footer is read), and there is no predicate/limit pushdown into listing and no row-group skipping.What
Replace that path with a
FooterFileIndexerthat reads each file's Parquet footer on a pool ofFooterReaderactors (SPREADacross the cluster) and packs row groups into read units with an online, locality-preserving bin packer (OnlineBinPacker). This makes read units row-group-accurate instead of size-estimated.ReadFilesscanner onto the upstreamListFiles(sync_list_files_pushdown, gated on the datasource supporting each pushdown). The footer actors then prune row groups by statistics, size only projected columns, and stop listing early under a limit.FileIndexerabstraction —ListFilesdrives it via the ordinarylist_filestransform;yields_read_units=Truemakes it list in a single task and skip the partitioner.ParquetFileChunker/ParquetFileChunkMetadataand their size-based row-group-range helpers; the reader now reads exactly the row groups a bin names.Footer reading is the default for Parquet V2 reads.