Skip to content

[Data] DSv2 Reorg [5.5/6]: Regroup datasource_v2 into interfaces/, common/ and formats/parquet/ - #66497

Merged
goutamvenkat-anyscale merged 10 commits into
ray-project:masterfrom
AarryaSaraf:dsv2-folder-layout
Sep 29, 2026
Merged

goutamvenkat-anyscale merged 10 commits into
ray-project:masterfrom
AarryaSaraf:dsv2-folder-layout

Conversation

@AarryaSaraf

@AarryaSaraf AarryaSaraf commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

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

AarryaSaraf and others added 4 commits September 25, 2026 13:00
…on/ and formats/parquet/

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…the moved listing files

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…gacy ParquetDatasource at its new module

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@AarryaSaraf
AarryaSaraf marked this pull request as ready for review September 25, 2026 20:28
@AarryaSaraf
AarryaSaraf requested a review from a team as a code owner September 25, 2026 20:28
@AarryaSaraf AarryaSaraf added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Sep 25, 2026

@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 performs a significant refactoring of the ray.data._internal.datasource_v2 module, primarily focusing on reorganizing files into a cleaner structure (common/, formats/, interfaces/). The review identified two potential issues: unnecessary object allocation in non_sampling_file_indexer.py when preserve_order is false, and a limitation in create_chunk_metadata regarding optional keys in TypedDict subclasses. I have kept both comments as they provide actionable improvements.

Comment on lines +301 to +308
for file_path, file_size in contents.files:
file_info_result = FileInfo(path=file_path, size=file_size)
if preserve_order:
add_result(
OrderedFileResult(
input_path_index=input_path_index,
file_path=file_path,
file_info=file_info_result,
)
add_result(
OrderedFileResult(
input_path_index=input_path_index,
file_path=file_path,
file_info=FileInfo(path=file_path, size=file_size),
)
else:
add_result(file_info_result)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Always wrapping every FileInfo in an OrderedFileResult introduces unnecessary object allocation and memory overhead when preserve_order is False (which is the default and most common case). For datasets with millions of files, this can significantly impact performance and memory usage.\n\nWe can avoid this regression by conditionally wrapping the results only when preserve_order is True, and using a type union/isinstance check to satisfy the type checker. Please also update the add_result type signature in process_fn (line 275) to Callable[[Union[OrderedFileResult, FileInfo]], None] and the yield loop (lines 329-330) to handle both types using isinstance.

            for file_path, file_size in contents.files:\n                file_info = FileInfo(path=file_path, size=file_size)\n                if preserve_order:\n                    add_result(\n                        OrderedFileResult(\n                            input_path_index=input_path_index,\n                            file_path=file_path,\n                            file_info=file_info,\n                        )\n                    )\n                else:\n                    add_result(file_info)

Comment on lines +28 to +36
required_keys = list(get_type_hints(cls).keys())

missing_keys = [key for key in required_keys if key not in kwargs]
if missing_keys:
raise ValueError(f"Missing required keys: {missing_keys}")

extra_keys = [key for key in kwargs if key not in required_keys]
if extra_keys:
raise ValueError(f"Unexpected keys: {extra_keys}")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The current implementation of create_chunk_metadata assumes all keys defined in the TypedDict are required. If a ChunkMetadata subclass defines optional keys (e.g., using total=False or NotRequired), this function will incorrectly raise a ValueError when those optional keys are missing.\n\nWe can fix this by using cls.__required_keys__ (with a fallback to all keys for compatibility) to identify required keys, and checking extra keys against all keys returned by get_type_hints(cls).

    all_keys = get_type_hints(cls)\n    required_keys = getattr(cls, \

@AarryaSaraf AarryaSaraf changed the title [Data] DSv2 Reorg [6/6]: Regroup datasource_v2 into interfaces/, common/ and formats/parquet/ [Data] DSv2 Reorg [5.5/6]: Regroup datasource_v2 into interfaces/, common/ and formats/parquet/ Sep 25, 2026
AarryaSaraf and others added 2 commits September 25, 2026 13:57
…der is set, as before the type fix

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
…icitly so CI's pyrefly accepts the moved files

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
path=p,
is_discovered_subdir=False,
input_path_index=i if preserve_order else None,
input_path_index=i,

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 changing?

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.

Thats a bug. Ill fix 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.

Looked further into it; I dont see a case where this makes a difference, but the code is quite complicated so I think ill change it back.

Comment on lines +4 to +10
from ray.data._internal.datasource_v2.interfaces.pushdown import (
ListFilesPushdown,
SupportsColumnPruning,
SupportsFilterPushdown,
SupportsLimitPushdown,
SupportsPartitionPruning,
)

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.

What's the point of this file if everything is moved out and you're just importing these modules?

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.

Certainly not everything being moved out; I did move a few things but theres a few still remaining here.

AarryaSaraf and others added 3 commits September 28, 2026 11:08
…traversal work items instead of always setting it

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
… the datasource_v2 README

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit 8ce3a09 into ray-project:master Sep 29, 2026
6 checks passed
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]>
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]>
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