Repository navigation
Conversation
Batch schema reads into bounded Ray tasks, preserve Ray's merge semantics through safe partials and ordered lossless replay, and reuse budgeted file metadata for Parquet indexing and exact file counts. Signed-off-by: jiangxt2 <[email protected]>
Use driver schema reads for placement-group strategies and explicit None scheduling, which can inherit the caller's group. Preserve read-task resources and cover fractional-CPU Parquet/ORC planning plus normal task admission. Signed-off-by: jiangxt2 <[email protected]>
Merge master while retaining plan-time generated-ID binding and full-schema metadata reuse for Parquet and ORC. Keep hard node-affinity schema inference on the driver and preserve read task environments, placement, and resources in metadata counts. Cover generated IDs, fractional-CPU placement groups, and zero-CPU node affinity with targeted regressions. Signed-off-by: jiangxt2 <[email protected]>
Integrate ORC adaptive batch sizing and Parquet filesystem retries while retaining full-schema planning and metadata counts. Cover sampled and full-schema ORC initial batch sizing together. Signed-off-by: jiangxt2 <[email protected]>
Preserve upstream logical partition types and UDF predicate barriers alongside full-schema planning and optional execution metadata. Combine API test imports without changing existing assertions. Signed-off-by: jiangxt2 <[email protected]>
Combine duplicate schema/metadata and worker checks while retaining assertions, and reuse small typed helpers and format cases. Make driver-fallback tests reach task admission so removing either access constraint is detected. Signed-off-by: jiangxt2 <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces distributed full-schema planning and metadata caching/reuse for file-based datasources (Parquet and ORC) in Ray Data, allowing schema inference to be distributed across bounded Ray tasks and enabling planning metadata (like row counts and Parquet footers) to be reused during execution. Feedback on these changes includes wrapping unify_schemas_with_validation in _merge_same_types with a try...except block to gracefully handle schema conflicts, and wrapping metadata serialization in _FooterBudget.encode with a try...except block to prevent budget leaks in case of serialization failures.
| def _merge_same_types( | ||
| left: Optional[pa.Schema], right: pa.Schema | ||
| ) -> Optional[pa.Schema]: | ||
| """Merge only flat fields whose types stay unchanged across all inputs.""" | ||
| if not _is_flat_schema(right): | ||
| return None | ||
| if left is None: | ||
| return right | ||
| types = {field.name: field.type for field in left} | ||
| if any(field.name in types and types[field.name] != field.type for field in right): | ||
| return None | ||
| return unify_schemas_with_validation([left, right]) or left |
There was a problem hiding this comment.
If unify_schemas_with_validation raises an exception (e.g., due to unexpected schema conflicts or PyArrow validation errors), the worker task will fail. Wrapping this call in a try...except block and returning None allows the system to gracefully fall back to the driver-side full merge instead of failing the entire task.
def _merge_same_types(
left: Optional[pa.Schema], right: pa.Schema
) -> Optional[pa.Schema]:
"""Merge only flat fields whose types stay unchanged across all inputs."""
if not _is_flat_schema(right):
return None
if left is None:
return right
types = {field.name: field.type for field in left}
if any(field.name in types and types[field.name] != field.type for field in right):
return None
try:
return unify_schemas_with_validation([left, right]) or left
except Exception:
return NoneThere was a problem hiding this comment.
_merge_same_types only unifies flat schemas with unique field names and identical types for shared fields. Other inputs already use ordered replay. I haven’t identified a valid input that passes these guards but requires this exception fallback.
| def encode(self, metadata) -> Optional[bytes]: | ||
| # A metadata-only file adds the header, footer length and trailing magic. | ||
| reserved = metadata.serialized_size + 12 | ||
| with self.lock: | ||
| if reserved > self.remaining: | ||
| return None | ||
| self.remaining -= reserved | ||
| with pa.BufferOutputStream() as output: | ||
| metadata.write_metadata_file(output) | ||
| payload = output.getvalue().to_pybytes() | ||
| with self.lock: | ||
| extra = len(payload) - reserved | ||
| if extra > self.remaining: | ||
| self.remaining += reserved | ||
| return None | ||
| self.remaining -= extra | ||
| return payload |
There was a problem hiding this comment.
If metadata.write_metadata_file(output) raises an exception (e.g., due to serialization issues or out-of-memory errors), the reserved bytes that were subtracted from self.remaining will never be restored. This leads to a permanent leak of the budget, which can prevent subsequent files from caching their metadata. Wrapping the serialization in a try...except block ensures that the reserved budget is restored if an exception occurs.
def encode(self, metadata) -> Optional[bytes]:
# A metadata-only file adds the header, footer length and trailing magic.
reserved = metadata.serialized_size + 12
with self.lock:
if reserved > self.remaining:
return None
self.remaining -= reserved
try:
with pa.BufferOutputStream() as output:
metadata.write_metadata_file(output)
payload = output.getvalue().to_pybytes()
except Exception:
with self.lock:
self.remaining += reserved
raise
with self.lock:
extra = len(payload) - reserved
if extra > self.remaining:
self.remaining += reserved
return None
self.remaining -= extra
return payloadThere was a problem hiding this comment.
_FooterBudget is local to each batch. Serialization errors propagate and fail the batch; a new invocation creates a fresh budget. Restoring the reservation before re-raising would not affect subsequent batches.
Signed-off-by: jiangxt2 <[email protected]>
|
A few clarifications on the resource and memory trade-offs:
|
|
Please split this into two PRs. This is two features: distributing the schema reads, and caching footers and row counts from planning into execution. The first is small and clearly worth it. The second adds a new manifest column, a cache-validation protocol, footer budgets, and lineage growth, and deserves its own discussion. Reviewing 2,400 lines across 23 files as one unit is hard, and the two halves have different risk profiles. |
| partial = pa.ipc.read_schema(pa.BufferReader(summary.schema)) | ||
| merged = _merge_same_types(merged, partial) | ||
| eligible = merged is not None | ||
| if not eligible: |
There was a problem hiding this comment.
Any struct, list, map, or extension column makes a batch ineligible, and then the driver pulls every file’s schema and replays the old one-shot merge. For most real Parquet datasets that is the common case, so peak driver memory is unchanged and we also hold the task refs. The issue this closes is about driver memory. Could tasks merge their own batch with unify_schemas and the driver fold the batch results in candidate order? Arrow’s unify is already a left fold, so I’d expect the same answer. If there is a case where it differs, a test showing it would justify the replay.
There was a problem hiding this comment.
The partial-merge/replay path has been removed. The late-object regression covers int64/string/ArrowPythonObjectType: a prefix can fail to merge while the full set is valid, so both PRs retain the ordered one-shot unifier.
#67542 reuses the last decoded schema only for consecutive byte-identical IPC payloads, including nested schemas. This avoids duplicate decoded objects on matches; nonmatching schemas and candidate references can still require O(files) storage, and schema RPC traffic is unchanged.
|
|
||
| # Bound submitted reads, not just executing threads, for full inference. | ||
| _SCHEMA_READ_BATCH_SIZE = 256 | ||
| _SCHEMA_READ_MIN_FILES = 2048 |
There was a problem hiding this comment.
2,048 files, 16 tasks, 0.5 CPU, 32 MiB, and 1 MiB per task are all fixed constants. The footer indexer exposes its actor count, I/O concurrency, and batch size through env vars.
Two ways to say “read footers in parallel on workers” with different knobs is confusing. Either reuse the footer indexer’s actors for planning, or put these on DataContext with the same env-var pattern.
There was a problem hiding this comment.
There was a problem hiding this comment.
Correction to my earlier reply: after the later #67542 feedback to avoid adding public DataContext fields, I kept the two metadata budgets as internal environment-variable settings as well, for consistency. They do not have DataContext overrides.
Plan full schemas with bounded worker tasks or driver fallback. Configure resources through DataContext and preserve ordered schema replay, candidate files, and read scheduling constraints. Signed-off-by: jiangxt2 <[email protected]>
Read schemas in worker batches and apply the original one-shot unifier on the driver. Remove partial reduction, dictionary compression and replay state, and retain scheduling constraints and failure cleanup. Signed-off-by: jiangxt2 <[email protected]>
Keep JSONL tracing as the schema-read recorder. Signed-off-by: jiangxt2 <[email protected]>
Separate metadata reuse from the schema I/O changes in ray-project#67542. Preserve one-shot schema merging and legacy schema hooks while retaining budgeted planning metadata for indexing and exact file counts. Signed-off-by: jiangxt2 <[email protected]>
Pass options directly while preserving all eleven cases, IDs and assertions. Signed-off-by: jiangxt2 <[email protected]>
Keep one payload/schema entry within each inference call and preserve the full candidate sequence for the existing one-shot merge. Signed-off-by: jiangxt2 <[email protected]>
Merge PR1 schema-read updates and preserve per-call single-entry IPC reuse in the metadata-aware consumer. Keep file metadata, footer credits and candidate ordering independent from shared schemas. Signed-off-by: jiangxt2 <[email protected]>
Split into #67542 (schema planning) and #67269 (metadata reuse, validation and lineage transport). #67269 depends on #67542, so its master diff still includes the prerequisite changes; I will synchronize it with master after #67542 merges. |
Assert that the first two schemas fail to unify and that the full candidate sequence resolves to ArrowPythonObjectType. Signed-off-by: jiangxt2 <[email protected]>
Carry the reviewed PR1 assertions into the existing schema-planning test while preserving the custom-extension case and production behavior. Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 81f9f46. Configure here.
Signed-off-by: jiangxt2 <[email protected]>
|
Thanks for these! The team is aligning on some Ray Data test conventions (#67919 / #67928). In short: each test should fail if the change is reverted, extend or parametrize existing tests before adding new ones, test through the public read_* APIs rather than asserting on internal mock calls, and use ray_start_regular_shared instead of starting new clusters. This PR has about 1.7× more test lines than code. Could you trim it to the tests that catch a revert, and note in the description which revert each one catches? |
Signed-off-by: jiangxt2 <[email protected]>
| @@ -48,6 +49,7 @@ py_test_module_list( | |||
|
|
|||
| py_test_module_list( | |||
| size = "medium", | |||
| data = ["tests/datasource_v2/data/map_empty_struct.parquet"], | |||
There was a problem hiding this comment.
we shouldn't be modifying this file; please generate this on the fly
There was a problem hiding this comment.
The binary fixture is now generated at runtime. The remaining BUILD changes add the Python test helper to the relevant test targets and specify the Parquet test entry point.
Signed-off-by: jiangxt2 <[email protected]>
## Description
Parallelize eligible Parquet and ORC `merge_schema=True` reads with
bounded Ray tasks. Each task deduplicates schemas by IPC bytes and
returns distinct schema payloads with their first file positions; the
driver restores their order and runs the existing one-shot unifier. When
IPC is lossy and generated Parquet metadata cannot preserve a Parquet
schema, workers return verified original file metadata.
The formats share per-file readers between driver and workers. If no
task returns within 30 seconds, cancellation is attempted for pending
tasks and planning falls back to the driver. Default sampled planning
and unsupported scheduling fallbacks are preserved. The inherited
full-schema implementation respects `infer_schema` overrides on Parquet
and ORC subclasses.
Task-local deduplication reduces repeated schema payloads when a batch
contains identical schemas; distinct schemas and file paths can still
require O(files) storage.
**Before:** full-schema reads run on driver threads.
**After:** eligible reads run on workers, followed by the existing
driver merge.
Subsystems: IO and API.
```mermaid
flowchart LR
subgraph Before["Before · IO: full-schema planning"]
B1["Candidate files"] --> B2["Driver reads schemas"] --> B3["One-shot merge"]
end
subgraph After["After · IO: full-schema planning"]
A1["Candidate files"] -->|Eligible| A2["Bounded worker reads and per-task deduplication"]
A2 --> A3["Driver orders schemas and merges once"]
A1 -->|Fallback| A4["Driver reads schemas"] --> A3
end
classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
class A2,A3 changed
```
## Related issues
Related to #67040. Execution-time footer and row-count reuse remain in
#67269.
## Additional information
### Testing
Targeted tests passed in separate invocations:
- Planner unit tests cover candidate ordering, per-batch deduplication,
task options, timeout, and cancellation.
- Worker schema tests detect driver fallback and loss of schema metadata
or extension fields.
- Placement tests verify driver fallback and read placement for
placement groups, zero CPU, and explicit `None`.
- Parquet reader tests verify footer retries and listed file-size
forwarding; the ORC reader test verifies retries.
Reproduction selections:
```bash
python -m pytest -q \
python/ray/data/tests/unit/datasource_v2/test_full_schema_planning.py \
python/ray/data/tests/unit/datasource_v2/test_parquet_datasource_v2.py::test_parquet_schema_reader_uses_listed_size_and_retries \
python/ray/data/tests/unit/datasource_v2/test_orc_datasource_v2.py::test_orc_schema_reader_retries_schema_read
python -m pytest -q \
python/ray/data/tests/datasource_v2/test_distributed_schema_planning.py::test_schema_reads_use_selected_workers \
python/ray/data/tests/datasource_v2/test_distributed_schema_planning.py::test_driver_schema_fallback_preserves_read_placement \
python/ray/data/tests/datasource_v2/test_schema_worker_semantics.py
```
Tests ran on Linux arm64 with Python 3.12, PyArrow 23 and a prebuilt Ray
Core runtime. Applicable Ruff, Black and Pyrefly checks passed. The
requested real-S3 comparisons at 10k and 100k files have not been run.
AI assistance: Codex assisted with implementation, tests, documentation
and static review.
---------
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
|
I ran All values below are arithmetic means of three runs.
For the request-count question, small-scale instrumentation observed the following per-file object-request pattern:
|
Signed-off-by: jiangxt2 <[email protected]>
|
Thanks for running these! This covers everything I asked for.
|
Thanks for catching this. My earlier benchmark used a version that still included experimental Parquet footer caching. I removed that code and pushed the updated PR after the test. I should have verified the tested version before reporting the results. Sorry for the confusion. On the same 10,000-file dataset, the updated PR’s Driver peak RSS was 240.80 MiB with the row-count cache enabled and 240.98 MiB with it disabled—one run each. In a separate A-B-B-A comparison, restoring footer collection and retention increased mean peak RSS from 241.71 MiB to 349.88 MiB. The increase appeared while building file-info blocks containing footer metadata. |
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
…ressions Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
…ference Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
|
|
||
| def _num_rows(path: str, file_size: Optional[int]) -> int: | ||
| def _num_rows(file: FileInfo) -> int: | ||
| cached = get_cached_file_metadata(file, filesystem, retried_io_errors) |
There was a problem hiding this comment.
Thanks for the update! count() still sends one get_file_info per file (a HEAD on S3), so we trade one footer GET for one HEAD. On in-region S3 both cost about one round trip, so I'd expect most of the win to go away there. The check also doesn't fully protect us:
- s3fs gives no mtime.
- A rewrite with the same size and the same mtime passes. I reproduced this:
count()returned 24 while the file had 25 rows. - When the size changed, we still open the file with the old listed size.
Since merge_schema=True already freezes the file list and sizes at planning, could we trust the saved counts the same way and drop the check? That would also remove the mtime plumbing (include_mtime, FileInfo.mtime_ns, __file_mtime_ns, file_metadata.py). And when every file has a count, count() could be answered on the driver with no tasks.
There was a problem hiding this comment.
Thanks! I removed the per-file validation and mtime plumbing. An eligible plain count() now returns the complete planned total directly. The docstring notes that it reflects the files at planning time.
| supports_distributed_reads=self.supports_distributed_reads, | ||
| ) | ||
| if result is None: | ||
| return FullSchemaInferenceResult(self.infer_schema(sample)) |
There was a problem hiding this comment.
When planning runs on the driver, we still read every footer but drop num_rows, so count() reads them all again. That happens with 2048 files or fewer, under a placement group, or after a first-result timeout. Could the driver path keep the counts too? It's about 16 B per file, and count() would then behave the same whatever the cluster looked like at planning time.
There was a problem hiding this comment.
Driver planning now collects the total alongside the schema, including placement-group and timeout fallback paths.
| # placement together with the resources requested for that placement. | ||
| ray_remote_args={ | ||
| "num_cpus": self._PER_TASK_NUM_CPUS_ALLOCATION, | ||
| **read_files.ray_remote_args, |
There was a problem hiding this comment.
This now copies all read remote args onto the count tasks. So read_parquet(..., num_cpus=4) makes each footer-count task take 4 CPUs instead of 0.5, and num_gpus=1 makes count tasks hold a GPU. This affects every V2 Parquet count(), not only merge_schema=True. Carrying runtime_env and label_selector over looks like a real fix, but it's separate from row-count reuse. Could it go in its own PR, copying only the env and placement keys?
| # Estimated row-count metadata budgets, internal rather than public config. | ||
| # Zero disables caching. Index scaffolding, schemas and temporary copies are | ||
| # excluded from these budgets. | ||
| _FULL_SCHEMA_INFERENCE_METADATA_BUDGET_BYTES = env_integer( |
There was a problem hiding this comment.
The saved data is two int64s per file, much smaller than the paths we already keep. Do we need two byte budgets plus a 32 B estimate? At the defaults the per-task budget never applies (32,768 > batch size 256). A single on/off switch would let us drop the row_slots/row_limit math and its test.
There was a problem hiding this comment.
I removed both budgets and their allocation logic. Planning now retains one complete total, controlled by a single internal on/off switch.
| @@ -0,0 +1,270 @@ | |||
| import os | |||
There was a problem hiding this comment.
Thanks for trimming! A few tests could still go or move:
- The generated-id test checks code this PR doesn't change.
- The zero-CPU placement test belongs with the count remote-args change, and it starts its own cluster instead of using a shared fixture.
- The budget and stat unit tests go away if we drop the budgets and the stat.
Could the remaining count-reuse cases be parametrized into the existing distributed-schema-planning tests?
There was a problem hiding this comment.
I removed the generated-ID, zero-CPU placement, budget, and stat tests. The count-reuse cases are parametrized in test_planning_metadata.py; the existing distributed-planning fallback tests also cover driver reuse.
Signed-off-by: jiangxt2 <[email protected]>

Description
Reuse the complete Parquet row count collected during
merge_schema=Trueplanning for eligible plaincount()operations. Other counts use the existing execution path.#67542 distributes full-schema reads; this PR reuses the total when every candidate file reports a row count.
Before: Eligible counts reread Parquet footers after schema planning.
After: Driver and worker planning can retain one complete total. An eligible plain count returns it directly; other counts use the existing path. Row-group indexing still reads the original footer.
flowchart TD subgraph Before["Before"] subgraph B["IO: Parquet"] B1["Schema planning"] --> B2["Count reads footer"] end end subgraph After["After"] subgraph A["IO: Parquet"] A1["Driver or worker schema planning"] --> A2["Collect complete row count"] A2 -->|"Eligible plain count"| A3["Return planned count"] A2 -->|"Other counts"| A4["Existing count path"] end end classDef changed fill:#fff9c4,stroke:#f9a825,color:#000 class A2,A3 changedDistributed schema-only and row-count planning share the batch reader and worker task loop introduced by #67542. If distributed planning is unavailable or the first result times out, planning falls back to the driver. Parquet metadata reads reuse the existing reader, including listed sizes and configured I/O retries; ORC remains on the schema-only path.
Count pushdown preserves the read task's environment and placement options, including when
merge_schema=False(#68512). For prelisted files,ListFilesreports an unknown output schema because the indexer determines its output columns. Listing and manifests retain the unknown-file-size behavior from #68397.Subsystems: IO, API, logical planning / query optimization.
Related issues
Related to #67040. The metadata reuse motivation was discussed in #66522.
Additional information
The planned total reflects the candidate files at planning time. Inputs must remain stable: changes or deletions after planning may not be reflected in a plain count. Returning the planned total does not perform per-file validation.
The total is used only when every candidate file reports a count and the read has no filter, limit, pruning, projection, block UDF, or checkpoint configuration. Other cases use the existing path.
Testing
Focused tests passed on Linux arm64 with Python 3.12, PyArrow 23.0.1, and a prebuilt Ray Core:
For example, the directory lineage test was run with:
Ruff, Black, and Ray Data Pyrefly checks passed. The full suite was not run locally.
AI assistance: Codex assisted with implementation, tests, documentation and static review.