Skip to content

[Data] Read the Parquet SizeStatistics PyArrow doesn't expose [1/6] - #67836

Merged
goutamvenkat-anyscale merged 22 commits into
masterfrom
aarrya/decoded-size-1-parser
Nov 9, 2026
Merged

goutamvenkat-anyscale merged 22 commits into
masterfrom
aarrya/decoded-size-1-parser

Conversation

@AarryaSaraf

@AarryaSaraf AarryaSaraf commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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.

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"]
Loading

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

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 high-performance Cython implementation (_compact_reader.pyx) along with a Python fallback (parquet_size_statistics.py) to parse Parquet footer size statistics and data page counts, which optimizes the footer walk. The review feedback highlights several critical security vulnerabilities in the Cython code, specifically potential integer overflows and out-of-bounds memory reads when casting large uint64_t values to signed Py_ssize_t or when advancing the buffer position (self.pos) without verifying the remaining buffer bounds.

@AarryaSaraf
AarryaSaraf added this pull request to stack #67842 November 4, 2026 22:13
AarryaSaraf and others added 2 commits November 4, 2026 14:33
…binaries image so //:ray_pkg_zip can build it

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…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 added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Nov 5, 2026
AarryaSaraf and others added 5 commits November 4, 2026 17:10
…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]>
…ompact reader builds on Windows

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…'s skip cases into one table

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…ask's size enough to keep

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@AarryaSaraf AarryaSaraf changed the title [Data] Read Parquet SizeStatistics, page counts and dictionary page headers PyArrow doesn't expose [1/6] [Data] Read Parquet SizeStatistics and dictionary page headers PyArrow doesn't expose [1/6] Nov 6, 2026
elif field_type == _DOUBLE:
self._pos += _DOUBLE_BYTES
elif field_type == _MAP:
count = self._varint()

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 MAP skip path can hang on adversarial input: for fixed-width element types (bool/byte/double), _skip_element only advances self._pos without ever reading the buffer, so a huge varint count here spins for _ in range(count) with no IndexError to stop it.

This reproduces the hang — running it against the module hangs on read_dictionary_page rather than returning in bounded time:

import signal
import parquet_size_statistics as pss  # this module

def handler(signum, frame):
    raise TimeoutError("still looping")

signal.signal(signal.SIGALRM, handler)
signal.alarm(3)  # a correct parse returns in microseconds

# field 1, type MAP (0x1B); long-form varint count ~2**40; types byte double/double (0x77)
payload = bytes([0x1B]) + bytes([0xFF] * 5 + [0x3F]) + bytes([0x77]) + bytes([0x00] * 56)
print(pss.read_dictionary_page(payload))  # never prints; raises TimeoutError after 3s

I ran exactly this: after 3s it is still in for _ in range(count): self._pos += 8 having read zero buffer bytes and raised nothing. read_dictionary_page parses raw bytes straight off disk at dictionary_page_offset that pyarrow never validated, so a single corrupt/crafted file pins a read task at 100% CPU. read_footer_stats's except Exception can't catch a hang either, so this also defeats the "a footer it can't read never fails the read" guarantee for the footer path.

The Cython version of this reader had a bounds check for exactly this (rejecting a count longer than the bytes remaining, commit 2cc51a1 on this branch) that didn't survive the port. Suggest raising _ThriftDesync when count > len(self._buf) - self._pos before the loop (each element needs at least one byte), here and in _skip_list/_i64_list for consistency.

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.

Ah yes, will fix.

reader._skip(sub.type)
else:
reader._skip(field.type)
except (IndexError, _ThriftDesync):

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.

RecursionError escapes this except: a buffer of repeated 0x1C bytes (field delta 1, type STRUCT) recurses _skip -> _skip_struct -> _skip two frames per byte, and past the default 1000-frame limit the function raises instead of returning None as the docstring promises.

Reproduction — this raises RecursionError instead of returning None:

import parquet_size_statistics as pss  # this module

buf = bytes([0x1C]) * 600  # 0x1C = field delta 1, type STRUCT; nests ~2 frames/byte
print(pss.read_dictionary_page(buf))  # raises RecursionError, not None

I ran exactly this and it raised RecursionError. Not reachable with the shipped 64-byte DICTIONARY_PAGE_HEADER_READ_BYTES, but this is a public function taking arbitrary buf, so a future caller reading a larger window is exposed. Either catch RecursionError here or cap struct nesting depth with _ThriftDesync.

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.

if len(row_groups) != metadata.num_row_groups:
return None
num_columns = metadata.num_columns
if any(len(columns) != num_columns for columns in row_groups):

@goutamvenkat-anyscale goutamvenkat-anyscale Nov 6, 2026 •

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 only check after parsing is that the row-group count and the per-group column count match the footer. Both of those are set by list headers right at the start of the walk, so they pass even if the cursor later drifts off position partway through a ColumnMetaData. If it drifts and then lands on bytes that happen to look like "field 16, struct, field 1 i64", we return wrong numbers with the counts still looking correct, and sizing downstream trusts them. (Negative values slip through here too, though read_dictionary_page rejects them.)

Suggestion: add a cheap sanity check per leaf using numbers pyarrow already gives us. For each leaf, if the repetition histogram is non-empty its first entry should equal metadata.row_group(i).num_rows, and otherwise if the definition histogram is non-empty its entries should sum to num_rows. If that doesn't hold, the parse drifted -- return None. This checks the actual decoded values against trusted numbers, not just the shape.

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 check exists one layer up, in #67837: LeafChunk._histograms_agree (parquet_decoded_size.py) compares each leaf's histograms with PyArrow's numbers: the first repetition entry with the row group's num_rows, both sums with the chunk's num_values, and each histogram's length with the leaf's max levels. On a mismatch it drops that leaf's histograms and falls back to the footer's bounds. I'd keep it per leaf rather than return None for the file, because a mismatch isn't always drift: PyArrow 24's writer adds an entry at repetition level 0 for every 16,384 values in one record, so one row holding a 16,385-value list reports (2, 16383). A file-level None would throw away every other column's SizeStatistics in any file with a tensor column. Negative values now raise _ThriftDesync here (), for the string bytes and every histogram entry.

"""The raw Thrift footer behind a ``FileMetaData``, or ``None``: from
``__reduce__``, which PyArrow pickles it with, so no I/O but not public API."""
try:
payload = metadata.__reduce__()[1][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.

The test suite asserts len(buf) == metadata.serialized_size as the integrity anchor for this private API, but production never checks it. If a future pyarrow reshapes the reduce args tuple to some other bytes-like state blob, [1][0] still casts to a memoryview and the thrift walk may parse it cleanly, feeding wrong numbers into sizing with no error anywhere (the count checks only compare list cardinalities).

Suggest returning None here when len(payload) != metadata.serialized_size -- it's the one cheap, public anchor proving the payload is actually the footer.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'd rather not compare with serialized_size: reduce doesn't hand back the file's bytes, it writes the parsed metadata out again (FileMetaData.reduce calls WriteTo), while serialized_size is the original footer's length. They match for PyArrow and Polars footers, but a footer carrying a field PyArrow's Thrift doesn't know, say from a newer writer, comes back shorter, and the check would throw away SizeStatistics that parse fine: a PyArrow footer with an unknown field 100 appended has serialized_size 2,169 and a reduce payload of 2,162. Instead the walk now has to end exactly at the payload's last byte (). PyArrow writes one FileMetaData and nothing after it, so a different blob would have to parse as exactly one footer, with the right row-group and column counts, to get through: a pickle of the FileMetaData and a footer with 4 bytes appended both give None.



# Thrift compact type ids.
_BOOL_TRUE, _BYTE, _I64 = 1, 3, 6

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.

These redefine the thrift type ids the module already defines, and the test already reaches into pss for _CompactReader, LeafSizeStats, and _ThriftDesync. If the module's ids are ever corrected, the shadow copy keeps passing against stale ids and the hand-built payloads stop pinning the real reader's skip widths. Suggest pss._BOOL_TRUE 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.

I'd keep the copy: it's there so the tests check the module's ids against the spec rather than against themselves. These payloads cover skip widths PyArrow footers never exercise (doubles, bytes, bools in lists), so nothing else pins those ids. With pss._DOUBLE mistyped as 13, the doubles case built from the spec's 7 fails with "unknown compact type 7", while one built from pss._DOUBLE still passes, since the payload carries the same wrong id. The ids are fixed by the compact protocol, so the copy can't go stale. I've reworded the comment above it to say this

AarryaSaraf and others added 3 commits November 6, 2026 15:16
…og its fallbacks once

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…ings without SizeStatistics used

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…onary page reader's removal

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@AarryaSaraf AarryaSaraf changed the title [Data] Read Parquet SizeStatistics and dictionary page headers PyArrow doesn't expose [1/6] [Data] Read the Parquet SizeStatistics PyArrow doesn't expose [1/6] Nov 9, 2026
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit b3b6e8f into master Nov 9, 2026
6 checks passed
@goutamvenkat-anyscale
goutamvenkat-anyscale deleted the aarrya/decoded-size-1-parser branch November 9, 2026 22:43
goutamvenkat-anyscale pushed a commit that referenced this pull request Nov 11, 2026
…oter [2/6] (#67837)

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

```mermaid
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"]
```

This is what the dataflow looks like

```mermaid
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
```

- With `SizeStatistics` (read by #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](https://claude.com/claude-code)

---------

Signed-off-by: Aarrya <[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