Skip to content

[Data] Size Parquet V2 read tasks by exact decoded bytes from footer SizeStatistics - #66121

Closed
goutamvenkat-anyscale wants to merge 2 commits into
ray-project:masterfrom
goutamvenkat-anyscale:goutam/parquet-decoded-size-planning
Closed

goutamvenkat-anyscale wants to merge 2 commits into
ray-project:masterfrom
goutamvenkat-anyscale:goutam/parquet-decoded-size-planning

Conversation

@goutamvenkat-anyscale

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Parquet's total_uncompressed_size is the encoded size — decompressed, but still dictionary/RLE/bit-packed — and is a poor proxy for the Arrow block a read task actually materializes: measured decoded/uncompressed ratios span 0.87x for plain int64 to 133x for nullable dictionary-encoded strings. Sizing V2 read tasks on it (raw or scaled by the fixed 5x encoding ratio) either floods the scheduler with tiny tasks or overfills blocks to the point of OOM.

The footer already carries the missing quantity: SizeStatistics (parquet-format 2.10), which PyArrow's C++ writer emits by default but whose Python bindings expose no getter (pyarrow 23 binds geo_statistics — Thrift field 17 — but not field 16). This PR recovers it with a targeted Thrift walk over footer bytes already in memory and computes each row group's exact decoded Arrow size, which then drives bin packing, an upfront per-task memory reservation, and reader batch sizing. On a mixed-type 100k-row file the footer-only estimate lands within 0.6% of pa.Table.nbytes, where the old heuristic overestimated by 4.6x.

Files whose footers lack usable SizeStatistics fall back per row group to the pre-existing uncompressed x ratio estimate, bit-for-bit.

Overarching approach

flowchart TD
    A["FooterReader (ListFiles op)<br/>one footer fetch per file → FileMetaData"] --> B["read_size_statistics()<br/>targeted Thrift walk over footer bytes<br/>(zero extra I/O)"]
    A --> C["estimate_row_group_decoded_size()<br/>per row group, per projected leaf"]
    B -->|"LeafSizeStats[rg][leaf]"| C
    C -->|"exact decoded bytes"| D["coalesce_row_groups()<br/>merge contiguous row groups,<br/>target measured in decoded bytes"]
    C -.->|"None (no SizeStatistics)"| F["fallback: uncompressed x 5<br/>(pre-existing behavior)"]
    F -.-> D
    D --> E["OnlineBinPacker<br/>cap = target_max_block_size, in decoded bytes<br/>1 sealed bin = 1 read task"]
    E --> G["Ray memory reservation<br/>256 MiB + 8 x cap per read task"]
    E --> H["block sizing<br/>bins land on the block target"]
    E --> I["reader batch sizing<br/>rows/batch = target / (decoded/num_rows)"]
Loading

Decoded-size recovery from the footer bytes

FileMetaData.__reduce__() returns the raw TCompactProtocol-serialized footer. The walk decodes only the recognized path FileMetaData.4 → RowGroup.1 → ColumnChunk.3 → ColumnMetaData.16 and generically skips every other field (scanned, never materialized) — the same targeted-parse approach arrow-rs adopted for its 3-9x footer-parsing speedup.

flowchart TD
    A["FileMetaData.__reduce__()<br/>raw Thrift footer bytes"] --> B["struct FileMetaData<br/>field 4: row_groups — everything else skipped"]
    B -->|"x num row groups"| C["struct RowGroup<br/>field 1: columns"]
    C -->|"x num leaves"| D["struct ColumnChunk<br/>field 3: meta_data"]
    D --> E["struct ColumnMetaData<br/>field 16: size_statistics<br/>(fields 1-15, 17+ skipped, incl. Statistics blobs)"]
    E --> F["SizeStatistics<br/>1: unencoded_byte_array_data_bytes<br/>2: repetition_level_histogram<br/>3: definition_level_histogram"]
    F --> G{"per-leaf decoded size"}
    G -->|fixed width| H["num_values x arrow_width(type)"]
    G -->|BYTE_ARRAY| I["unencoded bytes + 4·(n+1) offsets"]
    G -->|BOOLEAN| J["ceil(n / 8)"]
    G --> K["+ validity bitmap iff nulls present<br/>(definition-level histogram)<br/>+ list offsets (repetition-level histogram)"]
    H & I & J & K --> L{"every projected leaf exact?"}
    L -->|yes| M["exact decoded size for the row group"]
    L -->|"no (all-or-nothing)"| N["None → fallback sizing"]
    E -->|"type assertion fails → _ThriftDesync"| N
    A -->|"truncated footer → IndexError"| N
Loading

Hand-decoded binary fails by returning wrong numbers, not by raising: a one-byte cursor desync decodes later field-id deltas onto plausible but wrong ids. Guards: type assertions on every recognized field (field 17 geospatial_statistics is also a struct — only the assert on its field 1 catches a drifted cursor), row-group/leaf shape checks against FileMetaData, and a differential test against thriftpy2's independent compact-protocol implementation (test-only dependency) as the module's real contract. Any failure returns None and the file keeps the old sizing.

Related issue number

N/A. Checked for duplicate work before opening: searched open PRs for "parquet decoded size", "SizeStatistics", "read task memory parquet", and "bin packing parquet" — no open PR or issue addresses footer-based decoded-size estimation for V2 read planning.

Checks

  • I've signed off every commit (DCO).
  • I've run pre-commit hooks (pre-commit run — all hooks pass; ruff/black clean).
  • Tests:
    • python -m pytest python/ray/data/tests/unit/datasource_v2/test_parquet_decoded_size.py test_parquet_size_statistics.py test_online_bin_packer.py test_file_chunker.py test_read_task_memory.py test_file_indexer.py — 204 passed.
    • Coverage includes a thriftpy2 differential oracle over a matrix of written files, decoded-size accuracy vs real pa.Table.nbytes (within a validity bitmap), desync-injection tests, and fallback behavior.
  • AI assistance was used for parts of this change (Claude Code); I have reviewed every changed line and run the tests above locally.
  • Release tests / benchmarks on wide-footer datasets (draft — pending before marking ready).

🤖 Generated with Claude Code

…SizeStatistics

Parquet's total_uncompressed_size is the encoded size (decompressed but
still dictionary/RLE/bit-packed) and is a poor proxy for the Arrow block a
read task materializes: measured decoded/uncompressed ratios span 0.87x
(plain int64) to 133x (nullable dictionary-encoded strings). Sizing read
tasks on it either floods the scheduler with tiny tasks or overfills
blocks into OOMs.

This change recovers the footer's SizeStatistics (parquet-format 2.10) --
which PyArrow writes by default but exposes no Python getter for -- via a
targeted TCompactProtocol walk over the raw footer bytes FileMetaData
already holds, and computes each row group's exact decoded Arrow size from
value counts, per-type widths, unencoded byte-array bytes, and
definition/repetition level histograms. The decoded size then drives:

- row-group coalescing and online bin packing (bin cap now defaults to
  target_max_block_size, measured in decoded bytes; 1 bin = 1 read task)
- an upfront Ray memory reservation per read task
- reader batch sizing, replacing the fixed 5x encoding-ratio guess

Files without usable SizeStatistics fall back per row group to the
pre-existing uncompressed x ratio estimate. The Thrift walk is guarded by
type assertions, shape checks, and a differential test against thriftpy2
(test-only dependency).

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
@goutamvenkat-anyscale goutamvenkat-anyscale added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Sep 14, 2026
if leaf_idx >= len(size_stats) or leaf_idx >= len(leaf_profiles):
return None
stats = size_stats[leaf_idx]
if stats is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why is this here? Is there any case where this is needed? It causes it to return None here:

pa.table(
            {"a": pa.array(range(N), pa.int64()),
             "b": pa.array([f"s-{i:08d}" for i in range(N)], pa.string())},
            schema=pa.schema([pa.field("a", pa.int64(), nullable=False),
                              pa.field("b", pa.string(), nullable=True)]),
        ),


# Arrow's offsets buffer for string/binary/list uses int32 offsets and holds one
# more entry than there are values, so the trailing end offset is included.
_OFFSET_WIDTH = 4

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 isnt true in general. Is the following example out of our scope of support? Consider
pa.table({"s": pa.array([f"{i % 10}" for i in range(N)], pa.large_string())})

# The spec defines the field as exclusive of each value's length prefix,
# so Arrow's offsets buffer is added separately rather than assumed
# included.
total = stats.unencoded_byte_array_data_bytes + _OFFSET_WIDTH * (num_values + 1)

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.

Correct for a hydrated StringArray, but when ARROW:schema marks the column a dictionary, PyArrow returns a DictionaryArray whose cost is 4 x num_values plus the dictionary itself.
consider:

pa.table({"d": pa.array([f"{i % 50:02000d}" for i in range(N)]

if histogram:
# The last bucket counts values at the max definition level, i.e. the
# non-null ones; everything below it is a null at some level.
return chunk.num_values > histogram[-1]

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.

Seems theoretically correct, and I confirmed bool and int8 get no bitmap. But practically arrow-C++ allocates one anyway for int64/double/timestamp, so the answer is type-dependent in a way the function assumes it isn't.
Consider

 pa.table({"i": pa.array(np.arange(N, dtype=np.int64))})

width = profile.fixed_width
if width is None:
return None
total = num_values * width

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.

An empty list still emits one Parquet record at a definition level below max, so it's in num_values — but contributes zero elements to the child array.
consider

pa.table(
            {"l": pa.array([[] if i % 2 else [1, 2] for i in range(N)], pa.list_(pa.int64()))}
        ),

running = 0
for level in range(min(max_repetition_level, len(histogram))):
running += histogram[level]
total += _OFFSET_WIDTH * (running + 1)

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.

Is this something you saw empirically?


if _has_nulls(profile, chunk, stats):
total += math.ceil(num_values / 8)
total += _list_offsets_size(profile, 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.

Could you explain this?

return 0
histogram = stats.repetition_level_histogram
if not histogram:
# Permitted omission only when max_repetition_level is 0, which is

@AarryaSaraf AarryaSaraf Sep 15, 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.

Wait shouldnt we return a "I dont know" and not 0?

@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Sep 29, 2026
goutamvenkat-anyscale pushed a commit that referenced this pull request Sep 29, 2026
…mmon/ and formats/parquet/ (#66497)

## Description

`python/ray/data/_internal/datasource_v2/` grouped files by role
(`listing/`,
`scanners/`, `readers/`, `partitioners/`, `chunkers/`), and each role
folder
mixed the abstract class, the format-independent implementation and the
Parquet one. `listing/file_indexer.py` held `FileIndexer` next to
`NonSamplingFileIndexer`, with `FooterFileIndexer` two files over.
Someone
adding a format could not tell from the tree what they must implement,
what
they may reuse, and what is Parquet's business.

This PR regroups the package by kind: `interfaces/` is what a format
implements, `common/` is what it may reuse, `formats/<name>/` is one
folder
per format. `interfaces/` imports nothing else in the package, `common/`
imports only `interfaces/`, `formats/` may import both. No class,
signature
or behaviour changes; every import path changes.

### The layout

```
python/ray/data/_internal/datasource_v2/
  __init__.py                      InputSplit TypeVar (unchanged)
  README.md                        new: layout rule, how a read flows, what a format implements
  interfaces/                      abstract classes and the types their signatures use
    datasource_v2.py               DataSourceV2, DatasourceCategory, FileDataSourceV2, DataSourceWithMetadata
    scanner.py                     Scanner
    reader.py                      Reader
    file_indexer.py                FileIndexer, FileInfo
    file_pruner.py                 FilePruner
    file_partitioner.py            FilePartitioner, PartitionHints
    in_memory_size_estimator.py    InMemorySizeEstimator
    supports_metadata.py           SupportsMetadata, MetadataType
    pushdown.py                    SupportsFilterPushdown, SupportsColumnPushdown, SupportsLimitPushdown, SupportsPartitionPruning, ListFilesPushdown
    read_units.py                  ReadUnit, ReadUnitFragment
    synthesized_columns.py         SynthesizedColumn, ReadUnitPosition
    file_manifest.py               FileManifest, ChunkMetadata, create_chunk_metadata
  common/                          format-independent implementations
    non_sampling_file_indexer.py   NonSamplingFileIndexer
    listing_utils.py, indexing_utils.py
    file_pruners.py                FileExtensionPruner, PartitionPruner, PartitionPredicatePruner
    round_robin_partitioner.py     RoundRobinPartitioner
    online_bin_packer.py           OnlineBinPacker, BinItem, Bin
    size_estimators.py             SamplingInMemorySizeEstimator
    file_scanner.py                FileScanner
    arrow_file_scanner.py          ArrowFileScanner
    file_reader.py                 FileReader
    synthesized_columns.py         PathColumn, RowHashColumn
    pushdown_utils.py              derive_list_files_pushdown, combine_predicates
  formats/
    parquet/
      parquet_datasource_v2.py     ParquetDatasourceV2
      parquet_scanner.py           ParquetScanner
      parquet_file_reader.py       ParquetFileReader
      footer_file_indexer.py       FooterFileIndexer
      footer_reader.py             FooterReader actor
      parquet_footer_types.py      RowGroupInfo, FileChunks, ParquetRowGroupChunkMetadata
      parquet_size_estimator.py    ParquetInMemorySizeEstimator
      parquet_file_chunking_utils.py, parquet_row_group_coalescing.py, parquet_utils.py
```

### What changes
1. **32 renames** into the three folders; `git diff -M` pairs them, most
at 90%+ similarity with the rest being import lines.
2. **7 files split** where an interface sat next to its implementations:
`listing/file_indexer.py`, `listing/file_pruners.py`,
`readers/in_memory_size_estimator.py`, `readers/synthesized_columns.py`,
`logical_optimizers.py` (mixins to `interfaces/pushdown.py`, helpers to
`common/pushdown_utils.py`), `chunkers/file_chunker.py` (dissolved into
`interfaces/file_manifest.py` and
`formats/parquet/parquet_footer_types.py`) and
`chunkers/parquet_footer_types.py` (`BinItem`/`Bin` to
`common/online_bin_packer.py`).
3. **27 files outside the package** change import lines only:
`read_api.py`, the legacy `ParquetDatasource`, logical rules, planners,
tests. Tests keep their locations.
4. **Nine type errors fixed** in `common/indexing_utils.py`,
`common/non_sampling_file_indexer.py` and `interfaces/file_manifest.py`.
These three files were in `ci/lint/pyrefly-excluded-files.txt` under
their old paths, so the move puts them under pyrefly for the first time.
The fixes: re-raise after `_handle_read_os_error` returns instead of
reading an unbound `file_info`; the threaded lister always wraps results
in `OrderedFileResult` and unwraps on yield, so `input_path_index` is an
`int` and there is no `FileInfo | OrderedFileResult` union;
`FileManifest.__init__` asserts a `TableBlockAccessor` before calling
`column_names()`. `ci/` is not touched.
5. **`README.md`** (new) for the package.

One import still crosses the layering line:
`common/online_bin_packer.py` reads and writes
`ParquetRowGroupChunkMetadata` from `formats/parquet/`. The packer is
meant for any format with sized sub-file units, so it stays in
`common/`. A follow-up PR, once #66121 has settled the packer's fields,
adds a generic chunk-run type in `interfaces/` that the packer works on
and makes the Parquet type a subclass of it. Doing that here would turn
a reviewable set of renames into content changes.

## Additional information
Follows #66450 (`[4/6]`) and #66478 (`[5/6]`), both merged; the branch
sits directly on `master`. Not a duplicate: #62573 (WIP, `_internal/`
wide) does not touch `datasource_v2/`.

Checks run locally from this branch (macOS, `~/ray/.venv`):
```
pytest -q tests/unit/datasource_v2   # 146 passed
```
`ruff`, `black` and `pydoclint` at the pre-commit pins are clean on
every changed Python file; `tests/test_import.py` (from #66463) passes;
`pyrefly` via `ci/lint/pyrefly-check.sh` reports 59 errors, identical to
`master`, none new.

Written with Claude Code; I reviewed every changed line and ran the
tests above.

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

---------

Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
goutamvenkat-anyscale pushed a commit that referenced this pull request Oct 1, 2026
…mat with one `FileChunk` type for run metadata (#66577)

## Description

Last PR of the DSv2 Reorg series. Three changes, two types:

1. **`OnlineBinPacker` packs any file, not just Parquet.** It read and
wrote `ParquetRowGroupChunkMetadata`, so only the Parquet footer indexer
could feed it. It now works on a format-neutral row: "this file's units
3-5, N rows, S bytes", where a unit is whatever a format's reader can
scan on its own (a Parquet row group today, a CSV byte range or a Lance
fragment tomorrow). The packer only sums `size_bytes` against its budget
and never asks what the number measures; the indexer that writes the row
decides. The packing arithmetic is unchanged.
2. **One dataclass for "a run of units" instead of four look-alikes.**
`RowGroupInfo` (footer reader and coalescer),
`ParquetRowGroupChunkMetadata` (manifest row), the copied fields on the
packer's `BinItem`, and the `create_chunk_metadata` helper that built
the row all carried the same ids / rows / bytes / per-unit tuples under
different names. They collapse into one frozen `FileChunk` in
`interfaces/file_manifest.py`, with `to_metadata()` / `from_metadata()`
for the manifest's `__file_chunk_metadata` column. (Named `UnitRun` in
the first draft; renamed per review because it read too close to
`ReadUnit`.)
3. **One shape for "a file and its size" from listing to packer.**
`FileInfo(path, size)` already existed in `interfaces/file_indexer.py`,
but the listing helpers passed `(path, size)` tuples,
`OrderedFileResult` carried the path twice, the footer actor took
`list[tuple[str, int]]`, its result `FileChunks` had its own
`path`/`size`, and the packer's `BinItem` had its own
`path`/`size_bytes`. All of them now carry a `FileInfo`. An indexer
author emits one type; a reviewer checks no conversions.

**Cost of the unified types.** Measured with `pympler.asizeof` on Python
3.12, same 45-character path for old and new. A single-row-group run is
888 bytes as a `FileChunk` versus 920 as a `RowGroupInfo`; a three-group
coalesced run is 1120 versus 1072. A `BinItem` is 1888 bytes versus 1416
for the old flat `BinItem(path, size_bytes, run)`: the extra ~470 bytes
is the `FileInfo` instance it now points at instead of copying its two
fields. `BinItem`s are transient packing state, bounded by the open
bins, so this is a few hundred bytes per in-flight item. The manifest's
Arrow column is unchanged at 36 bytes per row, because the struct has
the same fields under new names.

### What changes

1. **`interfaces/file_manifest.py`.** New `FileChunk(unit_ids, num_rows,
size_bytes, fully_matched=True, unit_sizes=(), unit_rows=())` with
`to_metadata()` / `from_metadata()`; `__post_init__` asserts a per-unit
breakdown is empty or one entry per unit. `create_chunk_metadata` and
its `TypeVar` are removed; the empty `ChunkMetadata` `TypedDict` becomes
a `Dict[str, Any]` alias, since a row's chunk metadata is now always
`None` or `FileChunk.to_metadata()`.
2. **`formats/parquet/`.** `parquet_footer_types.py` is deleted:
`RowGroupInfo` and `ParquetRowGroupChunkMetadata` are gone, and the one
survivor, `FileChunks` → `ChunkedFile(file: FileInfo, row_groups:
Tuple[FileChunk, ...])`, moves next to the `FooterReader` that builds
it. `footer_reader.py` builds one `FileChunk` per row group and
`_read_and_chunk` / `read_footers` take `FileInfo`;
`parquet_row_group_coalescing.py` merges with `dataclasses.replace`;
`footer_file_indexer.py` emits `run.to_metadata()` via
`_chunked_file_to_manifest` with `size_bytes` = the run's
projection-scoped uncompressed size, as before. `parquet_file_reader.py`
reads `unit_ids` and `size_bytes`, and drops the `"uncompressed_size" in
chunk` key check, since a non-`None` row always has the keys now.
Docstrings in `parquet_file_chunking_utils.py` follow.
3. **`common/indexing_utils.py`,
`common/non_sampling_file_indexer.py`.** `PathContents.files` and
`_get_file_infos` produce `FileInfo`; `OrderedFileResult` loses its
duplicate `file_path`.
4. **`common/online_bin_packer.py`.** `BinItem(file: FileInfo, run:
Optional[FileChunk])`, with `size_bytes` a property (the run's bytes,
else the file size); `run is None` is a whole-file row. Splitting a run
slices the `FileChunk`; a sealed bin merges a file's runs back into one
`FileChunk` row. `Bin.total_uncompressed_size` → `total_bytes`. Two
behaviour details: a whole-file row now comes out of the packer as a
whole-file row again (it used to come out claiming
`row_group_ids=(0,)`), and every packed row keeps the on-disk
`__file_size` the listing gave it (a chunk row used to carry the run's
bytes there; nothing reads `__file_size` after the packer).
5. **README.** One paragraph under "Adding a format": an indexer that
lists `FileChunk` rows can hand them to `OnlineBinPacker` as they are.
6. **Tests.** `test_online_bin_packer.py` builds rows directly and
imports nothing from `formats/`; its `coalesce_row_groups` cases move
verbatim to a new `test_parquet_row_group_coalescing.py`, since they are
Parquet's; two tests added (whole-file rows, on-disk size kept).
`test_chunk_metadata.py` becomes a `FileChunk` round-trip and invariant
test. `FileInfo` / renamed fields in `test_footer_reader.py`,
`test_read_units.py`, `test_synthesized_columns.py`,
`test_parquet_datasource_v2.py`, `test_file_indexer.py` and
`tests/datasource/test_read_parquet_v2.py`.

## Additional information

Not a duplicate: no open PR generalises the packer's row or unifies the
listing types. #66121 and #65887 both touch these files under the
pre-#66497 paths and will need a rebase either way; #66121 adds a second
size field to the old Parquet row; on this PR it needs no new field,
since `size_bytes` is whatever the indexer records and the
decoded-or-fallback choice belongs in the footer indexer's
`_chunked_file_to_manifest`. Its footer-indexer changes will see
`ChunkedFile.file.path` and `read_footers(list[FileInfo])` rather than
tuples.

Checks run locally from this branch (macOS, `~/ray/.venv`):

```
pytest -q python/ray/data/tests/unit/datasource_v2 \
          python/ray/data/tests/datasource_v2/test_footer_reader.py  # 193 passed
pytest -q python/ray/data/tests/datasource/test_read_parquet_v2.py   # 37 passed
```

`ruff`, `black` and `pydoclint` at the pre-commit pins are clean on
every changed file; `pyrefly` 0.51.0 with `pyarrow==24.0.0` reports no
errors in the changed files. `grep -r datasource_v2.formats interfaces/
common/` is empty.

Written with Claude Code; I reviewed every changed line and ran the
tests above.

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 Fable 5.1 <[email protected]>
@goutamvenkat-anyscale goutamvenkat-anyscale removed the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 2, 2026
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…mmon/ and formats/parquet/ (ray-project#66497)

## Description

`python/ray/data/_internal/datasource_v2/` grouped files by role
(`listing/`,
`scanners/`, `readers/`, `partitioners/`, `chunkers/`), and each role
folder
mixed the abstract class, the format-independent implementation and the
Parquet one. `listing/file_indexer.py` held `FileIndexer` next to
`NonSamplingFileIndexer`, with `FooterFileIndexer` two files over.
Someone
adding a format could not tell from the tree what they must implement,
what
they may reuse, and what is Parquet's business.

This PR regroups the package by kind: `interfaces/` is what a format
implements, `common/` is what it may reuse, `formats/<name>/` is one
folder
per format. `interfaces/` imports nothing else in the package, `common/`
imports only `interfaces/`, `formats/` may import both. No class,
signature
or behaviour changes; every import path changes.

### The layout

```
python/ray/data/_internal/datasource_v2/
  __init__.py                      InputSplit TypeVar (unchanged)
  README.md                        new: layout rule, how a read flows, what a format implements
  interfaces/                      abstract classes and the types their signatures use
    datasource_v2.py               DataSourceV2, DatasourceCategory, FileDataSourceV2, DataSourceWithMetadata
    scanner.py                     Scanner
    reader.py                      Reader
    file_indexer.py                FileIndexer, FileInfo
    file_pruner.py                 FilePruner
    file_partitioner.py            FilePartitioner, PartitionHints
    in_memory_size_estimator.py    InMemorySizeEstimator
    supports_metadata.py           SupportsMetadata, MetadataType
    pushdown.py                    SupportsFilterPushdown, SupportsColumnPushdown, SupportsLimitPushdown, SupportsPartitionPruning, ListFilesPushdown
    read_units.py                  ReadUnit, ReadUnitFragment
    synthesized_columns.py         SynthesizedColumn, ReadUnitPosition
    file_manifest.py               FileManifest, ChunkMetadata, create_chunk_metadata
  common/                          format-independent implementations
    non_sampling_file_indexer.py   NonSamplingFileIndexer
    listing_utils.py, indexing_utils.py
    file_pruners.py                FileExtensionPruner, PartitionPruner, PartitionPredicatePruner
    round_robin_partitioner.py     RoundRobinPartitioner
    online_bin_packer.py           OnlineBinPacker, BinItem, Bin
    size_estimators.py             SamplingInMemorySizeEstimator
    file_scanner.py                FileScanner
    arrow_file_scanner.py          ArrowFileScanner
    file_reader.py                 FileReader
    synthesized_columns.py         PathColumn, RowHashColumn
    pushdown_utils.py              derive_list_files_pushdown, combine_predicates
  formats/
    parquet/
      parquet_datasource_v2.py     ParquetDatasourceV2
      parquet_scanner.py           ParquetScanner
      parquet_file_reader.py       ParquetFileReader
      footer_file_indexer.py       FooterFileIndexer
      footer_reader.py             FooterReader actor
      parquet_footer_types.py      RowGroupInfo, FileChunks, ParquetRowGroupChunkMetadata
      parquet_size_estimator.py    ParquetInMemorySizeEstimator
      parquet_file_chunking_utils.py, parquet_row_group_coalescing.py, parquet_utils.py
```

### What changes
1. **32 renames** into the three folders; `git diff -M` pairs them, most
at 90%+ similarity with the rest being import lines.
2. **7 files split** where an interface sat next to its implementations:
`listing/file_indexer.py`, `listing/file_pruners.py`,
`readers/in_memory_size_estimator.py`, `readers/synthesized_columns.py`,
`logical_optimizers.py` (mixins to `interfaces/pushdown.py`, helpers to
`common/pushdown_utils.py`), `chunkers/file_chunker.py` (dissolved into
`interfaces/file_manifest.py` and
`formats/parquet/parquet_footer_types.py`) and
`chunkers/parquet_footer_types.py` (`BinItem`/`Bin` to
`common/online_bin_packer.py`).
3. **27 files outside the package** change import lines only:
`read_api.py`, the legacy `ParquetDatasource`, logical rules, planners,
tests. Tests keep their locations.
4. **Nine type errors fixed** in `common/indexing_utils.py`,
`common/non_sampling_file_indexer.py` and `interfaces/file_manifest.py`.
These three files were in `ci/lint/pyrefly-excluded-files.txt` under
their old paths, so the move puts them under pyrefly for the first time.
The fixes: re-raise after `_handle_read_os_error` returns instead of
reading an unbound `file_info`; the threaded lister always wraps results
in `OrderedFileResult` and unwraps on yield, so `input_path_index` is an
`int` and there is no `FileInfo | OrderedFileResult` union;
`FileManifest.__init__` asserts a `TableBlockAccessor` before calling
`column_names()`. `ci/` is not touched.
5. **`README.md`** (new) for the package.

One import still crosses the layering line:
`common/online_bin_packer.py` reads and writes
`ParquetRowGroupChunkMetadata` from `formats/parquet/`. The packer is
meant for any format with sized sub-file units, so it stays in
`common/`. A follow-up PR, once ray-project#66121 has settled the packer's fields,
adds a generic chunk-run type in `interfaces/` that the packer works on
and makes the Parquet type a subclass of it. Doing that here would turn
a reviewable set of renames into content changes.

## Additional information
Follows ray-project#66450 (`[4/6]`) and ray-project#66478 (`[5/6]`), both merged; the branch
sits directly on `master`. Not a duplicate: ray-project#62573 (WIP, `_internal/`
wide) does not touch `datasource_v2/`.

Checks run locally from this branch (macOS, `~/ray/.venv`):
```
pytest -q tests/unit/datasource_v2   # 146 passed
```
`ruff`, `black` and `pydoclint` at the pre-commit pins are clean on
every changed Python file; `tests/test_import.py` (from ray-project#66463) passes;
`pyrefly` via `ci/lint/pyrefly-check.sh` reports 59 errors, identical to
`master`, none new.

Written with Claude Code; I reviewed every changed line and ran the
tests above.

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

---------

Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…mat with one `FileChunk` type for run metadata (ray-project#66577)

## Description

Last PR of the DSv2 Reorg series. Three changes, two types:

1. **`OnlineBinPacker` packs any file, not just Parquet.** It read and
wrote `ParquetRowGroupChunkMetadata`, so only the Parquet footer indexer
could feed it. It now works on a format-neutral row: "this file's units
3-5, N rows, S bytes", where a unit is whatever a format's reader can
scan on its own (a Parquet row group today, a CSV byte range or a Lance
fragment tomorrow). The packer only sums `size_bytes` against its budget
and never asks what the number measures; the indexer that writes the row
decides. The packing arithmetic is unchanged.
2. **One dataclass for "a run of units" instead of four look-alikes.**
`RowGroupInfo` (footer reader and coalescer),
`ParquetRowGroupChunkMetadata` (manifest row), the copied fields on the
packer's `BinItem`, and the `create_chunk_metadata` helper that built
the row all carried the same ids / rows / bytes / per-unit tuples under
different names. They collapse into one frozen `FileChunk` in
`interfaces/file_manifest.py`, with `to_metadata()` / `from_metadata()`
for the manifest's `__file_chunk_metadata` column. (Named `UnitRun` in
the first draft; renamed per review because it read too close to
`ReadUnit`.)
3. **One shape for "a file and its size" from listing to packer.**
`FileInfo(path, size)` already existed in `interfaces/file_indexer.py`,
but the listing helpers passed `(path, size)` tuples,
`OrderedFileResult` carried the path twice, the footer actor took
`list[tuple[str, int]]`, its result `FileChunks` had its own
`path`/`size`, and the packer's `BinItem` had its own
`path`/`size_bytes`. All of them now carry a `FileInfo`. An indexer
author emits one type; a reviewer checks no conversions.

**Cost of the unified types.** Measured with `pympler.asizeof` on Python
3.12, same 45-character path for old and new. A single-row-group run is
888 bytes as a `FileChunk` versus 920 as a `RowGroupInfo`; a three-group
coalesced run is 1120 versus 1072. A `BinItem` is 1888 bytes versus 1416
for the old flat `BinItem(path, size_bytes, run)`: the extra ~470 bytes
is the `FileInfo` instance it now points at instead of copying its two
fields. `BinItem`s are transient packing state, bounded by the open
bins, so this is a few hundred bytes per in-flight item. The manifest's
Arrow column is unchanged at 36 bytes per row, because the struct has
the same fields under new names.

### What changes

1. **`interfaces/file_manifest.py`.** New `FileChunk(unit_ids, num_rows,
size_bytes, fully_matched=True, unit_sizes=(), unit_rows=())` with
`to_metadata()` / `from_metadata()`; `__post_init__` asserts a per-unit
breakdown is empty or one entry per unit. `create_chunk_metadata` and
its `TypeVar` are removed; the empty `ChunkMetadata` `TypedDict` becomes
a `Dict[str, Any]` alias, since a row's chunk metadata is now always
`None` or `FileChunk.to_metadata()`.
2. **`formats/parquet/`.** `parquet_footer_types.py` is deleted:
`RowGroupInfo` and `ParquetRowGroupChunkMetadata` are gone, and the one
survivor, `FileChunks` → `ChunkedFile(file: FileInfo, row_groups:
Tuple[FileChunk, ...])`, moves next to the `FooterReader` that builds
it. `footer_reader.py` builds one `FileChunk` per row group and
`_read_and_chunk` / `read_footers` take `FileInfo`;
`parquet_row_group_coalescing.py` merges with `dataclasses.replace`;
`footer_file_indexer.py` emits `run.to_metadata()` via
`_chunked_file_to_manifest` with `size_bytes` = the run's
projection-scoped uncompressed size, as before. `parquet_file_reader.py`
reads `unit_ids` and `size_bytes`, and drops the `"uncompressed_size" in
chunk` key check, since a non-`None` row always has the keys now.
Docstrings in `parquet_file_chunking_utils.py` follow.
3. **`common/indexing_utils.py`,
`common/non_sampling_file_indexer.py`.** `PathContents.files` and
`_get_file_infos` produce `FileInfo`; `OrderedFileResult` loses its
duplicate `file_path`.
4. **`common/online_bin_packer.py`.** `BinItem(file: FileInfo, run:
Optional[FileChunk])`, with `size_bytes` a property (the run's bytes,
else the file size); `run is None` is a whole-file row. Splitting a run
slices the `FileChunk`; a sealed bin merges a file's runs back into one
`FileChunk` row. `Bin.total_uncompressed_size` → `total_bytes`. Two
behaviour details: a whole-file row now comes out of the packer as a
whole-file row again (it used to come out claiming
`row_group_ids=(0,)`), and every packed row keeps the on-disk
`__file_size` the listing gave it (a chunk row used to carry the run's
bytes there; nothing reads `__file_size` after the packer).
5. **README.** One paragraph under "Adding a format": an indexer that
lists `FileChunk` rows can hand them to `OnlineBinPacker` as they are.
6. **Tests.** `test_online_bin_packer.py` builds rows directly and
imports nothing from `formats/`; its `coalesce_row_groups` cases move
verbatim to a new `test_parquet_row_group_coalescing.py`, since they are
Parquet's; two tests added (whole-file rows, on-disk size kept).
`test_chunk_metadata.py` becomes a `FileChunk` round-trip and invariant
test. `FileInfo` / renamed fields in `test_footer_reader.py`,
`test_read_units.py`, `test_synthesized_columns.py`,
`test_parquet_datasource_v2.py`, `test_file_indexer.py` and
`tests/datasource/test_read_parquet_v2.py`.

## Additional information

Not a duplicate: no open PR generalises the packer's row or unifies the
listing types. ray-project#66121 and ray-project#65887 both touch these files under the
pre-ray-project#66497 paths and will need a rebase either way; ray-project#66121 adds a second
size field to the old Parquet row; on this PR it needs no new field,
since `size_bytes` is whatever the indexer records and the
decoded-or-fallback choice belongs in the footer indexer's
`_chunked_file_to_manifest`. Its footer-indexer changes will see
`ChunkedFile.file.path` and `read_footers(list[FileInfo])` rather than
tuples.

Checks run locally from this branch (macOS, `~/ray/.venv`):

```
pytest -q python/ray/data/tests/unit/datasource_v2 \
          python/ray/data/tests/datasource_v2/test_footer_reader.py  # 193 passed
pytest -q python/ray/data/tests/datasource/test_read_parquet_v2.py   # 37 passed
```

`ruff`, `black` and `pydoclint` at the pre-commit pins are clean on
every changed file; `pyrefly` 0.51.0 with `pyarrow==24.0.0` reports no
errors in the changed files. `grep -r datasource_v2.formats interfaces/
common/` is empty.

Written with Claude Code; I reviewed every changed line and ran the
tests above.

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 Fable 5.1 <[email protected]>
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 16, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

Again, you can always ask for help on our discussion forum or Ray's public slack channel.

Thanks again for your contribution!

@github-actions github-actions Bot closed this Oct 31, 2026
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 stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants