Skip to content

[Data] Pack Parquet read tasks by estimated decoded size in DSv2 [5/6] - #67840

Open
AarryaSaraf wants to merge 185 commits into
masterfrom
aarrya/decoded-size-5-packing
Open

AarryaSaraf wants to merge 185 commits into
masterfrom
aarrya/decoded-size-5-packing

Conversation

@AarryaSaraf

@AarryaSaraf AarryaSaraf commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

Stacked on #67839.

Parquet reads in DataSourceV2 now pack row groups into read tasks by their estimated decoded Arrow size (#67837, #67838) instead of their uncompressed bytes, which size a dictionary-encoded string column at a few bytes a row however long its values are. A read task's output now stays near the block target, 128 MiB by default, and a row group estimated over the target gets a task of its own. Each row group also records the memory PyArrow is estimated to peak at while decoding it (#67839). Nothing reads that yet; #67841 requests it as the read task's memory.

How it works: the footer reader already opens every file's footer to list its row groups. It now also reads SizeStatistics (#67836) from that footer and gives each row group two numbers, FileChunk.size_bytes and the new FileChunk.memory_bytes. So that they describe what the read returns rather than what the file stores, the indexer is given the schema once it is inferred, and the footer readers see the read's options and the schema it casts to.

flowchart TD
    RA["read_api, after schema inference"] -->|"format kwargs, dataset schema"| FI["Footer file indexer"]
    FI -->|"each file"| FR["FooterReader"]
    FR -->|"footer and its SizeStatistics"| S["_row_group_sizes, per row group"]
    S -->|"estimated decoded bytes"| SB["FileChunk.size_bytes"]
    S -->|"estimated decode peak"| MB["FileChunk.memory_bytes"]
    SB -->|"packed up to the block target"| BP["Bin packer"]
    MB -->|"summed per run"| BP
    BP -->|"one bin per task"| RT["Read tasks"]
Loading
  • FooterReader._row_group_sizes returns both numbers. size_bytes is the decoded size of the leaves the estimator models, a pinned schema's cast and the columns Ray appends. memory_bytes is [Data] Estimate PyArrow's peak memory decoding a Parquet row group from its footer [4/6] #67839's peak over that: the I/O and the decode buffers on top.
  • Leaves the estimator doesn't model are charged 4 times their uncompressed bytes, and at least 12 MiB per row group (_unmodelled_bytes), in both numbers. That is every leaf of a file read with binary_type or list_type or whose schema PyArrow can't convert, and otherwise a view, an Arrow dictionary, a BYTE_ARRAY column dictionary_columns names, a list or a dictionary- or DELTA_BYTE_ARRAY-encoded string without SizeStatistics, or a column whose shape a cast changes. The floor is for dictionary-encoded strings, whose uncompressed bytes are a dictionary and bit-packed indices.
  • The predicate's columns are sized first, then the projection's, in the order PyArrow decodes them (read_order): PyArrow decodes a predicate column to evaluate the filter even when the projection drops it.
  • read_api gives the file indexer the inferred schema through FileIndexer.with_read_schema, which returns the indexer unchanged by default. The Parquet footer indexer keeps the schema, and the Hive indexer forwards it to the Parquet indexer it wraps.
  • The reader and the footer reader now share the rules for what a file is cast to. file_dataset_schema (common/file_reader.py) gives the schema a file's batches are cast to, without its partition keys and the columns the reader appends. read_format_kwargs (parquet_utils.py) drops dictionary_columns, binary_type and list_type when the read casts, since the cast undoes them.
  • The bin packer's budget is the block target (make_row_group_bin_packer(shuffle, hints)), or DEFAULT_TARGET_MAX_BLOCK_SIZE when block sizing is off. It was 128 MiB of uncompressed bytes whatever the block target, so a smaller target_max_block_size now means more read tasks. RAY_DATA_PARQUET_BIN_PACKING_BYTES still overrides it. Delta reads pass the block target too. The docs of DataContext.small_shuffle_chunk_size and FileShuffleConfig now say their sizes are estimated decoded bytes.
  • Coalescing and packing sum memory_bytes over the row groups they merge (parquet_row_group_coalescing.py, online_bin_packer.py); a run split across bins carries its share by bytes.
  • A read task's first batch size comes from size_bytes / num_rows, no longer the uncompressed bytes per row times 5.

Before and after, for two 200,000-row row groups written and measured with PyArrow 26.0.1: an int64 and a double column, and a string column holding "COMPLETED_SUCCESSFULLY" or "OK", which PyArrow dictionary-encodes.

int64 + double Status strings
Uncompressed bytes, master's size 3.57 MiB 0.02 MiB
Decoded bytes, measured 3.10 MiB 3.69 MiB
size_bytes 3.10 MiB 3.69 MiB
PyArrow's peak, measured 8.89 MiB 5.32 MiB
memory_bytes 9.75 MiB 7.38 MiB
Row groups that fit a 128 MiB bin, master → this PR 35 → 41 5,145 → 34
Decoded bytes in that bin, master → this PR 108 → 127 MiB 18.5 GiB → 125 MiB

The accuracy table this description had came from packing by the decode peak. The bench #67838 describes hasn't been re-run on this sizing, so it is left out.

Listing cost: the footer reader now sizes row groups from every footer it opens, about 10 µs of Python per column chunk on top of master. Nothing is read past the footer, with or without SizeStatistics. To bound that, a file with more than 1,000 column chunks (columns × row groups) has only its first, middle and last row groups sized (_row_groups_to_size), and the footer walk skips to those three (_CompactReader._jump). Every other row group takes the highest bytes per row and per stored byte of the three, plus 25% (_SizedRates). A file at or under 1,000 has every row group sized.

Milliseconds per file by footer shape (columns × row groups), on local disk: one footer reader, batches of 10 files, io_concurrency 1; Apple M5, PyArrow 26.0.1.

Shape master This PR
20 × 4 0.12 0.95
100 × 10 0.77 10.3
1,000 × 10 6.97 40.8
100 × 100 5.64 8.51

End to end from S3, listing 3,830 files of 100 × 100 with the default 8 footer actors on 8 CPUs (x86_64 Linux, PyArrow 24.0.0) took 15.0 to 19.6 s on master over five runs and 21.8 and 22.8 s on this PR. Sizing every row group of those files took 238 s.

Tests:

  • tests/unit/datasource_v2/test_parquet_decode_peak.py gains cases that run real files through the footer reader, coalescing and the bin packer: size_bytes is the decoded size and sits under memory_bytes; a small unmodelled row group pays the 12 MiB floor once and a large one 4 times its uncompressed bytes; a pinned schema adds the cast and the added columns; a partition column is sized by its value; bins stay under the budget; and a file over the column-chunk limit has three row groups sized and the others no smaller than their own sizes.
  • test_parquet_size_statistics.py checks that reading only some row groups gives what the full walk gives for them, with identical row groups too, and that a row group the skip can't find falls back to the full walk.
  • test_online_bin_packer.py and test_parquet_row_group_coalescing.py check that packed and coalesced runs carry their summed memory_bytes. test_parquet_datasource_v2.py checks the bin budget and that a reader which casts drops the type options.
  • 387 passed in the ten changed files under tests/unit/datasource_v2/ and 58 in tests/datasource_v2/test_footer_reader.py, on Python 3.10 with PyArrow 23.0.0 and 25.0.1 and on Python 3.12 with PyArrow 26.0.1. Not run locally: the Delta file's test, which needs deltalake, and two tests in test_parquet_datasource_v2.py that need a Ray cluster.
  • Two tests elsewhere change with it. test_size_estimation.py::test_split_read_parquet and test_checkpoint.py::test_generated_id_read_keeps_block_size set RAY_DATA_PARQUET_BIN_PACKING_BYTES so their file stays one read task, which the smaller bin budget would split. The checkpoint test now checks that generated IDs leave at least as many blocks as the plain read, not exactly 8.

Signed-off-by: Aarrya [email protected]

🤖 Generated with Claude Code

AarryaSaraf and others added 10 commits October 30, 2026 12:13
…w doesn't expose

Co-authored-by: Goutam <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…ader dataclasses

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
… per leaf

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…le docstring

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>

@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 refactors the Parquet metadata and footer reading logic in Ray Data to size row groups based on PyArrow's estimated peak memory usage during decoding, rather than using the projection-scoped uncompressed size. This peak memory estimate is then utilized for more accurate bin packing and coalescing of row groups. Feedback on the changes suggests optimizing membership lookups in _added_bytes by pre-computing a set of read_order to avoid O(M * N) list scans, and wrapping the inner loop of _read_dictionary_pages in a try-except block to ensure that a single corrupt dictionary page does not prevent reading subsequent valid pages.

Comment on lines +228 to 232
self.read_order: list[str] | None = (
list(dict.fromkeys([*self.filter_columns, *projected_cols]))
if projected_cols is not None
else 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.

medium

In _added_bytes, field.name in self.read_order is checked for each field in self.read_schema. Since self.read_order is a list, this results in an $O(M \times N)$ lookup per file, which can be slow for wide schemas and many files. We can optimize this by pre-computing a set of self.read_order in __init__ and using it for $O(1)$ membership lookups.

Suggested change
self.read_order: list[str] | None = (
list(dict.fromkeys([*self.filter_columns, *projected_cols]))
if projected_cols is not None
else None
)
self.read_order: list[str] | None = (
list(dict.fromkeys([*self.filter_columns, *projected_cols]))
if projected_cols is not None
else None
)
self._read_order_set = (
set(self.read_order) if self.read_order is not None else 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.

The lookup only runs for the few columns a file lacks, so a set isn't worth it.

Comment on lines +564 to +568
if (
self.read_order is None
or field.name in self.read_order
or field.type == GENERATED_ID_COLUMN_TYPE
):

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

Use the pre-computed self._read_order_set instead of self.read_order to perform $O(1)$ membership lookups, avoiding $O(N)$ list scans for each field in the schema.

Suggested change
if (
self.read_order is None
or field.name in self.read_order
or field.type == GENERATED_ID_COLUMN_TYPE
):
if (
self._read_order_set is None
or field.name in self._read_order_set
or field.type == GENERATED_ID_COLUMN_TYPE
):

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 lookup only runs for the few columns a file lacks, so a set isn't worth it.

Comment on lines +529 to +537
for rg_idx, leaf_idx, offset, nbytes in wanted:
buf = call_with_retry(
functools.partial(f.read_at, nbytes, offset),
description=f"read a dictionary page of {path}",
match=self.retried_io_errors,
)
page = read_dictionary_page(buf)
if page is not None:
pages.setdefault(rg_idx, {})[leaf_idx] = page

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

In _read_dictionary_pages, if reading or parsing a dictionary page for a single column/row group fails, the entire loop is aborted because the try-except block wraps the outer with block. This means that a single corrupt or failing page will prevent reading all subsequent valid dictionary pages for other row groups or columns, reverting them to the fallback estimate. Wrapping the inner loop body in a try-except block would make the process more robust by allowing it to continue reading other valid pages.

Suggested change
for rg_idx, leaf_idx, offset, nbytes in wanted:
buf = call_with_retry(
functools.partial(f.read_at, nbytes, offset),
description=f"read a dictionary page of {path}",
match=self.retried_io_errors,
)
page = read_dictionary_page(buf)
if page is not None:
pages.setdefault(rg_idx, {})[leaf_idx] = page
for rg_idx, leaf_idx, offset, nbytes in wanted:
try:
buf = call_with_retry(
lambda: f.read_at(nbytes, offset),
description=f"read a dictionary page of {path}",
match=self.retried_io_errors,
)
page = read_dictionary_page(buf)
if page is not None:
pages.setdefault(rg_idx, {})[leaf_idx] = page
except Exception as e:
logger.debug(
"Error reading dictionary page for row group %d, leaf %d: %s",
rg_idx,
leaf_idx,
e,
exc_info=True,
)

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.

Gone: the footer reader no longer reads dictionary pages.

…binaries image so //:ray_pkg_zip can build it

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@AarryaSaraf
AarryaSaraf force-pushed the aarrya/decoded-size-5-packing branch from 95e3ee2 to 49de0ac Compare November 4, 2026 22:36

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

Stale Bugbot comment from a previous run.

…ed Parquet walk, which a signed cast could turn negative

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@AarryaSaraf
AarryaSaraf force-pushed the aarrya/decoded-size-5-packing branch from 49de0ac to b44ff13 Compare November 4, 2026 23:28

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

Stale Bugbot comment from a previous run.

@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Nov 5, 2026
…n walk and reading dictionary page headers in the compiled reader

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@AarryaSaraf
AarryaSaraf force-pushed the aarrya/decoded-size-5-packing branch from b44ff13 to 8544e4e Compare November 5, 2026 02:06

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

Stale Bugbot comment from a previous run.

…ompact reader builds on Windows

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
AarryaSaraf and others added 4 commits November 13, 2026 15:11
@AarryaSaraf
AarryaSaraf requested a review from a team as a code owner November 17, 2026 22:09
AarryaSaraf and others added 2 commits November 17, 2026 14:11

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

Stale Bugbot comment from a previous run.

statistics = chunk.statistics
if statistics is None or not statistics.has_min_max:
return None
longest = max(len(statistics.min_raw), len(statistics.max_raw))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Dictionary guess crashes on null min

Medium Severity

_dictionary_string_bytes treats statistics.has_min_max as enough to call len on min_raw and max_raw. Some writers set the min/max flag while leaving those raw buffers unset, so len(None) raises and the footer read fails for that file. The method already returns None to fall back to the unmodelled charge when statistics are missing; the same fallback does not run when the raw values are null.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c01879e. Configure here.

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

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 25cb699. Configure here.

return ["hive://direct"]

def _get_file_indexer(self) -> FileIndexer:
def _get_file_indexer(self, schema: Optional[pa.Schema] = None) -> FileIndexer:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hive parquet listing drops inferred schema

Medium Severity

HiveDirectDatasource._get_file_indexer accepts the inferred schema but never forwards it, and _HiveFileIndexer still builds the wrapped Parquet indexer with no schema. Hive parquet listing therefore sizes row groups from the file's own types only, so Hive casts and schema-evolution columns the reader will materialize are missing from size_bytes. Bins can pack past the block target on those reads.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 25cb699. Configure here.

AarryaSaraf and others added 8 commits November 23, 2026 15:17
…eak estimate and address review comments

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Signed-off-by: Aarrya <[email protected]>

# Conflicts:
#	python/ray/data/tests/unit/datasource_v2/test_parquet_decode_peak.py
Signed-off-by: Aarrya <[email protected]>

# Conflicts:
#	python/ray/data/_internal/datasource_v2/common/file_reader.py
#	python/ray/data/_internal/datasource_v2/formats/mcap/mcap_datasource_v2.py
#	python/ray/data/_internal/datasource_v2/formats/parquet/footer_file_indexer.py
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…ith_read_schema

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Base automatically changed from aarrya/decoded-size-4-peak to master November 24, 2026 05:26
goutamvenkat-anyscale added a commit that referenced this pull request Nov 24, 2026
…om its footer [4/6] (#67839)

## Description

Stacked on #67838.

A read task's memory peaks while PyArrow decodes a row group, well above
the decoded Arrow bytes #67837 estimates. For 200,000 rows of an `int64`
and a `double` column, the decoded table is 3.1 MiB but PyArrow's memory
pool peaks at 8.9 MiB when a read task scans it.
`parquet_decode_peak.py` estimates that peak from the footer, without
decoding anything: 9.8 MiB here. Nothing calls it yet, so behavior
doesn't change.

The inputs are the footer as PyArrow parses it, the `SizeStatistics`
#67836 reads from it, the file's size from the listing, and how many CPU
threads PyArrow decodes on.

A column, as `columns=` names it, is stored as one or more leaves,
Parquet's primitive columns: an `int64` column has one leaf, a
`struct<a: int64, b: string>` two. Each of PyArrow's CPU threads decodes
one column at a time, and a column's leaves one after another. A leaf's
buffers are either kept until its column is read or temporary, freed
once that leaf is decoded. Once a column is read, only its decoded
values stay. A Ray read task gives PyArrow one CPU thread
(`RAY_DATA_PARQUET_READER_CPU_COUNT`, which #67840 passes in).

```mermaid
flowchart TD
    F["Footer and its SizeStatistics"] -->|"each leaf's sizes and encodings"| L["estimate_leaf_work, per leaf"]
    L -->|"a column's leaves in turn"| C["Each column's buffers"]
    F -->|"each leaf, #67837"| D["Every column's decoded values"]
    C -->|"the largest, one column per CPU thread"| P["Row group peak"]
    D --> P
    F -->|"80 KiB footer read and gaps + compressed chunks"| P
    S["File size"] -->|"under 48 KiB: the file instead"| P
    X["estimate_cast"] -->|"a pinned schema's cast x 1.5"| P
```

Modelled on PyArrow 24's reader, a row group's peak is the sum of four
parts:

1. **I/O** (`estimate_row_group_peak`): PyArrow's 64 KiB footer read and
up to two of the 8 KiB gaps `pre_buffer` reads between chunks, 80 KiB in
all, plus each chunk's compressed bytes. A file under 48 KiB was read
whole by the footer read, so it's charged its size plus 512 bytes and
256 bytes per leaf read instead.
2. **Every column's decoded values** (#67837).
3. **The buffers of the columns decoding at once**
(`estimate_row_group_work`, `estimate_leaf_work`). A leaf keeps its
`int16` definition and repetition levels, its dictionary plus 16 bytes
an entry for strings (an entry per 4 bytes of dictionary, the most it
can hold), and for a compressed chunk the buffer pages decompress into,
the larger of the chunk's uncompressed bytes and its dictionary page.
DELTA encodings add 4 bytes a value for the lengths they unpack, and
`DELTA_BYTE_ARRAY` its prefix lengths and rebuilt values too. Its
temporaries are offsets reserved past the values used, the string
builder's copy of the values, and list offsets. A column's buffers peak
at one leaf's temporaries on top of what that leaf and the ones before
it keep. The estimate adds the buffers of the `decode_threads` largest
columns, or of every column when it is 0 or less.
4. **A pinned schema's cast** (`estimate_cast`): #67838's estimate of
the cast columns, × 1.5 because casts to text measured higher, plus the
columns Ray adds.

A leaf #67837 doesn't model is left out here; #67840 charges it.

Underestimating is what causes OOMs, so the rules lean high. These
numbers were measured before the review changes to #67838 and not re-run
since. On the bench #67838 describes (10,000 random files, 148,166 row
groups), PyArrow's pool peak was measured for each row group as a read
task scans it: one CPU thread, 16 IO threads. On the 30,127 whose every
leaf and cast the estimate models, none is under 0.95× (the lowest is
0.996×, a 34-row group):

| Estimate ÷ PyArrow's peak | All modelled (30,127) | Peak ≥ 1 MiB
(7,573) |
|---|---|---|
| < 0.95 | 0 | 0 |
| 0.95–1.2 | 10.1% | 18.5% |
| 1.2–1.5 | 34.3% | 46.1% |
| 1.5–2 | 38.6% | 28.9% |
| 2–3 | 16.5% | 6.3% |
| > 3 | 0.5% | 0.3% |
| median / p90 | 1.55× / 2.16× | 1.40× / 1.85× |

Tests: `tests/unit/datasource_v2/test_parquet_decode_peak.py` (new), 6
passed. It writes 200,000-row files (an `int64` and a `double`, a
nullable `int16`, strings with 50,000 distinct values, a list column
read after an `int64` column, and eight list columns on one CPU thread
and on 12), measures PyArrow's peak as a read task scans each one, on
PyArrow's default memory pool in a fresh process, and checks the
estimate lands within 0.95–1.5× of it. The cases need PyArrow ≥ 23 for
`SizeStatistics`.

Signed-off-by: Aarrya <[email protected]>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Goutam <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>

# Conflicts:
#	python/ray/data/tests/unit/datasource_v2/test_parquet_datasource_v2.py
#	python/ray/data/tests/unit/datasource_v2/test_parquet_decode_peak.py
Comment on lines +115 to +118
statistics = chunk.statistics
if statistics is None or not statistics.has_min_max:
return None
longest = max(len(statistics.min_raw), len(statistics.max_raw))

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.

Dictionary string columns can be sized hundreds of times too small

Problem. min_raw / max_raw are the lexicographically smallest and largest values, not the longest ones. Some writers also truncate them. So longest here can be 1 byte for a column of 2 KB strings.

Repro (PyArrow 23.0.1):

N = 200_000
vals = ["a", "z"] + [f"https://example.com/{i % 50:04d}/" + "x" * 2000 for i in range(N - 2)]
pq.write_table(pa.table({"s": vals}), "lex.parquet", row_group_size=N)
# footer: has_dictionary_page=True, total_uncompressed_size=288757,
#         len(min_raw)=1, len(max_raw)=1
Size
True decoded size 387.00 MiB
This PR's estimate (file read without SizeStatistics) 0.28 MiB
Charge before this change (unmodelled floor) 12.00 MiB

Impact. A 128 MiB bin would accept ~460 of these row groups (~170 GiB decoded) into one read task. (memory_bytes is low by the same factor, though nothing reads it yet at this head.)

Suggestion. Never return less than the unmodelled charge (max(12 MiB, 4 x uncompressed)), or keep the chunk unmodelled when the estimate falls below it.

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.

Without SizeStatistics the footer has nothing that gives string lengths, so this is a guess and it can be low on a column like yours. It's never below the chunk's uncompressed bytes, which is what master budgets on: your file is 0.28 MiB on master and 1.04 MiB here, and the exact 387 MiB when the file has SizeStatistics.

Comment on lines +457 to +461
if unmodelled:
# A leaf or cast the estimator doesn't model, such as a dictionary-encoded
# string with neither SizeStatistics nor a min and max, a view or a struct
# gaining a field.
decoded += _unmodelled_bytes(row_group=row_group, leaf_indices=unmodelled)

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 12 MiB floor leaks into size_bytes, so small row groups over-split

Problem. The unmodelled floor is added to decoded, and decoded becomes size_bytes, which is what the bin packer budgets on. Any row group with one unmodelled leaf now counts as at least 12 MiB of output, however small it really is.

Example. One file, 1,000 row groups of ~1 MiB each, with a list column written without SizeStatistics:

size_bytes per row group Row groups per 128 MiB bin Read tasks
Real decoded size ~1 MiB ~128 ~8
This PR >= 12 MiB 10 100

Impact.

  • Each task outputs ~10 MiB instead of ~128 MiB.
  • With target_max_block_size <= 12 MiB, every row group becomes its own read task.
  • _estimate_batch_size_from_chunk_stats derives its row size from the inflated size_bytes / num_rows.

Suggestion. The floor is a memory-safety margin, so it belongs on the peak (memory_bytes), not on the output size the packer budgets:

decoded_for_packing = decoded                        # no floor -> size_bytes
decoded_for_peak = decoded + _unmodelled_bytes(...)  # floor    -> memory_bytes

Caveat: at this head nothing consumes memory_bytes (see my comment on memory_bytes=peak below), so moving the floor only works once the peak drives task sizing. If that lands in 6/6, an interim option here is to cap the floor relative to the row group, e.g. min(12 MiB, k * uncompressed).

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.

Intentional. When we can't size a leaf I'd rather over-split than over-pack a read task. 12 MiB is arbitrary.

# One Thrift walk per file over the footer bytes ``metadata`` already
# holds -- no extra IO, though ``__reduce__`` re-serializes the
# footer, so skip it when every row group was pruned.
size_stats = read_footer_stats(metadata)

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.

Listing cost per file goes up by up to ~30x, and it is CPU-bound

Problem. For every row group of every file we now run read_footer_stats, _file_sizing and a pure-Python _row_group_sizes. That is CPU work under the GIL, so the footer actor's IO threads don't parallelise it.

Numbers from the PR description (ms per file, 0 ms latency):

Row groups x columns master This PR
20 x 4 0.16 0.98
100 x 10 0.63 10.28
1,000 x 10 3.25 108.24
100 x 100 3.04 99.14

Back-of-envelope. 100,000 files of 100 x 100:

100 ms x 100,000 files = ~10,000 CPU-seconds
/ 8 footer actors (one core each) = ~20 min of listing   (master: ~40 s)

The description also says these numbers were taken before the review changes and not re-run.

Suggestion.

  1. Re-run the benchmark on the current head, plus one large end-to-end listing.
  2. Cut the per-chunk work, e.g. size once per file when row groups share a shape, and only touch chunk.statistics when a dictionary string leaf needs it.

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.

Fixed. Sizing costs about 10 µs of Python per column chunk, so a file with many small row groups cost far more to list than on master. A file with more than 1,000 column chunks now has only its first, middle and last row groups sized; the others take the highest bytes per row and per stored byte of those three, plus 25%. Files at or under 1,000 are sized as before.

Re-run on this head, ms per file, local disk:

Columns x row groups master Before Now
20 x 4 0.12 0.94 0.95
100 x 10 0.77 10.4 10.3
1,000 x 10 6.97 108 40.8
100 x 100 5.64 97.9 8.51

End to end, listing 3,830 files of 100 x 100 from S3 on 8 CPUs: master 15-20 s, before 238 s, now 22 s.

budget = hints.max_bucket_size if hints is not None else None
if not budget or budget >= sys.maxsize:
budget = DEFAULT_TARGET_MAX_BLOCK_SIZE
max_bin_bytes = env_integer("RAY_DATA_PARQUET_BIN_PACKING_BYTES", budget)

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.

nit: existing knobs silently change meaning (uncompressed -> estimated decoded bytes)

These are all compared against FileChunk.size_bytes, which this PR redefines:

  • RAY_DATA_PARQUET_BIN_PACKING_BYTES (here)
  • RAY_DATA_PARQUET_FOOTER_COALESCE_BYTES
  • DataContext.small_shuffle_chunk_size

Example. A job tuned with RAY_DATA_PARQUET_BIN_PACKING_BYTES=134217728 on dictionary-heavy data:

Per read task
Before ~128 MiB uncompressed (several GiB decoded)
After ~128 MiB decoded -> many more read tasks, no warning

Also, the env var still overrides target_max_block_size, so the new "bins follow the block target" behaviour is off for anyone who has it set.

Two places still describe / assume the old unit and aren't in this PR:

# release/release_data_tests.yaml -- the variable appears on 17 lines, tuned for uncompressed bytes
RAY_DATA_PARQUET_BIN_PACKING_BYTES: "1342177280"
RAY_DATA_PARQUET_BIN_PACKING_BYTES: "67108864"
# python/ray/data/context.py:746
small_shuffle_chunk_size: Target uncompressed size in bytes of the row-group
    runs that ``FileShuffleConfig(small_chunks_shuffle=True)`` shuffles.

Suggestion.

  1. Retune or drop the release-test overrides in this PR, otherwise release timings move for reasons unrelated to the code under test.
  2. Update the small_shuffle_chunk_size docstring (public DataContext field) to say decoded size.
  3. Call out the unit change in the env var comments and the PR description.

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.

Updated both docstrings and the env var comment to say decoded bytes. I'll retune the release overrides from a release run on this branch.

Comment on lines +333 to +337
try:
# Cached on the fragment by the footer read.
file_schema: pa.Schema | None = fragment.physical_schema
except Exception:
file_schema = 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.

nit: broad except Exception hides why a file fell back to the unmodelled charge

try:
    file_schema = fragment.physical_schema
except Exception:       # ArrowInvalid, OSError, anything
    file_schema = None  # -> every leaf charged 4x uncompressed / 12 MiB, no trace

Problem. This also swallows IO errors, and with file_schema = None the added-column bytes are dropped too. If a dataset hits this path, the read just has far more tasks and nothing in the logs says why.

Suggestion.

except pa.ArrowException as e:  # only the conversion errors expected here
    logger.debug("Could not build Arrow schema for %s: %s", file.path, e)
    file_schema = 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.

Fixed

return [sum(c["size_bytes"] for c in m.file_chunk_metadatas) for m in manifests]


def test_bins_stay_under_the_budget(tmp_path):

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.

nit: file IO in tests/unit/

python/ray/data/tests/AGENTS.md: "Tests in tests/unit/ follow unit/README.md: no Ray runtime, no file or network IO, no sleeps."

This test and the other new cases write Parquet to tmp_path and run FooterReader over a LocalFileSystem; some use 200,000-row tables. The file already did file IO before this PR, so this extends an existing gap rather than introducing it.

Suggestion. Put the new footer-reader cases in tests/datasource_v2/test_footer_reader.py (already touched by this PR).

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.

Leaving this one: the file wrote Parquet to tmp_path before this PR, as 38 other files under tests/unit/ do, and these cases need a real footer.

Comment on lines +663 to +665
# The listing op's indexer sizes files as they will decode, which can depend on
# the schema; until here it only listed the sample's paths.
indexer = indexer.with_read_schema(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.

Hive-direct reads don't seem to receive the read schema

Problem. Only FooterFileIndexer overrides with_read_schema. _HiveFileIndexer wraps another indexer and inherits the base method, which returns self:

# formats/hive/hive_direct.py
class _HiveFileIndexer(FileIndexer):
    def __init__(self, source, retained):
        self._indexer = source._get_file_indexer()   # e.g. a FooterFileIndexer
    # no with_read_schema -> FileIndexer.with_read_schema returns self

So this line hands back the same wrapper and the inner indexer keeps _read_schema=None.

Impact. For a Hive table over Parquet whose schema widens int32 -> int64, or adds a column older files lack, the estimate skips the cast and the null-filled columns, so size_bytes / memory_bytes come out low.

Suggestion. Forward it in the wrapper:

def with_read_schema(self, schema):
    clone = copy.copy(self)
    clone._indexer = self._indexer.with_read_schema(schema)
    return clone

The PR description says Hive was updated, but the diff has no Hive change. Can you confirm whether this path is covered?

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.

Fixed

# Bins are budgeted on the estimated decoded size, so a read task's output
# stays near ``target_max_block_size``. Without a block target ``read_api``
# passes ``sys.maxsize``, one bin for every file, so that takes the default.
budget = hints.max_bucket_size if hints is not None else 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.

nit: Delta drops hints, so it won't follow the block target

make_row_group_bin_packer now takes its budget from hints, but the Delta caller doesn't pass them:

# formats/delta/delta_datasource_v2.py:253
def get_file_partitioner(self, *, hints=None):
    return make_row_group_bin_packer(self._shuffle_config)   # hints dropped

Example. With ctx.target_max_block_size = 512 MiB:

Bin budget
read_parquet 512 MiB
read_delta over the same files 128 MiB (DEFAULT_TARGET_MAX_BLOCK_SIZE) -> 4x the read tasks

Suggestion. Pass hints=hints there.

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.

Fixed

Comment on lines +49 to +51
def with_read_schema(self, schema: pa.Schema) -> "FileIndexer":
"""An indexer that knows the schema the read casts to; ``self`` if unused."""
return self

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.

nit: Arrow schema on the shared FileIndexer interface

python/ray/data/_internal/datasource_v2/REVIEW.md: "Shared interfaces use only types every format can supply. A signature that needs a Parquet footer, an Arrow schema, or a row-group index belongs on the format, not in interfaces/."

This adds import pyarrow as pa and a pa.Schema parameter to interfaces/. The silent return self default is also what lets a wrapping indexer miss the schema without anyone noticing (see my Hive comment on read_api.py).

Suggestion. Keep the hook on FooterFileIndexer, and either have read_api call it only when the indexer has it, or have the Parquet datasource rebuild its indexer with the schema.

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.

Keeping it on the interface: DataSourceV2.infer_schema and Scanner.read_schema in the same folder already use pa.Schema, and the alternative is read_api special-casing Parquet. The Hive wrapper now forwards it, with a test.

unit_ids=(rg_idx,),
num_rows=row_group.num_rows,
size_bytes=decoded,
memory_bytes=peak,

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.

question: is anything meant to read memory_bytes in this PR?

python/ray/data/_internal/datasource_v2/REVIEW.md: "Read tasks are sized by peak decoded memory, not bytes on disk."

At this head the peak is computed and carried through FileChunk, the packer and coalescing, but no non-test code reads it:

$ git grep -n memory_bytes -- python/ray/data/_internal/datasource_v2
common/online_bin_packer.py          # summed / sliced, never budgeted on
formats/parquet/footer_reader.py     # set here
formats/parquet/parquet_row_group_coalescing.py  # summed
interfaces/file_manifest.py          # field + from_metadata

The packer still budgets on size_bytes only. If 6/6 is what consumes it, a one-line note in the description would help, since this PR pays the full cost of computing the peak during listing (see the listing-cost comment).

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 6/6

goutamvenkat-anyscale added a commit that referenced this pull request Nov 24, 2026
…plies them (#68532)

## Summary
Import each Ray Data `REVIEW.md` from a `CLAUDE.md` in the same
directory, so a local `/code-review` in Claude Code applies the review
rules added in #67928, not only the hosted Code Review.

## Before
The hosted Claude Code Review reads `REVIEW.md` natively. The local
`/code-review` command doesn't: it looks only for `CLAUDE.md` and
`CLAUDE.local.md` on the changed files' ancestor paths. `AGENTS.md` was
applied only because `python/ray/data/.claude/CLAUDE.md` imports it.

Seen on #67840: a local review listed the `REVIEW.md` files but never
read them, and raised nothing from them.

## After
- `python/ray/data/.claude/CLAUDE.md` imports `../REVIEW.md` alongside
`../AGENTS.md`.
- New `.claude/CLAUDE.md` files import `../REVIEW.md` in
`_internal/execution`, `_internal/logical`, `_internal/planner`,
`_internal/datasource`, `_internal/datasource_v2` and `datasource`.

Rerunning the local review of #67840 with these imports, the reviewer
read `python/ray/data/REVIEW.md` and
`_internal/datasource_v2/REVIEW.md`, and raised a finding citing the
`datasource_v2` rule on Arrow schemas in `interfaces/`.

Side effects:
- Interactive Claude Code sessions that work on files in these
directories also load the matching `REVIEW.md` (26–120 lines each) as
context.
- The hosted review may now see the same rules twice, natively and
through `CLAUDE.md`. The content is identical, so this shouldn't change
its findings.

No code or behavior change to Ray Data.

## Subsystems
None at runtime. Agent/review configuration for all Ray Data subsystems.

## Testing
- `pre-commit` hooks ran on commit and passed (trailing whitespace, end
of file, links to master resolve).
- Checked that each `@../REVIEW.md` import resolves to an existing file.
- Manually reran `/code-review` on #67840 with the imports, as described
above.

## Notes
- Not a duplicate: `gh pr list --repo ray-project/ray --state open
--search "REVIEW.md"` returns only #67840, which is unrelated; searches
for "CLAUDE.md data" and "code-review data" found nothing that touches
these files.
- AI assistance (Claude Code) was used for this change and description;
every line was human-reviewed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Goutam <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
…Delta and Hive reads the block target and read schema, and tidy the footer reader's review nits

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Aarrya <[email protected]>

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

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.

2 participants