Skip to content

[Data] Reuse Parquet row counts from schema planning - #67269

Open
jiangxt2 wants to merge 45 commits into
ray-project:masterfrom
jiangxt2:full-schema-planning
Open

jiangxt2 wants to merge 45 commits into
ray-project:masterfrom
jiangxt2:full-schema-planning

Conversation

@jiangxt2

@jiangxt2 jiangxt2 commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Description

Reuse the complete Parquet row count collected during merge_schema=True planning for eligible plain count() 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 changed
Loading

Distributed 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, ListFiles reports 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:

  • Driver and worker planning reuse a complete total; disabling reuse falls back to footer reads.
  • Directory candidates and the planned total survive lineage serialization; files appended after planning are excluded.
  • Unknown file sizes and duplicate input paths preserve count correctness.
  • Filter, limit, projection, and checkpoint cases use the existing path.
  • Footer-read retries work on driver and worker planning paths.
  • Placement-group and resource-constrained planning fall back to the driver; worker schema tests cover lossless schema transport.

For example, the directory lineage test was run with:

python -m pytest -q \
  python/ray/data/tests/datasource_v2/test_planning_metadata.py::test_planning_count_survives_lineage_roundtrip

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.

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]>
@jiangxt2
jiangxt2 marked this pull request as ready for review October 29, 2026 06:16
@jiangxt2
jiangxt2 requested a review from a team as a code owner October 29, 2026 06:16

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

Comment on lines +122 to +133
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

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.

high

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 None

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.

_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.

Comment on lines +75 to +91
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

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

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 payload

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.

_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.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

A few clarifications on the resource and memory trade-offs:

  • Driver fallback: Placement groups, hard node affinity and explicit read-task CPU requests below 0.5 retain driver planning to preserve scheduling compatibility. Budgeted metadata reuse remains available.
  • Scheduling: The window limits unfinished tasks; available resources determine actual concurrency. Observed completions release submission slots independently of candidate-order result consumption. This follows the same completion-driven replenishment principle as Spark.
  • Memory: The 32 MiB budget covers cached metadata payloads, not total planning memory. Spark returns at most one partial schema per partition to the driver; this implementation additionally retains lossless schemas to preserve Ray’s existing merge semantics. Candidate indexes and retained results still grow with input size. Further reductions require separate evaluation.

@abhishekverma-ray

Copy link
Copy Markdown
Contributor

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:

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.

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.

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.

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

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.

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.

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.

Implemented the DataContext/env-var option: schema-read settings in #67542 and global/per-task metadata budgets in #67269 use RAY_DATA_FULL_SCHEMA_INFERENCE_* defaults with explicit DataContext overrides. Configuration and worker-propagation tests cover this.

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.

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]>
@jiangxt2 jiangxt2 changed the title [Data] Distribute Parquet and ORC full schema planning [Data] Reuse Parquet and ORC full-schema planning metadata Oct 30, 2026
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]>

Copy link
Copy Markdown
Contributor Author

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.

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.

@jiangxt2 jiangxt2 changed the title [Data] Reuse Parquet and ORC full-schema planning metadata [Data] Reuse Parquet and ORC metadata collected during schema inference Oct 30, 2026
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]>

@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 using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 81f9f46. Configure here.

@abhishekverma-ray

Copy link
Copy Markdown
Contributor

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?

Comment thread python/ray/data/BUILD.bazel Outdated
Comment on lines +37 to +52
@@ -48,6 +49,7 @@ py_test_module_list(

py_test_module_list(
size = "medium",
data = ["tests/datasource_v2/data/map_empty_struct.parquet"],

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.

we shouldn't be modifying this file; please generate this on the fly

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.

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.

@jiangxt2
jiangxt2 requested a review from a team as a code owner November 17, 2026 06:36
richardliaw pushed a commit that referenced this pull request Nov 17, 2026
## 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]>
@abhishekverma-ray abhishekverma-ray added the go add ONLY when ready to merge, run all tests label Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

I ran count() comparisons with merge_schema=True on MinIO at 10K and 100K files, including the requested tc netem delay 20ms condition for 100K.

All values below are arithmetic means of three runs.

Test Planning: Master → PR count: Master → PR End-to-end: Master → PR Driver peak RSS: Master → PR
10K / cloud server MinIO 118.418 → 118.684 s (+0.22%) 117.293 → 7.077 s (−93.97%) 235.711 → 125.761 s (−46.65%) 241.970 → 346.230 MiB (+43.09%)
100K / LAN server MinIO, 0 ms 71.495 → 69.948 s (−2.16%) 68.410 → 22.760 s (−66.73%) 139.905 → 92.708 s (−33.73%) 297.809 → 443.624 MiB (+48.96%)
100K / LAN server MinIO, 20 ms 64.755 → 65.344 s (+0.91%) 59.113 → 27.968 s (−52.69%) 123.868 → 93.312 s (−24.67%) 298.115 → 442.603 MiB (+48.47%)

For the request-count question, small-scale instrumentation observed the following per-file object-request pattern:

Version Planning count
Master 1 GET 1 GET
PR 1 GET 1 HEAD

@jiangxt2 jiangxt2 changed the title [Data] Reuse Parquet planning metadata [Data] Reuse Parquet row counts from schema planning Nov 20, 2026
@abhishekverma-ray

Copy link
Copy Markdown
Contributor

Thanks for running these! This covers everything I asked for.

count() got faster in all three setups, and planning time didn't change. Two things left:

  1. Driver memory went up by 104–146 MiB (about 45%). The saved row counts are small: about 1.5 MiB for 100K files. With 100K local files, I see driver peak memory of 364–380 MiB on master and 384–404 MiB with this PR, and about the same with caching turned off (RAY_DATA_FULL_SCHEMA_INFERENCE_METADATA_BUDGET_BYTES=0). Could you rerun your 100K case with caching turned off and check whether the extra memory goes away?

  2. Could we make the PR smaller? infer_full_schema_with_metadata_from_files repeats the task loop from infer_full_schema_from_files: the window, the timeout, the cancel and the driver fallback. Could _read_schema_batch return the row counts too, so there's only one loop?

Copy link
Copy Markdown
Contributor Author

Driver memory went up by 104–146 MiB (about 45%).

Could you rerun your 100K case with caching turned off and check whether the extra memory goes away?

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.


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)

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

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

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.

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.

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.

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,

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

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.

I opened #68512 for the count-task environment and placement fix. I’ll sync this PR with master after #68512 merges so the duplicated change drops out.

# 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(

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.

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.

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.

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

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

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.

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.

This branch has not been deployed

No deployments
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants