Skip to content

[Data] Estimate PyArrow's peak memory decoding a Parquet row group from its footer [4/6] - #67839

Merged
goutamvenkat-anyscale merged 126 commits into
masterfrom
aarrya/decoded-size-4-peak
Nov 24, 2026
Merged

goutamvenkat-anyscale merged 126 commits into
masterfrom
aarrya/decoded-size-4-peak

Conversation

@AarryaSaraf

@AarryaSaraf AarryaSaraf commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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

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
Loading

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 ([Data] Estimate a Parquet row group's decoded Arrow bytes from its footer [2/6] #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): [Data] Size the schema pin and the columns Ray adds in the Parquet decoded-size estimate [3/6] #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

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 introduces a new module, parquet_decode_peak.py, along with its corresponding unit tests, to estimate PyArrow's peak memory usage when decoding a Parquet row group from its footer. The feedback highlights several opportunities to make the implementation more robust by defensively guarding against potential IndexError, KeyError, and ValueError exceptions when accessing row group columns, leaf indices, and schema fields.

Comment on lines +74 to +91
def estimate_row_group_peak(
row_group: RowGroupMetaData,
leaf_indices: Sequence[int],
row_group_work: int,
file_size: int,
) -> int:
"""PyArrow's peak bytes reading ``row_group``, given its work and cast."""
if file_size < _SMALL_FILE_BYTES:
# The footer read took the whole file, which stands in for the footer
# and the chunks. 512 bytes and 256 a leaf are the least slack over the
# file's size that covered the measured peaks; without it, 5 to 10 row
# groups fell under the floor.
return file_size + 512 + 256 * len(leaf_indices) + row_group_work
# The footer read and gaps, plus the chunks pre_buffer holds compressed.
compressed = sum(
row_group.column(leaf_idx).total_compressed_size for leaf_idx in leaf_indices
)
return _FOOTER_BYTES + compressed + row_group_work

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

To prevent potential IndexError crashes when leaf_indices contains out-of-bounds indices (e.g., due to added or virtual columns), we should filter the indices to ensure they are within the valid range of row_group.num_columns.

def estimate_row_group_peak(
    row_group: RowGroupMetaData,
    leaf_indices: Sequence[int],
    row_group_work: int,
    file_size: int,
) -> int:
    """PyArrow's peak bytes reading ``row_group``, given its work and cast."""
    valid_leaf_indices = [
        idx for idx in leaf_indices if 0 <= idx < row_group.num_columns
    ]
    if file_size < _SMALL_FILE_BYTES:
        # The footer read took the whole file, which stands in for the footer
        # and the chunks. 512 bytes and 256 a leaf are the least slack over the
        # file's size that covered the measured peaks; without it, 5 to 10 row
        # groups fell under the floor.
        return file_size + 512 + 256 * len(valid_leaf_indices) + row_group_work
    # The footer read and gaps, plus the chunks pre_buffer holds compressed.
    compressed = sum(
        row_group.column(leaf_idx).total_compressed_size for leaf_idx in valid_leaf_indices
    )
    return _FOOTER_BYTES + compressed + row_group_work

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.

leaf_indices comes from enumerating the file's own Parquet columns, so every index is in range.

Comment on lines +110 to +133
for position, leaf_indices in enumerate(column_leaves):
# PyArrow 24 reserves the k-th column's leaves for as many slots as the
# file's k-th *leaf* has values, whichever column that leaf is in.
reserved = row_group.column(position).num_values
# A column's leaves decode in turn: its peak is one leaf's temporaries
# on top of what that leaf and the leaves before it keep.
column_kept = column_peak = 0
for leaf_idx in leaf_indices:
leaf = leaves[leaf_idx]
ancestors = estimate_ancestors(leaf=leaf, counted=counted)
# Without the footer's page counts, a leaf is taken as one page.
leaf_kept, leaf_temporary = estimate_leaf_work(
leaf=leaf,
column=columns[leaf_idx],
reserved=reserved,
rows=row_group.num_rows,
read=read,
ancestors=ancestors,
pages=data_pages[leaf_idx] if data_pages else None,
)
column_kept += ancestors + leaf_kept
column_peak = max(column_peak, column_kept + leaf_temporary)
kept += column_kept
temporaries.append(column_peak - column_kept)

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

Defensively guard against IndexError and KeyError when accessing row_group.column(position), leaves[leaf_idx], columns[leaf_idx], or data_pages[leaf_idx]. If position is out of bounds (e.g., for columns not present in the file), we should default reserved to row_group.num_rows.

    for position, leaf_indices in enumerate(column_leaves):
        # PyArrow 24 reserves the k-th column's leaves for as many slots as the
        # file's k-th *leaf* has values, whichever column that leaf is in.
        if position < row_group.num_columns:
            reserved = row_group.column(position).num_values
        else:
            reserved = row_group.num_rows
        # A column's leaves decode in turn: its peak is one leaf's temporaries
        # on top of what that leaf and the leaves before it keep.
        column_kept = column_peak = 0
        for leaf_idx in leaf_indices:
            leaf = leaves.get(leaf_idx)
            if leaf is None:
                continue
            if leaf_idx >= len(columns):
                continue
            ancestors = estimate_ancestors(leaf=leaf, counted=counted)
            # Without the footer's page counts, a leaf is taken as one page.
            leaf_kept, leaf_temporary = estimate_leaf_work(
                leaf=leaf,
                column=columns[leaf_idx],
                reserved=reserved,
                rows=row_group.num_rows,
                read=read,
                ancestors=ancestors,
                pages=data_pages[leaf_idx] if data_pages and leaf_idx < len(data_pages) else None,
            )
            column_kept += ancestors + leaf_kept
            column_peak = max(column_peak, column_kept + leaf_temporary)
        kept += column_kept
        temporaries.append(column_peak - column_kept)

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.

Each position is a column the file has, with at least one leaf of its own, so it stays below the leaf count.

Comment on lines +291 to +295
for name, leaves in column_leaves.items():
before, after = file_schema.field(name).type, pinned_schema.field(name).type
if before == after:
# A column the pin leaves as it is isn't cast.
continue

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

Avoid potential KeyError or ValueError when calling file_schema.field(name) or pinned_schema.field(name) for columns that are not present in both schemas (e.g., added columns or columns excluded from the read). Using get_field_index is safer and more efficient.

    for name, leaves in column_leaves.items():
        before_idx = file_schema.get_field_index(name)
        after_idx = pinned_schema.get_field_index(name)
        if before_idx < 0 or after_idx < 0:
            continue
        before, after = file_schema.field(before_idx).type, pinned_schema.field(after_idx).type
        if before == after:
            # A column the pin leaves as it is isn't cast.
            continue

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 caller, _file_sizing in #67840, only passes columns present in both schemas with different types.

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

…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-4-peak branch from d6e4129 to 4f52815 Compare November 4, 2026 22:36
…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-4-peak branch from 4f52815 to 874b75d Compare November 4, 2026 23:28
@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-4-peak branch from 874b75d to 35d9937 Compare November 5, 2026 02:06
…ompact reader builds on Windows

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@AarryaSaraf
AarryaSaraf force-pushed the aarrya/decoded-size-4-peak branch from 35d9937 to e7ba827 Compare November 5, 2026 03:46
AarryaSaraf and others added 13 commits November 10, 2026 17:46
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…mate's pinned walk

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Aarrya <[email protected]>
… drop its tests' dead PyArrow 23 guards

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
… cast estimate an empty Read

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…e columns Ray adds

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Base automatically changed from aarrya/decoded-size-3-ray-read to master November 13, 2026 23:07
Comment on lines -16 to -18
from ray.data._internal.datasource_v2.formats.parquet.decoded_size.arrow_layout import (
detect_string_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.

Why are these being nuked?

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.

They aren't imported later on like I originally thought they might be, so I dropped the re-exports. The functions themselves are still in their modules.


# PyArrow reads a file's last 64 KiB for its footer, and pre_buffer coalesces
# chunks across gaps of up to 8 KiB; one gap measured short, two cover it.
_FOOTER_BYTES = 80 << 10

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 allows a fixed two 8 KiB pre_buffer gaps, but Arrow's read coalescing (CacheOptions defaults: hole_size_limit 8 KiB, range_size_limit 32 MiB) merges every gap of 8 KiB or less between requested chunks into one range. On a projected read of a wide file, the unread chunks between the read ones get fetched and cached too.

For example, 1,000 INT64 columns with 1,000-row row groups (~6 KiB chunks), reading every other column: the ~499 skipped chunks in between (~3 MiB) are read along with the ~3 MiB requested, but the estimate only charges compressed + 80 KiB. That's on the OOM side. Could estimate_row_group_peak compute the merged-gap bytes from the read and unread leaves' offsets and total_compressed_size, using the 8 KiB / 32 MiB limits?

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. I added an 8 KiB bound per gap instead of computing the gaps from the offsets, for complexity reasons.

unpinned leaves modelled; ``counted`` the ancestors sized."""
decoded, buffers = 0, []
for position, leaf_indices in enumerate(column_leaves):
# PyArrow 24 reserves the k-th column's leaves for as many slots as the

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 rule (and others, like reserved > rows deciding whether reader bytes are kept or temporary, and kept vs. temporary for the zero-copy hand-off) encodes PyArrow 24 internals, but nothing checks the version. setup.py allows pyarrow >= 23.0.0 and requirements_compiled.txt pins 25.0.1. If 25/26 change any of these, production estimates drift without any signal, possibly low, and the test's 0.95-1.5x band on allocator internals may also fail on versions other than the one it was tuned on.

Which PyArrow version did the bench numbers and the 6 passing tests run on? It'd be good to either check the version (with a conservative fallback) or confirm the test passes on 23 and 25.

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.

It was built and benchmarked on PyArrow 24. I briefly checked 23 through 26 and saw approximately the same results everywhere. Dealing with each version separately would be a nightmare, so I haven't added a version check.

return 0
# The bytes before the first data page at the chunk's ratio, never below
# them, since a page that doesn't compress is stored as is.
gap = chunk.data_page_offset - (chunk.dictionary_page_offset or 0)

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.

Two ways this can come out low:

  1. Scaling the dictionary page's compressed bytes by the whole chunk's ratio understates a dictionary that compresses much better than its index pages. E.g. an INT64/DOUBLE chunk with a 1 MiB plain dictionary compressed 4x (256 KiB) next to 1 MiB of index pages at ~1.1x: the chunk ratio is ~1.6, so ~410 KiB is charged instead of 1 MiB. The +16 B per entry covers this for strings, but not for fixed-width columns.
  2. L216 returns 0 when has_dictionary_page is False, even if encodings includes PLAIN_DICTIONARY/RLE_DICTIONARY. Some writers leave dictionary_page_offset unset, and PyArrow still decodes the dictionary page it finds at data_page_offset. Falling through to the 2 MiB-capped branch in that case seems safer.

@AarryaSaraf AarryaSaraf Nov 16, 2026 •

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.

(1) Fixed. A sorted int64 column with every value distinct came out 6% low. The page is now bounded by its compressed bytes plus what the whole chunk saved compressing, up to 2 MiB. Added that column as a test case.

(2) Fixed: a chunk with a dictionary encoding but no dictionary page offset now takes the 2 MiB-capped branch, with a test.

columns: Sequence[ColumnSchema],
column_leaves: Sequence[Sequence[int]],
leaves: Mapping[int, LeafChunk],
counted: Set[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.

counted comes from the caller and is mutated through estimate_ancestors, but node IDs are the same in every row group of a file. If a caller ever reuses one set across a file's row groups (natural for per-file state), every row group after the first silently drops its ancestor bytes (list offsets, struct/list bitmaps; ~800 KB of offsets for a 200k-row list<int64>), so the estimate comes out low. Both callers pass a fresh set() today. Could this just be a local variable?

@AarryaSaraf AarryaSaraf Nov 16, 2026 •

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, it's a local now.

return table, write_kwargs or {}, format_kwargs or {}, columns, high, threads


_CASES = {

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.

Most of the new branches don't have a case: estimate_cast, the small-file (< 48 KiB) branch (every file here is well over that), the DELTA and FIXED_LEN_BYTE_ARRAY paths, BYTE_ARRAY decimals, the dictionary fallback, uncompressed chunks, and decode_threads <= 0. The cases only cover snappy-compressed int/double/string/list<int64>, so a wrong branch in, say, the reserved > rows choice for DELTA reader bytes would ship unnoticed.

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.

Added cases for all of these except two PyArrow can't write: BYTE_ARRAY decimals, and a DELTA_BYTE_ARRAY chunk the estimator models (a PyArrow-written one takes #67840's fallback, which is tested there).

)
column_kept += ancestors + leaf_kept
column_peak = max(column_peak, column_kept + leaf_temporary)
column_decoded += ancestors + estimate_leaf(leaf=leaf)

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 (perf): some work is repeated on this per-row-group path:

  • estimate_leaf runs twice per leaf (here and L123).
  • estimate_row_group_peak (L58) rebuilds row_group.column(i) per leaf although LeafChunk.chunk already holds it.
  • chunk.encodings is built twice (L133, L137).
  • The power-of-two rounding is written out twice (L118, L171).

The footer-reader actors run this for every row group of every file, so on wide files it adds up. Returning decoded from estimate_leaf_work and taking compressed sizes from LeafChunk.chunk would remove most of 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, except row_group.column(i) in estimate_row_group_peak: that function also serves files with no LeafChunk to take the chunk from.

columns=["y", "l"],
),
# One CPU thread frees each column's buffers before the next column decodes.
"similar-lists": _case(pa.table({f"l{i}": _lists() for i in range(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.

_CASES builds every table at import time (~17 arrays of 200k rows from Python lists, including this 8-column list table twice), so collecting the module or running one case with -k pays for all of them. Storing factories (e.g. lambdas) and building the 8-list table once would avoid that.

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: each case holds a factory, and the eight-list table is built once.

cast += estimate_row_group(
row_group=row_group, leaves=leaves.values(), read=Read()
)
return int(_CAST_FACTOR * cast) + estimate_added_columns(

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.

Adding estimate_added_columns here has nothing to do with the cast, and it's why #67840 has to branch on pinned_schema to add the added columns exactly once; a future caller could easily count them twice or not at all. Simpler for the caller to always add them itself?

Two smaller things: column_leaves here is Mapping[str, Mapping[int, LeafChunk]] but Sequence[Sequence[int]] in estimate_row_group_work, so a different name would help; and estimate_row_group_peak's docstring (L52) says "given its work and cast" though it takes no cast.

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.

Agreed, fixed. estimate_cast returns only the cast and #67840's caller always adds the added columns itself. Also renamed the parameter to cast_leaves and fixed the docstring.

return pa.array([[i, i + 1, i + 2] for i in range(N)])


def _case(

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.

A few leftovers:

  • No case sets write_kwargs, format_kwargs or high.
  • The pytest.importorskip calls (L22-24) run after imports that already need pyarrow, so they can never skip.
  • _estimate (L88) maps columns to leaves with path.split(".")[0], which footer_reader._get_prefix_matches's docstring calls out as wrong for flat names containing dots (e.g. sepal.length).

Related: parquet_decode_peak.py imports the private _BINARY and _LIST from arrow_layout while this PR trims the package's exports.

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 the three leftovers. _BINARY and _LIST are imported from the module that defines them, not the package, so I've left that import.

@AarryaSaraf
AarryaSaraf requested a review from a team as a code owner November 17, 2026 22:09
AarryaSaraf and others added 3 commits November 17, 2026 14:11
for position, leaf_indices in enumerate(filter(None, column_leaves)):
# PyArrow 24 reserves the k-th column's leaves for as many slots as the
# file's k-th *leaf* has values, whichever column that leaf is in.
reserved = row_group.column(position).num_values

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.

reserved pairs the k-th read column with the file's k-th leaf, so any projection or filter-driven reordering indexes an unrelated chunk's value count.

File leaves in order: events list<int64> with 50M values, then a..z flat int64 columns with 1M values each. A read projects only z (or any filtered read, where column_leaves is reordered to put the filter column first). position = 0, so reserved = row_group.column(0).num_values = 50,000,000 — the list leaf, which isn't even read. slots = 2 * max(1_000_000, 50_000_000) = 100M, giving values = 8 * 100M = 800 MB plus 2 * 100M = 200 MB of definition levels, for a column whose decoded size is 8 MB.

The peak estimate comes out ~100x high, which a memory-based read-task sizer turns into tiny blocks and massive over-reservation. The only projection test (projection-over-small-chunks) uses 400 identical columns, so it can't detect the mis-pairing, and column-after-list-reserve reads every column, so it only validates the reordering case.

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. Up to PyArrow 25 the reader really does this: it reserves the i-th column read using the file's i-th leaf, so a flat column read alone is reserved for the list's values, and the memory is used. Arrow 26 reserves the row count instead, so the rule now follows the installed version. Added a case that reads only a flat column after a list.

pinned."""
cast = 0
for name, leaves in cast_leaves.items():
stored, pinned = file_schema.field(name).type, pinned_schema.field(name).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.

estimate_cast calls pa.Schema.field(name) unguarded on both schemas, so a missing or duplicated name raises KeyError out of an estimator the rest of the stack is built to never fail a read.

cast_leaves is keyed by column name. A pin that adds a column the file lacks, or a file column absent from the pin, or any schema with two fields of the same name (pyarrow's get_field_index returns -1 on an ambiguous name, and field() then raises KeyError) makes file_schema.field(name) / pinned_schema.field(name) throw.

Every neighbouring component degrades instead: build_leaf_profiles wraps its walk in except (pa.ArrowException, ValueError, TypeError): return None, read_footer_stats logs once and returns None, and leaf_chunks silently omits unmodelled leaves. This one propagates and fails the read task.

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.

Dealt with by the caller in 5/6.



@pytest.mark.parametrize("label", list(_CASES))
def test_estimate_bounds_measured_peak(tmp_path, label):

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.

15 parametrized cases each build a 200,000-row table, write a Parquet file, and launch a fresh interpreter that imports pyarrow and scans it — inside a size = "small" (60 s) Bazel target.

python/ray/data/BUILD.bazel globs tests/unit/**/test_*.py into py_test_module_list(size = "small", ...), which Bazel maps to a 60-second timeout.

Per case: _strings(N//4) materializes 200,000 Python f-strings (~0.4 s, 5 cases), _decimals() 200,000 Decimal objects (~0.5 s, 2 cases), pq.write_table of 200k rows, plus a subprocess.run([sys.executable, "-c", _SCAN, ...]) whose interpreter startup + import pyarrow alone costs ~0.6–1.5 s. 15 subprocesses is 9–22 s of pure process startup before any work; the total lands at 25–60 s on an idle machine and over 60 s on a loaded CI runner, flaking the target. The sibling suite test_parquet_decoded_size.py uses N=5000 for the same reason.

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 file runs in about 13 s for 20 cases locally, around 0.6 s a case, most of it the subprocess starting.

peak = _peak(path=path, rows=case.rows, columns=case.columns, threads=case.threads)
# The estimate carries a flat safety factor over the pool's peak.
ratio = estimate / (_SAFETY_FACTOR * peak)
assert 1.0 <= ratio <= case.high, ratio

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.

assert 1.0 <= ratio compares a static estimate against a live-measured allocator peak, so the lower bound fails whenever the machine, thread scheduling, or Arrow memory pool peaks above the model.

peak comes from pa.default_memory_pool().max_memory() in a subprocess that inherits the parent's environment, including ARROW_DEFAULT_MEMORY_POOL (jemalloc/mimalloc/system), which changes both the allocation pattern and what max_memory() reports.

For similar-lists-on-12-threads the test's own comment concedes "On a busy machine fewer overlap, down to one thread's peak" — the same non-determinism moves the measurement the other way (more overlap, more IO-thread prefetch) and drives ratio below 1.0. The failure is a bare assert ..., ratio with no retry or tolerance for measurement noise, and it will reproduce only on the CI host.

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.

This is flaky but its also a good signal for updates we wont actively track. Can make it 0.9 or smth

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.

def _list_offset_width(leaf: LeafChunk) -> int:
"""Bytes per offset of the widest list above ``leaf``: 4 under only a
fixed_size_list, which PyArrow reads as a list before dropping the offsets."""
widths = [node.width for node in leaf.profile.nodes[:-1] if node.kind == _LIST]

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.

_list_offset_width returns max(widths) and the caller charges one offsets buffer, so a leaf under N nested list levels is charged for a single level's offsets.

For list<list<int64>> (or map<string, list<...>>), leaf.profile.nodes[:-1] holds two _LIST nodes, but line 132 adds _list_offset_width(leaf) * reserved exactly once. parquet-cpp's nested ListReader reserves an offsets buffer per list level, so the estimate under-charges by roughly one buffer per extra level — the direction the PR description explicitly calls out as the OOM cause ("Underestimating is what causes OOMs, so the rules lean high").

Every _CASES entry uses single-level lists (_eight_lists, column-after-list-reserve), so nothing in the suite exercises a second level.

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.

Measured it on PyArrow 23 and 26: the estimate is 1.6 times the peak for list<list<int64>>, 1.4 to 1.8 for three levels and 1.95 for map<string, list<int64>>. The inner lists' offsets are part of the decoded bytes. Added a nested-list case.

@@ -0,0 +1,213 @@
"""Estimate PyArrow 24's peak memory decoding a Parquet row group, from its footer.

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 whole model is hardcoded to "PyArrow 24's reader" internals with no version guard, while the repo floor is pyarrow >= 23 and CI ships a pyarrow 25/26 lane.

python/requirements.txt pins pyarrow >= 23.0.0, python/requirements/data/pyarrow-v23.txt pins 23.0.0, and pyarrow-latest.txt pins 25.0.1 with the image force-installing 26 on Python >= 3.11.

Every constant here — _FOOTER_BYTES, _HOLE_BYTES, the doubling model in slots, the 5 * dictionary factor, _ZERO_COPY_PHYSICAL_TYPES — is calibrated on one minor release's reader. When pyarrow 26's reader changes any of them the estimate silently under-counts (the stated OOM direction) with no assertion, no get_pyarrow_version() check, and no telemetry hook, on a module whose only safety net is a flat 1.1x _SAFETY_FACTOR. _cast_reuses_buffers shows the authors did check 23 and 26 for casts; the buffer model got no equivalent treatment.

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 with the first comment: the one rule that differs by version now checks it, and the docstring no longer names 24. The unit tests measure the real peak, and CI runs them on PyArrow 23, 25 and 26.

if (leaf := leaves.get(leaf_idx)) is None:
continue
decoded += estimate_ancestors(leaf=leaf, counted=counted)
decoded += estimate_leaf(leaf=leaf)

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.

estimate_leaf(leaf) is computed twice for every leaf.

Line 102 does decoded += estimate_leaf(leaf=leaf) and line 119 recomputes decoded = estimate_leaf(leaf=leaf) for the same leaf. For a BYTE_ARRAY leaf that is estimate_string_bytes + estimate_string_type + a bitmap walk each time.

On a 400-column file (the suite's own _narrow_columns shape) with hundreds of row groups, this doubles the per-leaf estimator cost on the footer path, which the sibling module documents as running "about 7 microseconds per row group per leaf". Passing the already-computed decoded into estimate_leaf_buffers as a parameter removes 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.

estimate_leaf,
estimate_row_group,
)
from ray.data._internal.datasource_v2.formats.parquet.decoded_size.arrow_layout import (

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 module reaches past decoded_size/__init__.py into the private module arrow_layout for the private constant _LIST, in the same PR that narrows that package's public surface.

This PR deletes detect_string_type, detect_binary_or_list_type, estimate_fixed_width, estimate_string_type, detect_delta_byte_array, and pinned_type from decoded_size/__init__.py's __all__ to shrink the package's API — and then the one new consumer of that package imports _LIST from decoded_size.arrow_layout directly.

parquet_decode_peak.py also lives outside the decoded_size/ directory while every collaborator it uses lives inside it. Either _LIST belongs in the package's exports or this module belongs inside the package; as written the boundary the PR just tightened is bypassed on this line.

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. The offset width is now a property on LeafProfile.

# Bytes per value as PyArrow decodes each fixed-width physical type.
_PHYSICAL_WIDTH = dict(BOOLEAN=1, INT32=4, INT64=8, INT96=12, FLOAT=4, DOUBLE=8)
# Encodings whose decoders unpack a page's value lengths up front.
_DELTA_ENCODINGS = {"DELTA_BYTE_ARRAY", "DELTA_LENGTH_BYTE_ARRAY"}

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.

_DELTA_ENCODINGS, _DICTIONARY_ENCODINGS, and _PHYSICAL_WIDTH are mutable module-level set/dict literals where every sibling module uses frozenset.

footer_counts.py declares _PLAIN_STRING_ENCODINGS = frozenset({...}) and arrow_layout.py declares _ZERO_COPY_PHYSICAL_TYPES = frozenset({...}); this file declares the equivalent lookup tables as a mutable {...} set and dict(...).

Module-level mutable singletons are shared process-wide across every read task in the worker, so any accidental .add()/.pop() — or a test that monkeypatches one and doesn't restore it — silently changes the estimate for every subsequent file in that process.

Separately: parquet_decode_peak.py is the only module in this stack without from __future__ import annotations, so it uses typing.Mapping/Sequence/Set/Tuple where every neighbour uses the builtin generics.

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.

each top-level column read as its leaf indices, in the order PyArrow reads them:
the filter's columns, then the projection's others. ``leaves`` holds the
unpinned leaves modelled."""
decoded, buffers = 0, []

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 decoded-bytes loop is a copy of estimate_row_group's body, which this file already imports and uses two functions away in estimate_cast.

Lines 88–102 re-implement estimate.py's estimate_row_group verbatim — the counted: set[int] accumulator, the estimate_ancestors(leaf, counted) + estimate_leaf(leaf) pair — differing only in that it skips estimate_added_columns and groups by column. estimate_cast on line 172 calls the real estimate_row_group for the same work.

The two copies now have to be kept in sync by hand: any change to how a leaf's decoded bytes are summed (a new ancestor kind, a change to the counted keying) has to be made in both estimate.py and here, and only one of them has the decoded-size suite (test_parquet_decoded_size.py) covering 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.

Left as is: the buffers need each leaf's decoded bytes, so calling estimate_row_group would size every leaf twice, which is your comment on line 102. Added a line saying so.

@goutamvenkat-anyscale
goutamvenkat-anyscale enabled stacked auto-merge (squash) November 24, 2026 04:45
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit c434d0f into master Nov 24, 2026
5 checks passed
@goutamvenkat-anyscale
goutamvenkat-anyscale deleted the aarrya/decoded-size-4-peak branch November 24, 2026 05:26
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.

3 participants