Skip to content

[Data] Estimate a Parquet row group's decoded Arrow bytes from its footer [2/6] - #67837

Merged
goutamvenkat-anyscale merged 17 commits into
masterfrom
aarrya/decoded-size-2-estimator
Nov 11, 2026
Merged

goutamvenkat-anyscale merged 17 commits into
masterfrom
aarrya/decoded-size-2-estimator

Conversation

@AarryaSaraf

@AarryaSaraf AarryaSaraf commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

Stacked on #67836.

Adds formats/parquet/parquet_decoded_size.py, which estimates the bytes a Parquet row group takes once PyArrow decodes it to Arrow, from the footer alone. Ray sizes a row group today by its uncompressed bytes, which are still dictionary- and RLE-encoded. Nothing calls this module yet, so behavior doesn't change.

The idea: a decoded Arrow column is a few buffers (validity bitmap, offsets, values), and each buffer's size follows from three counts: how many elements the array has, how many are null, and, for strings, how many value bytes there are. The footer records those counts exactly when the writer wrote SizeStatistics. A leaf whose counts it doesn't record exactly isn't estimated: the caller charges it by its uncompressed bytes instead (#67840).

How it works:

  1. Once per file, build_leaf_profiles walks the Arrow schema into one chain of arrays per Parquet leaf: its structs and lists, then the leaf.
  2. Per row group, LeafChunk reads each array's length and nulls from the leaf's level histograms, or, for a top-level leaf, from the footer's null count.
  3. Each array is sized as bitmap plus offsets plus values. A string leaf's value bytes come from SizeStatistics.
  4. estimate_row_group sums over the leaves read, counting a struct or list that several leaves share once.
flowchart TD
    S["Arrow schema"] -->|"walked once per file"| P["Each leaf's chain of arrays"]
    F["Row group footer"] -->|"level histograms, or a top-level leaf's null count"| C["Each array's length and nulls"]
    P -->|"the arrays to count"| C
    C -->|"bitmap, offsets, fixed-width values"| A["Array bytes"]
    F -->|"SizeStatistics"| V["String value bytes"]
    A -->|"shared arrays counted once"| T["Row group estimate"]
    V -->|"added to the string leaf"| T
    F -->|"counts it doesn't record exactly"| U["No estimate: the caller charges the leaf"]
Loading

This is what the dataflow looks like

flowchart TD
    subgraph file ["Once per file"]
        blp["build_leaf_profiles"] --> tas["parquet_schema.to_arrow_schema"]
        blp --> walk["_walk"]
        walk --> visit["visit → _visit_struct / _visit_list / _visit_leaf, recursive"]
        visit --> node["_node"]
        visit --> layout["_leaf_layout"]
        layout --> dst["detect_string_type / _offset_width"]
        layout --> zc["_is_zero_copy_type"]
        visit --> rep["_is_repeated / _is_list"]
        blp --> match["_matches"]
    end

    subgraph rg ["Once per row group"]
        lc["leaf_chunks"] --> chunk["LeafChunk"]
        chunk --> dba["detect_delta_byte_array"]
        chunk --> agree["_histograms_agree"]
        lc --> modelled["modelled"]
        modelled --> known["levels_known"]
    end

    subgraph sum ["The byte sum"]
        erg["estimate_row_group"] --> anc["estimate_ancestors"]
        erg --> leaf["estimate_leaf"]
        leaf --> fw["estimate_fixed_width"]
        leaf --> sb["estimate_string_bytes"]
        sb --> st["estimate_string_type"]
        anc --> ab["_array_bytes"]
        fw --> ab
        st --> bm["bitmap / array_length"]
        ab --> bm
        bm --> hist["_opened / _below / _nulls"]
        bm --> bits["_bytes_for_bits"]
    end

    match --> lc
    modelled --> erg
Loading
  • With SizeStatistics (read by [Data] Read the Parquet SizeStatistics PyArrow doesn't expose [1/6] #67836) every count is exact.
  • Without them, as in files from Spark 3.5 or PyArrow 17, only leaves whose counts the footer still pins down are sized: a non-string leaf at the top level, whose nulls are the footer's null count, or one that can't be null at any level. Every other leaf, including every string and every list element, gets no chunk from leaf_chunks, so the caller charges it.
  • Also left to the caller: views, Arrow dictionary types and unions get no profile, and a string leaf whose SizeStatistics bytes can't be trusted (only parquet-java and arrow-rs are trusted to count DELTA_BYTE_ARRAY values in full; Arrow C++ undercounts them) has no bytes to size. A schema PyArrow can't convert, or the walk can't handle, gives None for the whole file.

Accuracy on a 10,000-file bench, with #67838's handling of the read, is in #67838.

Tests: tests/unit/datasource_v2/test_parquet_decoded_size.py, 48 passed. They compare the estimate with the buffers a real PyArrow scan allocates (get_total_buffer_size), not with a hand-computed formula. Without SizeStatistics, a string and a list column fall back while an int64 beside them stays exact.

Signed-off-by: Aarrya [email protected]

🤖 Generated with Claude Code

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a new module to estimate the decoded Arrow bytes of a Parquet row group from its footer, along with a comprehensive suite of unit tests. The feedback highlights a critical issue in the test suite where a check for PyArrow version 23.0.0 (a non-existent future version) causes several tests to be skipped. It is recommended to dynamically check for feature support (such as string_view) instead of relying on this version check.

Comment on lines +35 to +38
requires_pyarrow_23 = pytest.mark.skipif(
parse_version(pa.__version__) < parse_version("23.0.0"),
reason="PyArrow 17 writes no SizeStatistics or view types",
)

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

The version check 23.0.0 refers to a non-existent future version of PyArrow (as of early 2025, PyArrow is around version 19). This causes all tests decorated with @requires_pyarrow_23 to be skipped in CI and local environments, significantly reducing test coverage. Consider dynamically checking for the required features (e.g., checking if pa.string_view exists or if SizeStatistics is supported), or use the actual minimum version that supports these features (e.g., PyArrow 15.0.0 or 18.0.0).

Suggested change
requires_pyarrow_23 = pytest.mark.skipif(
parse_version(pa.__version__) < parse_version("23.0.0"),
reason="PyArrow 17 writes no SizeStatistics or view types",
)
requires_pyarrow_23 = pytest.mark.skipif(
not hasattr(pa, "string_view"),
reason="PyArrow version does not support view types or SizeStatistics",
)

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.

PyArrow 23 is released and the skip is intended: PyArrow 17 writes no SizeStatistics, and these tests run in the arrow v23 CI jobs.

@AarryaSaraf
AarryaSaraf force-pushed the aarrya/decoded-size-2-estimator branch 2 times, most recently from 2e15e1b to 75794f8 Compare November 4, 2026 23:28
@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Nov 5, 2026
@AarryaSaraf
AarryaSaraf force-pushed the aarrya/decoded-size-2-estimator branch 3 times, most recently from d0961ba to 1102257 Compare November 5, 2026 21:20
@AarryaSaraf
AarryaSaraf force-pushed the aarrya/decoded-size-2-estimator branch from 14dce2b to b10655e Compare November 6, 2026 21:10
Base automatically changed from aarrya/decoded-size-1-parser to master November 9, 2026 22:43
goutamvenkat-anyscale added a commit that referenced this pull request Nov 9, 2026
…67836)

## Description

Adds `formats/parquet/parquet_size_statistics.py`, which reads each
column chunk's `SizeStatistics` from the footer: PyArrow's Python
bindings don't expose them. Later PRs in this stack use them to estimate
a row group's decoded Arrow bytes (#67837) and PyArrow's peak memory
decoding it (#67839). Nothing calls this module yet, so behavior doesn't
change.

How it works: a Parquet footer is one Thrift struct in the compact
protocol, and `FileMetaData.__reduce__()` already returns its raw bytes,
so there is no extra I/O. `_CompactReader` walks from the file to each
row group, then to each column chunk's metadata, and decodes only
`SizeStatistics`. Every Thrift field starts with a type tag that says
how to step over it, so every other field is skipped without knowing
what it holds.

```mermaid
flowchart TD
    M["pq.FileMetaData"] -->|"__reduce__: the raw footer, already in memory"| R["_CompactReader"]
    R -->|"each row group's column chunks"| S["LeafSizeStats: string bytes, level histograms"]
    R -->|"every other field, skipped by its type tag"| X["Not decoded"]
```

**`read_footer_stats(metadata)`** returns a `LeafSizeStats` for each row
group and leaf column: the bytes of a string column's values and its
repetition and definition level histograms (parquet-format 2.10), or
`None` for a chunk whose writer wrote none. It returns `None`, logged,
when the walk fails or the row-group or leaf counts it finds don't match
the footer's, so a footer it can't read never fails the read.

Example: a file with one string column, `["hello", "worldworld", "x"] *
1000`. PyArrow's `ColumnChunkMetaData` has no field for its value bytes.
`read_footer_stats` returns
`LeafSizeStats(unencoded_byte_array_data_bytes=16000,
repetition_level_histogram=(), definition_level_histogram=(0, 3000))`:
16,000 bytes of values and 3,000 non-null slots.

Cost: the walk takes about 7 µs of CPU per column chunk (Apple M5,
Python 3.12, PyArrow 24), so about 7 ms for a footer of 100 row groups ×
10 columns.

Tests: `tests/unit/datasource_v2/test_parquet_size_statistics.py`, 25
passed. Footers PyArrow writes are checked against the values written
(string bytes, nulls, lists); hand-built Thrift payloads pin each skip
width PyArrow footers never exercise; fields of the wrong type, and
truncated or corrupt footers, give `None`.

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]>
AarryaSaraf and others added 13 commits November 9, 2026 14:43
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…coded-size estimate

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
… pages when the null count is wrong

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…e, and test it from one table

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…out changing an estimate

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…eaf's kind from its profile

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…odelled instead of failing the file or guessing

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
AarryaSaraf and others added 2 commits November 9, 2026 14:43
…ounding them

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@goutamvenkat-anyscale
goutamvenkat-anyscale force-pushed the aarrya/decoded-size-2-estimator branch from d3e664e to a04e53d Compare November 9, 2026 22:43
@AarryaSaraf AarryaSaraf added the go add ONLY when ready to merge, run all tests label Nov 9, 2026
@goutamvenkat-anyscale

goutamvenkat-anyscale commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor
flowchart TD
    subgraph file ["Once per file"]
        blp["build_leaf_profiles"] --> tas["parquet_schema.to_arrow_schema"]
        blp --> walk["_walk"]
        walk --> visit["visit, recursive"]
        visit --> node["_node"]
        visit --> layout["_leaf_layout"]
        layout --> dst["detect_string_type / _offset_width"]
        layout --> zc["_is_zero_copy_type"]
        visit --> rep["_is_repeated / _is_list"]
        blp --> match["_matches"]
    end

    subgraph rg ["Once per row group"]
        lc["leaf_chunks"] --> chunk["LeafChunk"]
        chunk --> dba["detect_delta_byte_array"]
        chunk --> agree["_histograms_agree"]
        lc --> modelled["modelled"]
        modelled --> known["levels_known"]
    end

    subgraph sum ["The byte sum"]
        erg["estimate_row_group"] --> anc["estimate_ancestors"]
        erg --> leaf["estimate_leaf"]
        leaf --> fw["estimate_fixed_width"]
        leaf --> sb["estimate_string_bytes"]
        sb --> st["estimate_string_type"]
        anc --> ab["_array_bytes"]
        fw --> ab
        st --> bm["bitmap / slots"]
        ab --> bm
        bm --> hist["_opened / _below / _nulls"]
        bm --> bits["_bitmap_size"]
    end

    match --> lc
    modelled --> erg
Loading

can we include this picture in the description cause it clearly shows the data flow?

self.size_statistics_bytes = None
# Histograms that disagree with the footer mean the walk drifted or the
# writer miscounted (PyArrow 24 with a write_batch_size above the rows).
if stats is not None and not self._histograms_agree(stats=stats):

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.

[med · correctness] size_statistics_bytes is captured from the SizeStatistics blob before _histograms_agree can reject that same blob, so a kept string leaf is sized with bytes the module itself just declared untrustworthy.

Flat nullable string column whose footer SizeStatistics has a definition histogram disagreeing with num_values AND a corrupt unencoded byte count: histograms are dropped at lines 329-330 but self.size_statistics_bytes (set at 322-324) survives; levels are rescued via Statistics.null_count, modelled() stays True, and the leaf is silently mis-sized (probe: estimate 114,899 vs actual 67,764, +69.6%; halved bytes -34.8%). The parallel DELTA_BYTE_ARRAY distrust path (325-326) does clear the bytes, so the asymmetry looks like an oversight; fix is a one-liner clearing size_statistics_bytes on rejection.

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.

Done

return 0
return _bitmap_size(self.slots(node))

def _histograms_agree(self, stats: LeafSizeStats) -> bool:

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.

[med · correctness] _histograms_agree's tripwires (lengths, repetition[0]==num_rows, sums==num_values) are insufficient: a real pyarrow 20-25 writer bug produces sum-preserving definition-histogram corruption that passes the guard and mis-sizes kept leaves, and rep-vs-def inconsistent histograms that pass it can even drive the estimate negative.

Demonstrated two ways. (a) Real writer: pyarrow 20.0.0-25.0.1 (including the 23.0.0 floor; clean on 26) with write_batch_size above a ~20k-value page boundary writes def=(7142,42858) where truth is (7143,42857) — sums match, guard passes, and a flat column whose single null sits at the boundary slot is kept and mis-sized (bool leaf 50% under; string leaf missing its 6,250-byte bitmap). The comment at line 328 blames only 'PyArrow 24'. (b) Synthetic: rep=(num_rows,0,rest) with all definition mass at level 1 passes every check yet makes an intermediate node's slots() negative — estimate_row_group returned -39,192 for a kept list<list> leaf; no >=0 clamp exists anywhere. Cheap fixes: cross-check def-implied null count against Statistics.null_count (correct in the same corrupted footers), bound def/rep against each other, and clamp slots/estimates at 0.

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.

Clamped the array length at 0 and took the PyArrow 24 mention out of the comment. Didn't add the Statistics.null_count cross-check: building Statistics costs about two thirds of an estimate, and every leaf would pay it.

# Arrow C++ writers leave out of a DELTA_BYTE_ARRAY chunk's count each value
# equal to, or a prefix of, the one before: 1,000 copies of an 8-byte string
# report 8 bytes, where arrow-rs reports 8,000.
counts_delta = writer != "" and not writer.startswith("parquet-cpp")

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.

[med · correctness] DELTA_BYTE_ARRAY byte-count trust is a fail-open deny-list — every writer whose created_by doesn't start with 'parquet-cpp' is trusted to have counted unencoded bytes fully, and the sniff is version-blind.

parquet.thrift defines unencoded_byte_array_data_bytes as plain-encoded size, but Arrow C++ undercounts prefix-compressed values (probe: 1,024 reported vs 10,240,000 true). Any unlisted writer sharing that misreading — or a wrapper embedding Arrow C++ under its own created_by ('MyETL 2.0') — is trusted: probe showed a kept string leaf estimated at 41,028 vs 10,280,004 actual, a 251x underestimate in the OOM direction with no fallback signal. Also, when Arrow C++ fixes the bug, 'parquet-cpp*' files stay distrusted forever. An allow-list of verified full-counting writers (parquet-mr/parquet-java 1.14+, parquet-rs/arrow-rs 53+) fails closed instead.

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.

Switched to an allow-list: only parquet-mr (parquet-java) and parquet-rs (arrow-rs), which both count each value's full length. No version check needed, since their versions before 1.14 and 53 write no SizeStatistics.

for leaf_idx in leaf_indices
if (profile := leaf_profiles[leaf_idx]) is not None
]
return [leaf for leaf in chunks if leaf.modelled()]

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.

[low · api-design] leaf_chunks communicates unmodelled leaves as silent absence from a filtered list, an API shape every real consumer immediately converts to a dict and length-reconciles, and that admits silent undercount if any caller forgets.

Downstream (stacked branches 4/6) each rebuild {leaf.index: leaf for leaf in chunks}, derive modelled = len(chunks) == len(leaf_indices), and repeat the length comparison a second time for cast columns; branch 4's estimate_cast feeds filtered lists straight into estimate_row_group, which sums partial leaves and is only correct because a remote call site re-checks lengths. A future caller summing without reconciling gets 0 bytes for every dropped text/list column. The filtered list also carries estimate_string_bytes' hidden precondition (assert at line 528, valid only post-filter). Returning dict[int, LeafChunk] (or a leaf_indices-aligned list of LeafChunk | None) makes fallback a visible value.

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.

Done

The profiles, or ``None`` for a file this module doesn't model at all.
"""
try:
arrow_schema = parquet_schema.to_arrow_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.

[low · robustness] build_leaf_profiles' try/except covers only to_arrow_schema(); the _walk and matching loop are unguarded and _leaf_layout catches only ValueError from bit_width, so a future pyarrow exception type crashes read planning instead of falling back.

On pyarrow 23 every non-fixed-width type raises plain ValueError (latent today), but a stub whose bit_width raises TypeError escapes build_leaf_profiles, and downstream wiring (branches 5/6 footer_reader) calls it bare inside the FooterReader actor, failing the whole read for a file the module was designed to merely skip. Ray CI runs a pyarrow-nightly lane where new types/exception classes land first. The sibling parquet_size_statistics.read_footer_stats wraps everything fail-open; widening the try to cover _walk + the loop (or except Exception: return None) matches the stack's own design.

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.

Done

**fields,
)

def visit(

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.

separate the visit method into _visit_struct, _visit_list etc. to make the handling of each type clear

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.

Done

)


def _walk(arrow_schema: pa.Schema) -> _SchemaWalk:

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.

Let's add a clear parameterized unit test for this function and assert on the leaves

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.

Done

Comment on lines +26 to +28
pa = pytest.importorskip("pyarrow")
pds = pytest.importorskip("pyarrow.dataset")
pq = pytest.importorskip("pyarrow.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.

Why are we skipping these?

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.

Done

Comment on lines +416 to +418
def _bitmap_size(length: int) -> int:
return (length + 7) // 8

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.

Let's rename this function to represent something like minimum_number_of_bytes_to_represent_length

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.

or nbytes etc.

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.

Renamed to _bytes_for_bits, since it also sizes boolean values, not just bitmaps.

)
return repetition and definition

def slots(self, node: _ArrowNode | None = None) -> int:

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.

slots is ambiguous, let's use array_length

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.

Done

@AarryaSaraf

Copy link
Copy Markdown
Contributor Author

It's in the description now.

…as no dictionary page and no SizeStatistics

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit f1bddd3 into master Nov 11, 2026
6 checks passed
@goutamvenkat-anyscale
goutamvenkat-anyscale deleted the aarrya/decoded-size-2-estimator branch November 11, 2026 08:59
goutamvenkat-anyscale added a commit that referenced this pull request Nov 13, 2026
…coded-size estimate [3/6] (#67838)

## Description

Follows #67837, which is merged.

Extends the estimator with what a Ray read does beyond PyArrow's decode,
and splits it from one file into the package
`formats/parquet/decoded_size/` (`arrow_layout`, `schema_walk`,
`schema_pin`, `footer_counts`, `added_columns`, `estimate`; `__init__`
re-exports the public names). The split is its own commit and only moves
code. Nothing calls the estimator yet, so behavior doesn't change.

A Ray read returns different arrays than the file stores: when the
dataset schema is pinned, Ray casts every batch to it, and Ray appends
columns such as `path`. Rather than size the cast on its own, the
estimate walks the schema the read returns, so #67837's per-array sizing
applies unchanged.

```mermaid
flowchart TD
    A["File's Arrow schema"] -->|"no pinned schema"| W["Schema walked"]
    D["Pinned dataset schema"] -->|"columns the cast maps leaf for leaf"| W
    D -->|"columns whose shape the cast changes"| U["Not modelled"]
    K["binary_type, list_type"] -->|"the whole file"| U
    C["dictionary_columns"] -->|"the BYTE_ARRAY columns it names"| U
    W -->|"#67837's per-array sizing"| L["Leaf bytes"]
    R["Columns Ray adds"] -->|"added_bytes, per row"| T["Row group estimate"]
    L -->|"summed"| T
```

- `build_leaf_profiles` gains `pinned_schema` and `format_kwargs`.
`pinned_schema` is the schema the reader casts every batch to
(`FileReader._file_dataset_schema`), not the dataset schema.
- A pinned column whose leaves the cast keeps one for one is walked at
its pinned type (`_pinned_walk`, `pinned_type`): an `int32` column
pinned to `int64` counts 8 bytes a value.
- Whether a column without nulls keeps its validity bitmap depends on
the cast (`_cast_keeps_bitmap`, measured on PyArrow 23 to 26): `int32`
pinned to `date32` keeps it, `int32` pinned to `int64` drops it.
- A cast that changes a column's shape (a struct gaining a field, a
nested field made nullable, numbers cast to text) leaves that column's
leaves unmodelled, for the caller to charge.
- A read with `binary_type` or `list_type` isn't modelled.
`dictionary_columns` leaves only the BYTE_ARRAY columns it names
unmodelled. The reader drops these options when it casts to the schema
(#67840).
- `estimate_row_group` takes a `Read`, the bytes per row and per row
group of the columns Ray appends (`added_bytes`,
`estimate_added_columns`): `path`, the file's partition values as the
reader parses them (`{"year": "2024"}` gives `year` 4 bytes a row), and
a dataset column the file lacks or holds as a null-typed column, which
the cast fills with nulls.

Accuracy, measured before the review changes and not re-run since: a
bench wrote 10,000 files from 100 fixed random seeds, drawing the writer
(PyArrow, Polars or arrow-rs), column types, encodings, compression,
row-group sizes, read options and pinned schemas at random, and measured
the bytes PyArrow holds for each row group a Ray read decodes. The bench
over-weights what the estimate leaves unmodelled (26% of reads use a
type option, 9% `dictionary_columns`, 13% of the files come from Polars,
which writes no `SizeStatistics`, and the bench strips parts of them at
random, from 58% of the row groups), so it models 30,160 of 148,039 row
groups (20%).

| Estimate ÷ PyArrow's bytes | Today: uncompressed bytes, all row groups
| This estimate, row groups it models |
|---|---|---|
| < 0.95 | 76.1% | 0 |
| 0.95–1.1 | 11.5% | 99.2% |
| median / p90 / p99 | 0.68× / 1.19× / 4.94× | 1.00× / 1.00× / 1.06× |

Tests: `tests/unit/datasource_v2/test_parquet_decoded_size.py`, 79
passed on Python 3.10 with PyArrow 23.0.0 and 25.0.1 and on Python 3.12
with PyArrow 26.0.1. New cases: eleven pinned casts, each with and
without nulls, match what a scan under the pinned schema holds;
`binary_type` leaves the file unmodelled and `dictionary_columns` only
the columns it names; a stored dictionary column is unmodelled; a text
pin over a non-text column is unmodelled; and the added columns (`path`,
a string, a dictionary and a null partition value, a null-filled column)
are within 5% of what PyArrow holds.

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]>
eugenepaniot added a commit to eugenepaniot/ray that referenced this pull request Nov 19, 2026
…floop-input

* upstream/master:
  [Data][3/n] update progress bar on lineage reconstruction (ray-project#67366)
  [Data] Enable the Top-N rewrite by default and expose it on DataContext (ray-project#68329)
  [Data] Adaptively skip map-side partial aggregation for high-cardinality keys (ray-project#68118)
  [Core] Spawn specific servers without preexec_fn to fix intermittent startup crashes (ray-project#67947)
  [Serve] Stop the __wrapped__ walk at non-callables (ray-project#67117)
  [Data] Deflake test_read_parquet_v2 by cutting redundant Ray Data executions (ray-project#68318)
  [Data] Retry FooterReader actor deaths with Ray Core and yield footers in listing order (ray-project#67988)
  [Data] Fix order-dependent schema unification when a list<null> arm is present (ray-project#68259)
  [Serve] Make @serve.batch work when wrapped in another decorator (ray-project#68177)
  [serve] Deflake test_metrics_3 - record the batch queue length once a batch is taken (ray-project#68302)
  [serve] Drop completed requests from the multiplexed model ID index (ray-project#68085)
  [Data] Fix flaky test_hudi: read each table once instead of sorting in Ray Data, keep size small (ray-project#68162)
  [Data] Fix flaky test_context: start 2 Ray clusters instead of 5 and keep size small (ray-project#68161)
  [Data] Fix flaky test_kafka: use recent timestamps in test_read_kafka_datetime_partial_range (ray-project#68248)
  [Data] Iceberg DSv2 [2/5]: The listing-to-reading manifest for Iceberg (ray-project#67951)
  [Train] Report training errors when the post-mortem debugger raises a BaseException (ray-project#68317)
  [RLlib] Skip the PPOConfig docstring example that crashes the rllib doctest target (ray-project#68306)
  [Train] Support post-mortem debugging for training function errors (ray-project#68296)
  [train][1/n] Give each health probe its own timeout (ray-project#68191)
  [Data] Fix unifying a fixed-shape tensor array with a lower-ndim variable-shaped one (ray-project#67266)
  [Train] Add a guide to debugging failures and hangs (ray-project#68299)
  [Data] Persist BlockMetadata.num_rows and batch ray.get in _calculate_blocks_rows (ray-project#67662)
  [Data] Vectorize LeRobot delta segment preparation and validate index contiguity (ray-project#67845)
  [Data] Avoid full-DataFrame apply in _AbstractKBinsDiscretizer._transform_pandas (ray-project#67862)
  [doc] Refresh intersphinx inventory snapshots (ray-project#68303)
  [Data] Fix SimpleImputer on categorical columns in append mode and with existing category values (ray-project#67467)
  [Data] Replace O(N) list.pop(0) with deque.popleft() in PushBasedShuffleTaskScheduler (ray-project#67243)
  [Train] Reject an elastic ScalingConfig with max_workers=0 (ray-project#68218)
  [core][move semantics][3/n]Populate task args with is_move for movable refs (ray-project#66803)
  [core][sandbox] Remove the readonly option (ray-project#68088)
  [Data](1/n) Implement the line-chunk reader for CSV and JSONL on DataSource V2 (ray-project#67907)
  [Data] Set MIMALLOC_PURGE_DELAY=0 on random_shuffle to fix the pyarrow 25 OOM regression (ray-project#68151)
  [core] Quote each `uv run` argument in the uv runtime env hook (ray-project#68156)
  [core] Don't let gRPC cancel calls that wait over 30s in the server queue (ray-project#68210)
  [Data] Fix shuffle and join on native tensor columns with pyarrow 25+ (ray-project#68072)
  [serve][llm] Remove decode load progress (ray-project#68258)
  [ci] Bump sglang to 0.5.23 in release tests (ray-project#68250)
  [Core] Build the test auth token file locally so Windows tests can read it (ray-project#68262)
  [image] Bump EFA installer to 1.51.0 in CPU base-extra images (ray-project#67730)
  [serve] Observe the result of rank reassignment reconfigures (ray-project#67923)
  [Serve][Docs] Explain imperative vs declarative deploys and in-place updates from Python (ray-project#68243)
  [Data] (Fault tolerance) Ray Data lineage reconstruction docs (ray-project#68061)
  [RLlib] Add a multi-node footsies APPO memory release test (ray-project#67595)
  [Train] Remove local mode (ray-project#68239)
  [Data] Fix filtered Lance row-count metadata (ray-project#67228)
  [Serve][2/2] Propagate TracingConfig to proxies at startup (ray-project#65437)
  [Data] Fix synthesized path filtering in DataSourceV2 (ray-project#67079)
  [RLlib] Run the BCConfig Tune example one trial at a time to unblock the rllib doctest target (ray-project#68242)
  [Data][Delta DSv2][2/7] List Delta Lake table files from the log (ray-project#67888)
  [Data] Parallelize Parquet and ORC full-schema reads (ray-project#67542)
  [Data] Random Shuffle on Shuffle V2 Map/Reduce Operators (ray-project#68004)
  [Data] Propagate metadata prefetch thread failures to executor (ray-project#68171)
  [core] Send generator consumed-progress updates from io_service_ (ray-project#67160)
  [Data] Add @ray-data-connectors as codeowner for datasource/sinks files (ray-project#68154)
  [data][llm] Keep the prompt in vLLM error rows (ray-project#67665)
  [data][actor-only][3/n] Actor-only backend: operator fusion (ray-project#67699)
  [Data] Read text files on DataSource v2 (ray-project#68063)
  [Autoscaler][KubeRay] Never patch worker group replicas below minReplicas (ray-project#67332)
  [Serve] Show progress of updating (ray-project#67107)
  [core][test] Trigger usage-stats OOM test without exhausting host memory (ray-project#68009)
  [Serve] Remove unused RAY_SERVE_HAPROXY_INGRESS_RETRY_ON and RAY_SERV… (ray-project#68175)
  [Data] Implement lineage tracker garbage collection upon marking operator durable (ray-project#67788)
  [Core] Fix recovery suppression race in ObjectRecoveryManager (ray-project#64974)
  [serve] Pass grpc.so_reuseport to gRPC as an integer (ray-project#66816)
  [Autoscaler][v2] Preserve retry accounting when trimming status history (ray-project#67360)
  [doc] Refresh intersphinx inventory snapshots (ray-project#68069)
  [Doc] Add item to AGENTS.md to update documentation when modifying API-facing code. (ray-project#68204)
  [Train] Preserve `num_boost_round=0` and avoid mutating `callbacks` in legacy LightGBM/XGBoost trainers (ray-project#68145)
  [Train] Raise in prepare_data_loader instead of dropping a custom batch_sampler (ray-project#68201)
  [air] Return None in skip_exceptions when exc or StartTraceback cause is None (ray-project#68172)
  [Train] Fix `checkpoint_manager` to support metrics only reported in a validation function (ray-project#67909)
  [Train] Count elastic workers in resource units for fractional resources (ray-project#68139)
  [Data] Refactor Disk shuffle map to use map Operator (ray-project#67130)
  [core][move semantics][2/n] Change state to moved on consumption and add enforcements (ray-project#66767)
  [Data] Propagate labels to object-store SHUFFLE_V2 map/reduce tasks (ray-project#67135)
  feat(core): add Cambricon MLU resource support (ray-project#66368)
  [Data] Make `zero_copy_batch=False` copy default batches (ray-project#67154)
  [data] Fix Parquet filename suffix detection (ray-project#67156)
  [data] Fix docstring/behavior mismatches in read_json and Dataset.sort (ray-project#66927)
  [Data] Run video_object_detection.ray on T4s with more memory (ray-project#68149)
  [core][sandbox] Let a node override network="public" sandboxes' default resolvers (ray-project#67691)
  [Data] read_mcap: resolve each sample's steps and lay out its row (ray-project#67925)
  [Data] read_mcap: sample read inputs: TopicSpec, steps, match and samples checks (ray-project#67924)
  [Data] Keep a map task's buffered rows when max_errored_blocks skips its error; read past corrupt MCAP chunks (ray-project#67167)
  [core][move semantics][1/n] Adding consume_once flag in actor methods (ray-project#66620)
  [Data] Size the schema pin and the columns Ray adds in the Parquet decoded-size estimate [3/6] (ray-project#67838)
  [Serve][LLM][1/3] Token based autoscaling: track autoscaling workload in KV router (ray-project#67937)
  [Data] Add native direct reads for nonpartitioned Hive tables (ray-project#67114)
  [Train] Count elastic workers in resource units for fractional resources (ray-project#68139)
  [Data] Add `condition` to `Dataset.join` and extract equi-join keys from it (ray-project#67590)
  [data] Add Top-N execution (ray-project#66931)
  [build] Bazel 8.8.1: bump protobuf to v29.6, rules_java to 8.12.0 and gRPC to 1.69.0 (ray-project#66483)
  [build] Use Arena::Create and pin Java 8 bytecode ahead of protobuf 29 / rules_java 8 (ray-project#67720)
  [core][sandbox] Don't join a sandbox's cgroup on every exec (ray-project#67690)
  [Data] Run `training_ingest_regression_test` on Instances that can be Provisioned (ray-project#68110)
  [Data] Run Sort on Disk-based Shuffle under SHUFFLE_V2 (ray-project#67850)
  [core] Deflake tests that race on timing (ray-project#67717)
  [ci] Bump pypa manylinux2014 base image to 2026.10.22-0 for CPython 3.15 (ray-project#67285)
  [Data] Make Mcap Data Column Test Insensitive to Struct Field Order (ray-project#68109)
  [Data] read_mcap V2: cut large files where their log-time order holds (ray-project#67166)
  [core][sandbox] Commit sandbox as new registry image (ray-project#67972)
  [Data] read_mcap V2: read neighbouring chunks in one ranged request (ray-project#67930)
  [train][4/n] Wire WorkerProbes through the HealthManager (ray-project#67915)
  [train][3/n] Add WorkerProbe results and health reports to the HealthState (ray-project#67879)
  [Data] (Data fault tolerance ray-project#6/6) Add a manual release test for lineage reconstruction (ray-project#67519)
  [train][6/n] Act on health decisions in the Ray Train controller (ray-project#67856)
  [Train] Do not start an elastic worker group with zero workers (ray-project#68101)
  [Train] Keep the last checkpoint after a metrics-only report in local mode (ray-project#68070)
  [Data][2/n] Migrate GPU Shuffle to Unified Phase Metrics (ray-project#67359)
  [Data][Chkpt] Fix `ArrowInvalid` when loading large generated-ID checkpoints (ray-project#68065)
  [core][test] Create auth token in test_redis_wrong_password (ray-project#68014)
  [data][actor-only][2/n] Actor-only backend: promote task pools to actor pools (ray-project#67698)
  [Data] Fix typing mismatches in Dataset public API (ray-project#62077)
  [Data] read_mcap V2: carry read tasks' summary records in the manifest (ray-project#67929)
  [Data] Distinguish generated ID collisions with synthesized columns (ray-project#67164)
  [Data] Fix incorrect scale-up in rate-based autoscaler for custom resources (ray-project#66647)
  [Data][Delta DSv2][1/7] Shared Parquet and partitioning fixes for the Delta reader (ray-project#67887)
  [Data] Eliminate redundant aggregation shuffle (ray-project#67198)
  [Data] Raise minimum supported pyarrow to 23.0.0 and test up to 26.0.1 (ray-project#68005)
  [Train] Use the default validation timeout when a report's ValidationTaskConfig has none (ray-project#68045)
  [doc][train] Use the global batch size in the TensorFlow Train examples (ray-project#68006)
  [TPU] Default multi-slice MASTER_ADDR to slice 0 host 0 in SlicePlacementGroup (ray-project#67878)
  [Data] Estimate a Parquet row group's decoded Arrow bytes from its footer [2/6] (ray-project#67837)
  [Data] Predicate pushdown through joins: split conjuncts, derive one-sided OR weakenings (ray-project#67122)
  [Data] Add partition_filters to read_delta and take file sizes from the log (ray-project#67900)
  [Data] Stop writing Unity Catalog vended credentials to the environment (ray-project#67899)
  [Data] Raise an error for Delta tables with column mapping in write_delta (ray-project#67898)
  [Core] Add initial foundational configurations and flags for fork server (ray-project#67356)
  [core][sandbox] Image layers caching (ray-project#67874)
  [Doc][Train] Add device stream batch prefetching section to accelerator guide (ray-project#67779)
  [Train] Use user-defined train function name in training thread name and error stack traces (ray-project#64292)
  [serve][docs] Remove beta label from custom autoscaling policies (ray-project#68046)
  [core] Don't treat a gRPC client with calls in flight as idle (ray-project#67718)
  [train] Fix checkpoint sorting to support nested metrics (ray-project#59130)
  [train][5/n] Run ControllerProbes on the controller's node monitor (ray-project#67671)
  [Train] Rank a checkpoint without the score attribute as worst in min order (ray-project#67901)
  [Core][RuntimeEnv] Stream runtime environment package downloads (ray-project#67184)
  [core] Deflake `_run_hanging_command` tests (ray-project#67461)
  [Data] Add Gravitino Iceberg REST catalog provider (ray-project#67007)
  [Data] Fix mixed-root partition filtering in Parquet and ORC V2 (ray-project#67067)
  [core] Keep absl logging at ERROR unless GRPC_VERBOSITY is set (ray-project#67719)
  [Data][1/n]Add Shuffle Metrics Unification Instrumentation (ray-project#66968)
  [ci][release] Stop publishing Python 3.10 wheels and images (ray-project#67722)
  [serve] Copy the ASGI lifespan state into each request scope (ray-project#67844)
  [Serve][LLM][4/5] Support scale-to-zero application routing (ray-project#67087)
  [core][sandbox] Let GPU sandboxes request NVIDIA profiling capabilities (ray-project#67974)
  [Serve][LLM] Exclude LLMRouter from dashboard QPS (ray-project#67873)
  [Data] Read the Parquet SizeStatistics PyArrow doesn't expose [1/6] (ray-project#67836)
  Add perf metrics for 2.60.0 (ray-project#67727)
  [Observability / Train] Add Grafana Annotation support with Ray Train usage (ray-project#66958)

Signed-off-by: Eugene Paniot <[email protected]>

# Conflicts:
#	python/ray/data/_internal/planner/plan_udf_map_op.py
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]>
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