Skip to content

[Data] Add opt-in full Parquet schema inference - #66522

Merged
richardliaw merged 7 commits into
ray-project:masterfrom
jiangxt2:design/issue-66444-parquet-schema-merge
Oct 15, 2026
Merged

richardliaw merged 7 commits into
ray-project:masterfrom
jiangxt2:design/issue-66444-parquet-schema-merge

Conversation

@jiangxt2

@jiangxt2 jiangxt2 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

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 gives ListFiles the 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

  • The option requires DSV2. Combining it with an explicit schema raises an argument error.
  • Delta and Iceberg readers obtain their schemas from table-backed dataset or scan metadata, rather than Parquet V2's 16-file sample.
  • Full mode performs an up-front directory listing and reads every candidate footer. Retained path metadata grows with file count, and the driver holds per-file schemas until the merge finishes. It is intended for reads where a complete planned schema justifies that cost.
  • The Dataset retains the discovered candidate paths across actions. Files appended after discovery are excluded from that Dataset; a concurrent directory traversal is not an atomic snapshot, and replacing a file at the same path is outside this guarantee.
  • Existing DSV2 type-promotion and nullability semantics are preserved. Missing non-nullable nested children can still fail during scanning. A missing native FixedShapeTensor column is null in Arrow batches, but the existing row conversion can represent those nulls as zero-valued NumPy arrays; this PR does not change that behavior.

Validation

  • pre-commit run --show-diff-on-failure with 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.
  • The Ray tests used the PR's ray.data Python 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.

@jiangxt2 jiangxt2 closed this Sep 28, 2026
@jiangxt2 jiangxt2 reopened this Sep 28, 2026
@jiangxt2

jiangxt2 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor Author

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 read_parquet(..., merge_schema=True) option requires DSV2 and cannot be combined with an explicit schema. It is passed into DSV2 planning as:

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,

ParquetDatasourceV2.infer_schema then reads the selected files’ footer schemas and uses Ray’s existing unifier:

schema = (
    unify_schemas_with_validation(per_file_schemas)
    or per_file_schemas[0]
)

So merge_schema=True changes which files contribute schemas, while retaining the existing schema unification and nullability behavior. The default remains the 16-file sample.

For the opt-in path, the discovered path-and-size records are retained on the Dataset plan. At execution, ListFiles consumes those candidates without relisting the directory; later pruning and checkpoint exclusions may narrow the set. For normal data reads, FooterFileIndexer reads execution-time row-group metadata, which then reaches the existing OnlineBinPacker. Full footers and prepacked read units are not retained.

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.

@jiangxt2

Copy link
Copy Markdown
Contributor Author

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, ParquetDatasourceV2.infer_schema reads the selected footers on the driver with at most 16 threads, then applies Ray’s existing one-shot schema unifier. This is a contiguous excerpt from the current Ray code:

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 SchemaMergeUtils offers an architectural reference. It distributes previously discovered path-and-length information across executor partitions, reads and merges schemas within each partition, then merges the partial results on the driver. These two consecutive source lines show the distribution step:

.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. local:// footer reads would stay on the driver, and the default 16-file sampling path would remain unchanged.

What file counts and storage systems would make this follow-up valuable? Feedback on the workload and the staged approach is welcome.

@jiangxt2
jiangxt2 marked this pull request as ready for review September 29, 2026 03:03
@jiangxt2
jiangxt2 requested a review from a team as a code owner September 29, 2026 03:03

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +315 to +319
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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jiangxt2

Copy link
Copy Markdown
Contributor Author

I ran a local Docker benchmark against PR commit a9984c8. The container used Ray 2.58.0 with this PR's Ray Data Python source, PyArrow 23.0.1, Linux arm64, --cpus=8, and --memory=12g.

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 read_parquet() returning a Dataset after Ray startup. Each result is the median of three trials.

Files Row groups/file Footer/file Default 16-file sample merge_schema=True
1,000 8 20,162 bytes 0.012 s 0.200 s
10,000 8 20,162 bytes 0.082 s 2.457 s
10,000 32 73,995 bytes 0.066 s 3.054 s

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.

@ray-gardener ray-gardener Bot added python Pull requests that update Python code data Ray Data-related issues community-contribution Contributed by the community labels Sep 29, 2026
@abhishekverma-ray

Copy link
Copy Markdown
Contributor

Thanks for the detailed write-up. A couple of questions.

  • Planning reads every footer on the driver, and execution reads the same footers again on the footer actors. Can the schema come from the existing distributed footer path instead, so each footer is read once and the driver is not the bottleneck?

  • Retaining the file list. This makes merge mode a frozen snapshot while default mode re-lists on every run. Is that a behavior we want tied to a schema flag?

@@ -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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread python/ray/data/read_api.py Outdated
# 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jiangxt2

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed write-up. A couple of questions.

  • Planning reads every footer on the driver, and execution reads the same footers again on the footer actors. Can the schema come from the existing distributed footer path instead, so each footer is read once and the driver is not the bottleneck?
  • Retaining the file list. This makes merge mode a frozen snapshot while default mode re-lists on every run. Is that a behavior we want tied to a schema flag?

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.

@jiangxt2
jiangxt2 force-pushed the design/issue-66444-parquet-schema-merge branch from a9984c8 to 7e272ee Compare September 30, 2026 11:42
@jiangxt2
jiangxt2 force-pushed the design/issue-66444-parquet-schema-merge branch from 7e272ee to b7f51ba Compare September 30, 2026 12:14
@AarryaSaraf AarryaSaraf self-assigned this Oct 1, 2026
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]>
@abhishekverma-ray

Copy link
Copy Markdown
Contributor

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.

@abhishekverma-ray abhishekverma-ray added the go add ONLY when ready to merge, run all tests label Oct 14, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 16999dd. Configure here.

@richardliaw
richardliaw enabled auto-merge (squash) October 15, 2026 04:53
@richardliaw
richardliaw merged commit c7e5160 into ray-project:master Oct 15, 2026
7 checks passed
@jiangxt2
jiangxt2 deleted the design/issue-66444-parquet-schema-merge branch October 27, 2026 07:07
sai-miduthuri added a commit that referenced this pull request Nov 13, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues go add ONLY when ready to merge, run all tests python Pull requests that update Python code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] Discuss full schema inference beyond the DSV2 16-file sample

4 participants