Repository navigation
[Data] Add opt-in full Parquet schema inference - #66522
richardliaw merged 7 commits into
Conversation
|
To enable full Parquet schema inference: import ray
ray.data.DataContext.get_current().use_datasource_v2 = True
ds = ray.data.read_parquet("path/to/parquet", merge_schema=True)The public sample_all_files_for_schema=merge_schema,That flag changes the scope of file discovery from the default 16 files to all eligible files: max_files=None if sample_all_files_for_schema else 16,
schema = (
unify_schemas_with_validation(per_file_schemas)
or per_file_schemas[0]
)So For the opt-in path, the discovered path-and-size records are retained on the Dataset plan. At execution, Spark’s Parquet reader provides the opt-in precedent because merging schemas across files is expensive. Spark’s schema merge utility sends path-and-length information to distributed schema-reading tasks. This PR uses driver-side footer reads and Ray’s existing unifier. The retained file information is O(file count) and lives with the Dataset plan. Files appended after discovery are excluded, while an append during traversal is not covered by an atomic snapshot. |
|
Following up on the implementation walkthrough above, a possible longer-term question is how to scale planning-time footer schema reads. The earlier comment covers file discovery and reuse; today, with ThreadPoolExecutor(max_workers=min(len(sample_paths), 16)) as executor:
for start in range(0, len(sample_paths), _SCHEMA_READ_BATCH_SIZE):
batch = sample_paths[start : start + _SCHEMA_READ_BATCH_SIZE]
per_file_schemas.extend(executor.map(_read_schema, batch))Spark’s .parallelize(partialFileStatusInfo, numParallelism)
.mapPartitions { iterator =>If measurements on representative remote datasets show excessive footer-read latency, a Ray follow-up could send bounded batches from the same candidate file set discovered for full inference to metadata tasks. I would first distribute footer reads and pass their results back in discovery order to the current one-shot unifier. If driver schema memory also becomes a problem, task-local merging could be considered after differential tests establish identical field order, metadata, type promotion, nested-field, and extension-type results. What file counts and storage systems would make this follow-up valuable? Feedback on the workload and the staged approach is welcome. |
There was a problem hiding this comment.
Code Review
This pull request introduces a merge_schema option for read_parquet in the V2 datasource, enabling schema inference from all files rather than a limited sample. It adds list_files_from_file_infos to indexers to support pre-listing files during schema inference and includes robust error handling for schema merging. A review comment suggests removing the batching logic in schema reading to improve thread utilization by submitting all tasks simultaneously.
| per_file_schemas: List[pa.Schema] = [] | ||
| with ThreadPoolExecutor(max_workers=min(len(sample_paths), 16)) as executor: | ||
| per_file_schemas = list(executor.map(_read_schema, sample_paths)) | ||
| schema = ( | ||
| unify_schemas_with_validation(per_file_schemas) or per_file_schemas[0] | ||
| ) | ||
| for start in range(0, len(sample_paths), _SCHEMA_READ_BATCH_SIZE): | ||
| batch = sample_paths[start : start + _SCHEMA_READ_BATCH_SIZE] | ||
| per_file_schemas.extend(executor.map(_read_schema, batch)) |
There was a problem hiding this comment.
Batching the schema reads with executor.map inside a loop introduces a synchronization barrier at the end of each batch (of size 256). Because per_file_schemas.extend(...) blocks until the entire batch is completed, any slow file read (due to network/S3 tail latency) at the end of a batch will cause the other worker threads to sit idle instead of starting work on the next batch.\n\nSince the task queue memory overhead in ThreadPoolExecutor is negligible even for tens of thousands of files, it is much more efficient to submit all tasks at once to keep all worker threads fully utilized.
with ThreadPoolExecutor(max_workers=min(len(sample_paths), 16)) as executor:\n per_file_schemas = list(executor.map(_read_schema, sample_paths))There was a problem hiding this comment.
In Python 3.13, submitting all paths through Executor.map would eagerly create a Future for each file, while this thread pool would still execute at most 16 _read_schema calls at a time. I’d keep submissions bounded rather than assume the additional queued state is negligible. If a representative workload shows that batch boundaries materially affect latency, a bounded rolling window could keep the pool busy without queueing every file. For larger remote datasets, I’ve outlined a Spark-inspired follow-up for distributed footer reads; task-local schema merging would be considered only if driver memory warrants it and equivalence with Ray’s current unifier is verified.
|
I ran a local Docker benchmark against PR commit For the planning benchmark, I used a Spark 3.5.8 Parquet file as a footer seed, then replicated its row-group metadata into metadata-only files with 24 columns. The 8- and 32-row-group counts are synthetic; these files have no readable data pages and were not scanned. I timed
I also tested file length separately. I placed the same footer at the end of each of 10,000 sparse files with a logical length of 1 GiB each. The unwritten gaps contained no data; the filesystem reported about 485 MiB of allocated blocks for the entire corpus. Full-mode planning took 2.480 s. This checks footer access at a large file offset, not the cost of reading 10 TB of data. In one separate run, unifying 10,000 already-loaded identical schemas took 0.069 s. For correctness, I used 17 genuine, scannable Parquet files with an extra column only in file 17. Default inference omitted the column; full inference included it, and an actual scan returned 16 nulls and one value in that column. The roughly 2–3 s local full-mode planning time seems acceptable for an opt-in batch-read feature. These results do not measure object-store latency, production footer distributions, or an exact target-revision native Ray build. |
|
Thanks for the detailed write-up. A couple of questions.
|
| @@ -309,11 +312,31 @@ def _read_schema(path: str): | |||
| with filesystem.open_input_file(path) as handle: | |||
| return pq.read_schema(handle) | |||
|
|
|||
| per_file_schemas: List[pa.Schema] = [] | |||
| with ThreadPoolExecutor(max_workers=min(len(sample_paths), 16)) as executor: | |||
There was a problem hiding this comment.
This reads every footer on the driver with 16 threads.
At execution the FooterReader actors read the same footers again, and fragment.metadata already has the schema.
For 100k files on S3 this loop alone is minutes.
Can we get the schema from the distributed footer read instead of doing it twice?
The current benchmarks are local disk only, so they don't show this cost.
There was a problem hiding this comment.
Thanks, this is a valid concern. Driver-side schema reads already exist for the default sample of up to 16 files. merge_schema=True expands them to all eligible candidates, so this PR makes that additional planning cost grow with the candidate count.
fragment.metadata does contain the schema, but the current FooterReader path runs during execution and returns row-group information. The Dataset schema must be resolved before read_parquet returns. Reusing those reads would require changing the planning/execution boundary and retaining or reusing the metadata needed later for execution.
As I outlined in my earlier follow-up comment, one possible staged direction is to distribute planning-time footer reads over the same candidate set and return per-file schemas in discovery order to the existing unifier. That could address the driver-side schema-read bottleneck, but by itself would not guarantee one footer read per file; metadata reuse would also need to be part of the design. Because that is a substantial change, I’d defer it to follow-up work unless large remote datasets are a required target for this PR.
The up-front cost may be reasonable for this opt-in mode: a complete planned schema makes columns found only in later files visible to downstream operations, so filters and projections that reference those columns may benefit from existing pushdown and column-pruning paths. This is workload-dependent, not a guaranteed speedup. The PR includes a small warm-call S3 measurement, but it does not establish performance at 100k files. If that scale is in scope, we should measure it and revisit the design before claiming support for it.
There was a problem hiding this comment.
Thanks, deferring is fine for an opt-in mode. Could you please open a GitHub issue for the follow-up (distributed planning-time footer reads, ideally reusing the metadata at execution) and link it from the docstring note?
There was a problem hiding this comment.
Thanks, deferring is fine for an opt-in mode. Could you please open a GitHub issue for the follow-up (distributed planning-time footer reads, ideally reusing the metadata at execution) and link it from the docstring note?
Thanks! I opened #67040 to track distributed planning-time footer reads, including reuse of footer metadata during execution, and linked it from the read_parquet docstring note.
| source_paths: List[str] | ||
| # Path and size blocks discovered during full schema inference. When set, | ||
| # execution processes this candidate set instead of walking ``paths`` again. | ||
| prelisted_file_infos: Optional[List["pa.Table"]] = None |
There was a problem hiding this comment.
Keeping the full file list here changes semantics: default mode re-lists on each execution, merge mode does not.
It also grows the logical plan and every serialize_lineage by O(files).
Can we either re-list at execution (listing is cheap next to footer reads) or call out the snapshot behavior very clearly in the docstring, including the lineage size?
There was a problem hiding this comment.
Thanks, this is a valid concern. I’d keep the discovered candidate set and take the documentation option: re-listing at execution could include files whose schemas were not included in inference. Execution may still narrow the set through pruning or checkpoint exclusions. The docstring already describes the candidate-set behavior and non-atomic directory listing; I’ll add that retaining path/size metadata grows with the file count and adds O(files) data to the serialized lineage.
| @@ -132,22 +164,22 @@ def sample_files( | |||
| paths: List[str], | |||
| filesystem: Optional["FileSystem"], | |||
| pruners: Optional[List[FilePruner]] = None, | |||
| max_files: int = 16, | |||
| max_files: Optional[int] = 16, | |||
There was a problem hiding this comment.
With max_files=None the driver walks the whole prefix serially. Can we add a warning above some file count, or a hard cap knob, so a huge prefix doesn't hang planning with no signal?
There was a problem hiding this comment.
Thanks for raising this. One clarification: file discovery is not serial under the default configuration; the existing indexer uses threaded work stealing with eight workers by default, configurable via RAY_DATA_LIST_FILES_THREADED_NUM_WORKERS. This PR does not change that traversal.
That said, full schema inference still discovers all eligible files and reads their footers before read_parquet returns, so a large remote prefix can make planning take a while. The API docstring warns about this up-front cost, but there is no progress signal while it runs. I’d add a one-time warning when the candidate count exceeds a documented threshold. I would avoid silently capping the file set, since that would make merge_schema=True incomplete; any hard limit should fail explicitly.
| # Copy each slice into its own buffers; retained chunks must not | ||
| # each keep the full listing's Arrow buffers alive. | ||
| prelisted_file_infos.append( | ||
| pa.Table.from_pydict(batch.to_pydict(), schema=file_infos.schema) |
There was a problem hiding this comment.
to_pydict() then from_pydict() copies every path through Python objects. For a million files that is slow. batch.take(...) or building the chunks straight from the Python lists in sample_files would avoid the round trip.
There was a problem hiding this comment.
Thanks! This currently round-trips each 1,000-row path/size block through Python objects. I’ll evaluate Arrow-native take-based chunking to remove that conversion. A plain slice is zero-copy: retained slices share the source buffers and can keep them alive, but they don’t each duplicate the full buffers. I’ll verify the buffer behavior, row order, schema, lineage serialization, and planning time/peak memory before finalizing.
Thanks for raising these. I’ve replied inline on the footer-read and file-list questions. In short, this PR expands the existing driver-side schema read from the default sample of up to 16 files to all eligible candidates. Eliminating the duplicate read would require a larger planning/execution change; as outlined in my earlier follow-up, I’d defer that unless representative remote workloads make it necessary. I’d keep the discovered candidate set so schema inference and execution use the same paths, and document its O(files) lineage cost. The up-front cost may be reasonable for an opt-in read that needs a complete schema, but the current measurements don’t establish performance at 100k files. |
a9984c8 to
7e272ee
Compare
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
7e272ee to
b7f51ba
Compare
Cover projection, predicates, limits, global file shuffle, and checkpoint recovery in merge-schema reads. Repair test imports and warning capture, and clarify planning cost and retained candidate paths. Signed-off-by: jiangxt2 <[email protected]>
|
LGTM. The listing warning, the Arrow-native chunking, and the expanded tests address the earlier comments, and the remaining cost of the double footer read is documented and scoped as a follow-up. Left a small non-blocking note inline. Let me add the go label which is needed for a full premerge run before merge. |
Signed-off-by: jiangxt2 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 16999dd. Configure here.
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
…conciliation and struct alignment (#66521) (#67995) ## Description Cherry-pick of #66521 (master commit 6fa1a28) onto `releases/2.60.1`. This is a prerequisite for the #67579 pick, #67999. The two sit in a 3-PR stack on `releases/2.60.1` under #68019 (the #67806 pick); merge it with `gh stack merge 68019`. #66521 fixes null-type handling when Ray Data reconciles Arrow schemas across blocks: - A nested field that is all-null in one block and a struct in another crashes `_backfill_missing_fields` with `TypeError: 'pyarrow.lib.DataType' object is not iterable`. - `_reconcile_field` reconciles `[null, list<null>, list<int64>]` to `null` instead of `list<int64>`. Without it, two of the tests #67579 adds fail on this branch. Both are the case where one block's tensor column is fixed-shape, another's is null, and a third's has a different shape. They fail with `ArrowTypeError: Casting from 'extension<ray.data.arrow_variable_shaped_tensor<...>>' to different extension type 'extension<ray.data.arrow_tensor_v2<...>>' not permitted`. ## Related issues Related to #66521. Needed by the #67579 pick. ## Additional information ### Cherry-pick details Applied cleanly with `git cherry-pick -x`. It has the same 2 files, +233/-30, and the same `git patch-id --stable` as the master commit. After the pick, `unit/test_transform_pyarrow.py` is identical to master at 6fa1a28. `transform_pyarrow.py` differs only by #66197's rename of `PreparedChunkedTensorTake` to `PreparedTensorTake`. #66197 is the only master commit that touched these files between the branch cut and #66521, and this change doesn't depend on it. To find what #67579 needed, I applied each master-only commit that touched `transform_pyarrow.py` or the tensor extensions on top of the #67579 pick: #66521, #65961, #66508, #66197, #66703 and #66522. #66521 alone makes the two failing tests pass, and none of the others changes the result. Not a duplicate: this branch doesn't contain #66521, and no PR on any branch references it. ### Testing | Command | Result | |---|---| | `pre-commit run --files <the 2 changed files>` | Passed | | `pytest python/ray/data/tests/unit/test_transform_pyarrow.py python/ray/data/tests/test_transform_pyarrow.py python/ray/data/tests/test_arrow_block.py` | 145 passed, 3 skipped | The #67579 pick's description has the results with both picks applied. I ran these against the Ray 2.60.0 release wheel, with this branch's `python/ray/data` and `python/ray/tests` copied over it. The wheel was built from `releases/2.60.0` at b7f4259, and its Python sources match `releases/2.60.1` except for `_version.py`. The environment was Python 3.12 with pandas 2.3.3 and pyarrow 23.0.1, the versions CI pins. Building Ray from source for `bazel test` wasn't practical on my machine. AI assistance was used to prepare this cherry-pick. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: dragongu <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: dragongu <[email protected]>

Description
Ray Data's DSV2 Parquet reader currently infers its schema from up to 16 files. A column added only in a later file can therefore be absent from the planned Dataset schema. This PR adds an opt-in
read_parquet(..., merge_schema=True)option that discovers every eligible file, merges their footer schemas before returning the Dataset, and givesListFilesthe same discovered path-and-size set for execution.The default 16-file sampling behavior remains unchanged. Full inference uses the existing schema unifier; execution still uses the existing
FooterFileIndexer, row-group bin packing, and optimizer paths. Distributed metadata reads remain a conditional scalability follow-up if a defined workload shows unacceptable driver-side cost.This PR implements the full-schema option requested in #66444. No other open PR was found for that issue or
merge_schema.Related issues
Closes #66444.
Additional information
schemaraises an argument error.Validation
pre-commit run --show-diff-on-failurewith Ray's pinned pre-commit 3.5.0 on Python 3.13 passed for the changed Python files.python -m pytest -q python/ray/data/tests/unit/datasource_v2/test_file_indexer.py python/ray/data/tests/unit/datasource_v2/test_parquet_datasource_v2.py python/ray/data/tests/unit/datasource_v2/test_read_units.py: 97 passed.python -m pytest -q python/ray/data/tests/datasource/test_read_parquet_v2.py: 50 passed.ray.dataPython sources with an installed Ray Core/native build that wasn't compiled from the PR base. These local results don't validate a Core/native build from the target revision.AI assistance was used for the design, implementation, tests, and PR draft.