Skip to content

[Data] Migrate CSV datasource to DatasourceV2 - #65743

Closed
400Ping wants to merge 7 commits into
ray-project:masterfrom
400Ping:data/migrate-csv-datasource-v2
Closed

400Ping wants to merge 7 commits into
ray-project:masterfrom
400Ping:data/migrate-csv-datasource-v2

Conversation

@400Ping

@400Ping 400Ping commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

Description

Migrate ray.data.read_csv() to the DataSourceV2 ListFiles -> ReadFiles
pipeline while preserving the existing public API and DataSourceV1 behavior.

This PR:

  • splits large, uncompressed CSV files at record boundaries without duplicating
    rows, including CRLF and quoted-field inputs;
  • keeps CSV schema discovery dynamic so columns and promoted types first seen
    outside the bounded sample are preserved rather than dropped or rejected;
  • rejects duplicate physical column names before name-based alignment can
    silently replace their values with nulls;
  • avoids copying a serialized schema into every chunk and performs boundary
    discovery in one forward pass per file, including giant-record coalescing;
  • preserves file/chunk order when execution_options.preserve_order=True;
  • retains Snappy stream handling and whole-file fallbacks for compressed or
    otherwise non-chunkable inputs;
  • propagates named Ray remote parameters and maintains path, partition,
    filtering, and block-count options.

Related issue

Closes #65651

Additional information

@400Ping 400Ping added data Ray Data-related issues data:datasources labels Aug 26, 2026
@400Ping 400Ping self-assigned this Sep 7, 2026
Signed-off-by: 400Ping <[email protected]>
goutamvenkat-anyscale pushed a commit that referenced this pull request Sep 21, 2026
…Metadata` as the two bases every datasource extends (#66312)

## Description

Sits between `[1/6]` (#66066) and `[2/6]` in the DSv2 Reorg series,
stacked
on #66066; the diff shows both until that one merges.

`DataSourceV2` asks every datasource for a PyArrow `filesystem`, a list
of
`file_extensions` and a file `shuffle`. Those only mean something when
Ray
walks a filesystem to find the files. A source whose indexer already
knows its
data, such as Iceberg or a database, had to return `None` for all three
just to
satisfy the contract. This PR gives the base class two subclasses and
every
datasource extends one of them. No behavior change for Parquet.

```mermaid
classDiagram
    class DataSourceV2 {
        <<abstract>>
        paths()*
        _get_file_indexer()*
        schema_needs_file_sample()*
        infer_schema(sample)*
        create_scanner(schema, filesystem, ...)*
    }
    class FileDataSourceV2 {
        <<abstract>>
        filesystem()* never None
        file_extensions() = None
        shuffle() = None
    }
    class DataSourceWithMetadata {
        <<abstract>>
        schema_needs_file_sample() = False
    }
    DataSourceV2 <|-- FileDataSourceV2 : Ray lists files through a filesystem
    DataSourceV2 <|-- DataSourceWithMetadata : the source finds its own data
    FileDataSourceV2 <|-- ParquetDatasourceV2
    DataSourceWithMetadata <|-- IcebergDatasourceV2 : later, same for Delta and SQL
```

### Changes

1. `FileDataSourceV2`: `filesystem` abstract and never `None`;
`file_extensions` and `shuffle` default `None`. The three members leave
   the base class. `ParquetDatasourceV2` extends it.
2. `DataSourceWithMetadata`: `schema_needs_file_sample` defaults to
`False`, since
   the schema comes from the same metadata as the listing.
3. `_read_datasource_v2` reads the three file members from a
`FileDataSourceV2`, passes `None` for a `DataSourceWithMetadata`, and
rejects a
   class that extends the base directly.
4. Contract tests in `tests/unit/datasource_v2/test_datasource_v2.py`.

## Additional information

Not a duplicate: no open PR changes the `DataSourceV2` class hierarchy.
The
open CSV migration (#65743) is a plain file format and would extend
`FileDataSourceV2` after a rebase.

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

```
pytest -q tests/unit/datasource_v2                     # 126 passed
pytest -q tests/datasource/test_read_parquet_v2.py     # 37 passed
pytest -q tests/datasource/test_parquet.py             # 246 passed, 13 skipped, 34 errors
```

The 34 errors are moto `s3_fs` fixture setup errors (`moto_server` not
on
PATH), identical on master. `ruff`, `black` and `pydoclint` at the
pre-commit
pins are clean; `pyrefly` reports the same 61 pre-existing errors as the
base
commit.

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 Sep 22, 2026
… datasource package (#66357)

## Description

Third PR of the DSv2 Reorg series, on top of #66312 (`[1.5/6]`).

`datasource_v2` still imports helpers from the legacy
`parquet_datasource.py`.
This PR moves them into `datasource_v2`, points the legacy module at
their new
homes, and adds a lint so the dependency only ever points one way:
legacy may
depend on V2, never the reverse. No behavior change.

### What moved where

1. Eight Parquet-only helpers (legacy tensor check, nested-type fallback
sizing, leaf-column resolution, row-group size, the Arrow chunk limit)
move
   from the legacy module into new `datasource_v2/parquet_utils.py`.
2. The predicate helpers `combine_predicates` and
`_split_predicate_by_columns`
move from the legacy module into `datasource_v2/pushdown.py`, which is
`logical_optimizers.py` renamed because it now holds all pushdown code.
3. `_compute_row_hashes` moves from the legacy module into
   `datasource_v2/readers/file_reader.py`.
4. The legacy `parquet_datasource.py` imports all of the above back from
V2.
5. New lint `ci/lint/check_datasource_v2_imports.py` fails on any V2
import of
the legacy package, module-level or function-level, wired into
pre-commit
   and `lint.sh`.

### Code changes summarized

- The Parquet extension list moves to `PARQUET_FILE_EXTENSIONS` in
  `parquet_utils.py`; both `ParquetDatasourceV2` and the legacy
  `ParquetDatasource._FILE_EXTENSIONS` read it from there.
- `check_for_legacy_tensor_type` gained type annotations on the move.
- `parquet_file_reader.py` imports the moved helpers at module level
instead
of inside the fallback method. The function-level import existed to
dodge an
  import cycle through the legacy module and its twenty Ray imports;
`parquet_utils.py` imports only `typing` and `pyarrow`, so the reason is
  gone. Import errors now surface at load time rather than on the first
oversized nested-type file, and tests can patch the names on the reader
  module.
- `_compute_row_hashes` lives in `file_reader.py` rather than
`parquet_utils.py` because it is not Parquet code: it makes the
`row_hash`
column for every format, and the generic `FileReader` is its only V2
caller.
- The legacy module's `ray.data.expressions` import shrinks from
`BinaryExpr, Expr, Operation` to `Expr`. The two dropped names were used
only
by the moved `_split_predicate_by_columns`; `Expr` still annotates a
legacy
  method parameter.
- One `test_parquet.py` test patches the nested-type helper at both the
legacy
path and the reader path, since each reader now resolves it through its
own
  module.

## Additional information

Not a duplicate: no open PR moves these helpers or adds an import
boundary for
`datasource_v2`. #65743 (CSV on DatasourceV2) touches the package but
not
these modules.

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

```
python ci/lint/check_datasource_v2_imports.py                                  # clean
pytest -q tests/unit/datasource_v2 tests/unit/test_parquet_predicate_split.py  # 159 passed
pytest -q tests/datasource/test_read_parquet_v2.py                             # 37 passed
pytest -q tests/test_execution_optimizer_limit_pushdown.py                     # 28 passed
```

`ruff`, `black` and `pydoclint` at the pre-commit pins are clean;
`pyrefly`
reports the same 60 pre-existing errors as master.

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]>
owenowenisme pushed a commit to owenowenisme/ray that referenced this pull request Sep 23, 2026
…Metadata` as the two bases every datasource extends (ray-project#66312)

## Description

Sits between `[1/6]` (ray-project#66066) and `[2/6]` in the DSv2 Reorg series,
stacked
on ray-project#66066; the diff shows both until that one merges.

`DataSourceV2` asks every datasource for a PyArrow `filesystem`, a list
of
`file_extensions` and a file `shuffle`. Those only mean something when
Ray
walks a filesystem to find the files. A source whose indexer already
knows its
data, such as Iceberg or a database, had to return `None` for all three
just to
satisfy the contract. This PR gives the base class two subclasses and
every
datasource extends one of them. No behavior change for Parquet.

```mermaid
classDiagram
    class DataSourceV2 {
        <<abstract>>
        paths()*
        _get_file_indexer()*
        schema_needs_file_sample()*
        infer_schema(sample)*
        create_scanner(schema, filesystem, ...)*
    }
    class FileDataSourceV2 {
        <<abstract>>
        filesystem()* never None
        file_extensions() = None
        shuffle() = None
    }
    class DataSourceWithMetadata {
        <<abstract>>
        schema_needs_file_sample() = False
    }
    DataSourceV2 <|-- FileDataSourceV2 : Ray lists files through a filesystem
    DataSourceV2 <|-- DataSourceWithMetadata : the source finds its own data
    FileDataSourceV2 <|-- ParquetDatasourceV2
    DataSourceWithMetadata <|-- IcebergDatasourceV2 : later, same for Delta and SQL
```

### Changes

1. `FileDataSourceV2`: `filesystem` abstract and never `None`;
`file_extensions` and `shuffle` default `None`. The three members leave
   the base class. `ParquetDatasourceV2` extends it.
2. `DataSourceWithMetadata`: `schema_needs_file_sample` defaults to
`False`, since
   the schema comes from the same metadata as the listing.
3. `_read_datasource_v2` reads the three file members from a
`FileDataSourceV2`, passes `None` for a `DataSourceWithMetadata`, and
rejects a
   class that extends the base directly.
4. Contract tests in `tests/unit/datasource_v2/test_datasource_v2.py`.

## Additional information

Not a duplicate: no open PR changes the `DataSourceV2` class hierarchy.
The
open CSV migration (ray-project#65743) is a plain file format and would extend
`FileDataSourceV2` after a rebase.

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

```
pytest -q tests/unit/datasource_v2                     # 126 passed
pytest -q tests/datasource/test_read_parquet_v2.py     # 37 passed
pytest -q tests/datasource/test_parquet.py             # 246 passed, 13 skipped, 34 errors
```

The 34 errors are moto `s3_fs` fixture setup errors (`moto_server` not
on
PATH), identical on master. `ruff`, `black` and `pydoclint` at the
pre-commit
pins are clean; `pyrefly` reports the same 61 pre-existing errors as the
base
commit.

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]>
@AarryaSaraf

Copy link
Copy Markdown
Contributor

Thank you for your contribution! A large refactoring of DSv2 has been done. Can you rebase your changes on top of that? I'll take a look once done.

nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…Metadata` as the two bases every datasource extends (ray-project#66312)

## Description

Sits between `[1/6]` (ray-project#66066) and `[2/6]` in the DSv2 Reorg series,
stacked
on ray-project#66066; the diff shows both until that one merges.

`DataSourceV2` asks every datasource for a PyArrow `filesystem`, a list
of
`file_extensions` and a file `shuffle`. Those only mean something when
Ray
walks a filesystem to find the files. A source whose indexer already
knows its
data, such as Iceberg or a database, had to return `None` for all three
just to
satisfy the contract. This PR gives the base class two subclasses and
every
datasource extends one of them. No behavior change for Parquet.

```mermaid
classDiagram
    class DataSourceV2 {
        <<abstract>>
        paths()*
        _get_file_indexer()*
        schema_needs_file_sample()*
        infer_schema(sample)*
        create_scanner(schema, filesystem, ...)*
    }
    class FileDataSourceV2 {
        <<abstract>>
        filesystem()* never None
        file_extensions() = None
        shuffle() = None
    }
    class DataSourceWithMetadata {
        <<abstract>>
        schema_needs_file_sample() = False
    }
    DataSourceV2 <|-- FileDataSourceV2 : Ray lists files through a filesystem
    DataSourceV2 <|-- DataSourceWithMetadata : the source finds its own data
    FileDataSourceV2 <|-- ParquetDatasourceV2
    DataSourceWithMetadata <|-- IcebergDatasourceV2 : later, same for Delta and SQL
```

### Changes

1. `FileDataSourceV2`: `filesystem` abstract and never `None`;
`file_extensions` and `shuffle` default `None`. The three members leave
   the base class. `ParquetDatasourceV2` extends it.
2. `DataSourceWithMetadata`: `schema_needs_file_sample` defaults to
`False`, since
   the schema comes from the same metadata as the listing.
3. `_read_datasource_v2` reads the three file members from a
`FileDataSourceV2`, passes `None` for a `DataSourceWithMetadata`, and
rejects a
   class that extends the base directly.
4. Contract tests in `tests/unit/datasource_v2/test_datasource_v2.py`.

## Additional information

Not a duplicate: no open PR changes the `DataSourceV2` class hierarchy.
The
open CSV migration (ray-project#65743) is a plain file format and would extend
`FileDataSourceV2` after a rebase.

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

```
pytest -q tests/unit/datasource_v2                     # 126 passed
pytest -q tests/datasource/test_read_parquet_v2.py     # 37 passed
pytest -q tests/datasource/test_parquet.py             # 246 passed, 13 skipped, 34 errors
```

The 34 errors are moto `s3_fs` fixture setup errors (`moto_server` not
on
PATH), identical on master. `ruff`, `black` and `pydoclint` at the
pre-commit
pins are clean; `pyrefly` reports the same 61 pre-existing errors as the
base
commit.

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
… datasource package (ray-project#66357)

## Description

Third PR of the DSv2 Reorg series, on top of ray-project#66312 (`[1.5/6]`).

`datasource_v2` still imports helpers from the legacy
`parquet_datasource.py`.
This PR moves them into `datasource_v2`, points the legacy module at
their new
homes, and adds a lint so the dependency only ever points one way:
legacy may
depend on V2, never the reverse. No behavior change.

### What moved where

1. Eight Parquet-only helpers (legacy tensor check, nested-type fallback
sizing, leaf-column resolution, row-group size, the Arrow chunk limit)
move
   from the legacy module into new `datasource_v2/parquet_utils.py`.
2. The predicate helpers `combine_predicates` and
`_split_predicate_by_columns`
move from the legacy module into `datasource_v2/pushdown.py`, which is
`logical_optimizers.py` renamed because it now holds all pushdown code.
3. `_compute_row_hashes` moves from the legacy module into
   `datasource_v2/readers/file_reader.py`.
4. The legacy `parquet_datasource.py` imports all of the above back from
V2.
5. New lint `ci/lint/check_datasource_v2_imports.py` fails on any V2
import of
the legacy package, module-level or function-level, wired into
pre-commit
   and `lint.sh`.

### Code changes summarized

- The Parquet extension list moves to `PARQUET_FILE_EXTENSIONS` in
  `parquet_utils.py`; both `ParquetDatasourceV2` and the legacy
  `ParquetDatasource._FILE_EXTENSIONS` read it from there.
- `check_for_legacy_tensor_type` gained type annotations on the move.
- `parquet_file_reader.py` imports the moved helpers at module level
instead
of inside the fallback method. The function-level import existed to
dodge an
  import cycle through the legacy module and its twenty Ray imports;
`parquet_utils.py` imports only `typing` and `pyarrow`, so the reason is
  gone. Import errors now surface at load time rather than on the first
oversized nested-type file, and tests can patch the names on the reader
  module.
- `_compute_row_hashes` lives in `file_reader.py` rather than
`parquet_utils.py` because it is not Parquet code: it makes the
`row_hash`
column for every format, and the generic `FileReader` is its only V2
caller.
- The legacy module's `ray.data.expressions` import shrinks from
`BinaryExpr, Expr, Operation` to `Expr`. The two dropped names were used
only
by the moved `_split_predicate_by_columns`; `Expr` still annotates a
legacy
  method parameter.
- One `test_parquet.py` test patches the nested-type helper at both the
legacy
path and the reader path, since each reader now resolves it through its
own
  module.

## Additional information

Not a duplicate: no open PR moves these helpers or adds an import
boundary for
`datasource_v2`. ray-project#65743 (CSV on DatasourceV2) touches the package but
not
these modules.

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

```
python ci/lint/check_datasource_v2_imports.py                                  # clean
pytest -q tests/unit/datasource_v2 tests/unit/test_parquet_predicate_split.py  # 159 passed
pytest -q tests/datasource/test_read_parquet_v2.py                             # 37 passed
pytest -q tests/test_execution_optimizer_limit_pushdown.py                     # 28 passed
```

`ruff`, `black` and `pydoclint` at the pre-commit pins are clean;
`pyrefly`
reports the same 60 pre-existing errors as master.

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]>
@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
@400Ping 400Ping removed the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 16, 2026
chia7712 pushed a commit to opensource4you/readme that referenced this pull request Oct 21, 2026
Add a nomination under `fellowship/ray/`

Suggested level: 20k

Highlights from 2026-09-01 to 2026-10-11:
- [Contribution](https://github.com/opensource4you/readme/blob/main/fellowship/ray/fellow-contribution/400Ping/September/report.md)
- Landed the Ray Data roadmap feature task-based shuffle v2 for `sort()`: ~35% faster, ~24% lower object-store peak and no spilling compared with v1 on an 11.92 GiB sort ([#64875](ray-project/ray#64875))
- As a senior contributor who can already approve Ray Data PRs, helps the community a lot by reviewing and guiding other contributors, for example, reviewing other fellows' PRs ([#66878](ray-project/ray#66878), [#65278](ray-project/ray#65278))
- Spent over a month with Ray Data maintainer Balaji researching how to cut Ray Data release test launch time([#66284](ray-project/ray#66284))
- Migrating the CSV datasource to DataSourceV2, with a design doc and a 5-PR stack for the Ray Data maintainers ([#65743](ray-project/ray#65743))
goutamvenkat-anyscale pushed a commit that referenced this pull request Nov 5, 2026
…Source V2 (#67725)

## Summary

Adds a shared chunker so CSV and JSONL files on DataSource V2 can be
split into byte ranges, letting several read tasks share one large file.
Listing reads no file bytes; each read task moves its range to whole
lines. The reader that uses it is a skeleton, with step-by-step
docstrings and `NotImplementedError` bodies, showing where CSV and JSONL
plug in. No datasource uses these classes yet, so nothing user-visible
changes.

## Changes

1. **Byte-range chunking.** Files:
`datasource_v2/common/line_chunking.py`, `_internal/util.py`.
Listing cuts a file into fixed ranges of `chunk_size` bytes using only
its size. At read time, `read_line_aligned` moves a range to whole lines
by one rule: a line belongs to the chunk holding its first byte. A chunk
skips the partial line it starts in and finishes the line that crosses
its end, all in one ranged read. For example, `b"a\nbb\nc\n"` with
`chunk_size=3` reads as `b"a\nbb\n"`, `b"c\n"` and `b""`, which joined
give back the file. Byte sizes are typed with a new `NumBytes` alias in
`_internal/util.py`.

2. **Listing rows.** Files:
`datasource_v2/common/line_chunk_file_indexer.py`,
`datasource_v2/common/non_sampling_file_indexer.py`.
`NonSamplingFileIndexer`'s listing loop now asks a new
`_chunk_metadatas_of_file(file_info)` how many rows each file gets; the
default is one whole-file row, so existing indexers are unchanged.
`LineChunkFileIndexer` overrides only that method and returns one row
per chunk. Each row carries a `FileChunk` whose single unit id is the
chunk index. A 300 MiB file with `chunk_size=128 MiB` becomes three rows
(128, 128 and 44 MiB), which `OnlineBinPacker` packs unchanged. A file
that fits in one chunk, or whose extension marks it compressed, stays
one whole-file row. Row counts aren't known before reading, so chunks
carry `num_rows=0, fully_matched=False`.

3. **A read hook for units whose fragment needs IO to build.** Files:
`datasource_v2/common/file_reader.py`.
A pyarrow fragment over a CSV path always scans the whole file, so a
chunk has to be downloaded and wrapped as an in-memory fragment first.
`FileReader` builds fragments while planning, serially and without
retry, so the read loop now calls a new
`_iter_unit_tables(fragment_to_read, scanner_kwargs)` per unit. Its
default calls `_iter_fragment_tables` exactly as before, so Parquet and
ORC are unchanged. An override runs inside the existing retry loop and
scan threads, so chunk downloads run in parallel and retry per chunk.

4. **Reader skeleton.** Files:
`datasource_v2/common/line_chunkable_file_reader.py`.
`LineChunkableFileReader(FileReader)` lays out the read path. It makes
one read unit per chunk without IO. It then fetches the chunk's lines,
wraps them as an in-memory pyarrow fragment, and scans that fragment
with the same projection, filter and limit as whole files. One hook,
`_make_chunk_fragment`, holds what differs by format: the CSV version
takes column names from the plan-time schema for chunks after the first,
and at byte 0 checks that the header lists the schema's columns in the
same order.

A read task holds up to `chunk_size` of raw text while parsing. The file
header describes the change to make if that ever matters.

## Data flow

```mermaid
flowchart TD
    subgraph Before
        subgraph B_IO["IO: datasource_v2/common"]
            B1["FileReader read loop"] -->|"whole-file fragment"| B2["_iter_fragment_tables"]
        end
    end
    subgraph After
        subgraph A_IO["IO: datasource_v2/common"]
            A6["NonSamplingFileIndexer listing loop"] -->|"_chunk_metadatas_of_file"| A0["LineChunkFileIndexer"]
            A0 -->|"one row per chunk, packed by OnlineBinPacker"| A1["FileReader read loop"]
            A1 -->|"read unit"| A3["_iter_unit_tables"]
            A3 -->|"default: whole-file fragment"| A2["_iter_fragment_tables"]
            A4["LineChunkableFileReader (skeleton)"] -. overrides .-> A3
            A4 -->|"read_line_aligned"| A5["line_chunking"]
        end
    end
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class A0,A3,A4,A5 added
    class A1,A6 changed
```

## Subsystems

IO (`_internal/datasource_v2/common/`).

## Testing

- **Lint.** `[email protected] check`, `[email protected] --check`,
`[email protected]` with the repo flags, and `git diff --check` are clean.
Pyrefly in CI's environment (Python 3.10, pyrefly 0.51.0, CI lock pins)
reports 0 errors.
- **Scratch script** run against this branch, not added to the tree:
- Over 2,979 random files, the chunks joined back into exactly the
original bytes. The files had lines longer than a chunk, cuts landing on
line starts, and some had no trailing newline.
- Every `chunk_size` from 1 to 25 on a 25-byte file gave back the file
the same way.
- A 1,000-row CSV split into 9 chunks and parsed through
`pds.CsvFileFormat().make_fragment(...)` gave rows 0–999 exactly once
each.
- A 100-byte file in 10-byte chunks with `max_paths_per_output=3` listed
as outputs of 3, 3, 3 and 1 rows, chunk ids 0–9 once each; plain
`NonSamplingFileIndexer` listing is unchanged.
- **Not covered.** No unit tests yet, and the existing DSv2 suites were
not run for the hook.

## Notes

- Related to, but not a duplicate of, #65743. That PR migrates
`read_csv` to DSv2, splits CSV only, and aligns boundaries both at
listing and at read. This PR is a shared chunker for CSV and JSONL that
reads nothing while listing.
- Written with AI assistance (Claude Code).

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

---------

Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@400Ping

400Ping commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Closing this since @NightWing1998 will work on this

@400Ping 400Ping closed this Nov 11, 2026
richardliaw pushed a commit that referenced this pull request Nov 18, 2026
…Source V2 (#67907)

## Summary

Implements `LineChunkableFileReader`, the skeleton from #67725, so a CSV
or JSONL file split into byte-range chunks can be read one chunk per
read unit. Nothing uses it yet: the CSV and JSON datasources come in the
next two PRs of this stack. To avoid a second copy of the planning and
scan loops, it also moves them into hooks on `FileReader`, which
`ParquetFileReader` now uses too, with no change in behavior.

## Before

`LineChunkableFileReader` had three methods that raised
`NotImplementedError`, and #67725 shipped no unit tests.
`FileReader._get_fragments_to_read` held the whole-file loop, and
`ParquetFileReader` repeated that loop with its own chunk fan-out.
`FileReader._iter_fragment_tables` hard-wired the scan schema.
`LineChunkFileIndexer` decided whether a file was compressed with
`infer_compression(path)`. That returns `None` for `.br` and for
upper-case extensions such as `.CSV.GZ`, so those compressed files were
split into byte ranges.

## After

- `FileReader._get_fragments_to_read` now owns the per-row loop and
calls two hooks: `_get_whole_file_fragment` and `_get_chunk_fragments`.
The default `_get_chunk_fragments` ignores chunk metadata, so readers
that don't chunk read as before. `ParquetFileReader` overrides both
hooks with its existing logic: row-group slicing, and the footer
`num_rows` read under `_with_io_retry`.
- `LineChunkableFileReader._get_chunk_fragments` makes one read unit per
chunk without IO: `ReadUnit(id=f"{path}#chunk{i}", index=i)`, with
`unit_start_row` set to the chunk's first byte. Unsplit files take the
base `_get_whole_file_fragment`.
- `_iter_unit_tables` fetches the chunk's whole lines with
`read_line_aligned`. It runs inside `FileReader`'s retry loop and scan
threads, so chunks download in parallel and retry on their own. The
format hook `_make_chunk_fragment` then wraps the lines as an in-memory
fragment.
- A whole uncompressed file of at most `chunk_size` bytes is read with
one request and takes the same path. Files open through their fragment,
which knows the size from the listing. Larger and compressed files keep
`FileReader`'s streaming path.
- `FileReader._iter_fragment_tables` takes its scan schema from a new
`_get_scan_schema` hook, whose default is unchanged: the caller schema,
else the fragment's physical schema. `LineChunkableFileReader` overrides
only that hook, so each fragment is scanned with the types pyarrow
infers for it, as V1 infers types per file.
- The scan pins the fragment's physical schema, which pyarrow infers
from the first block (1 MiB by default). So `_make_chunk_fragment` must
parse its bytes as one block, with `block_size` from
`one_block_size(lines)`, and the types then come from every row.
`one_block_size` returns the buffer's byte length, floored at 1 and
capped at pyarrow's int32 limit; a larger caller `block_size` changes
neither the parse nor the peak memory.
- Columns the scan reads that the fragment lacks are null-filled: the
projected columns, or without a projection, the plan-time file columns.
- `row_hash` row numbers start at each chunk's first byte. They're
unique, but they depend on `chunk_size`, as the docs now say. Only
`read_parquet` exposes `include_row_hash` today.
- Batches go through `raise_on_pickle_object_columns`.
- `LineChunkFileIndexer` keeps `.br` and upper-case compressed
extensions whole.

```mermaid
flowchart TD
    subgraph Before
        subgraph B_IO["IO: datasource_v2/common"]
            B0["FileReader: whole-file loop + scan loop"]
            BP["ParquetFileReader: own planning loop"]
            B1["LineChunkableFileReader (skeleton, NotImplementedError)"]
            B2["LineChunkFileIndexer: infer_compression(path)"]
        end
    end
    subgraph After
        subgraph A_IO["IO: datasource_v2/common"]
            subgraph A_FR["Component: FileReader"]
                F1["_get_fragments_to_read: per-row loop"] --> F2["_get_whole_file_fragment"]
                F1 --> F3["_get_chunk_fragments"]
                F4["_iter_fragment_tables: scan loop"] --> F5["_get_scan_schema"]
            end
            F2 -.override.-> AP1["ParquetFileReader: footer num_rows"]
            F3 -.override.-> AP2["ParquetFileReader: row-group slices"]
            F3 -.override.-> A1["LineChunkableFileReader: one unit per chunk, no IO"]
            F5 -.override.-> A4["LineChunkableFileReader: per-fragment types, null-fill"]
            A1 --> A2["_iter_unit_tables: read_line_aligned in scan threads, small files in one read"]
            A2 --> A3["_make_chunk_fragment (format hook, one block)"]
            A5["LineChunkFileIndexer: case-insensitive, .br compressed"]
        end
    end
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class A1,A2,A3,A4,F2,F3,F5 added
    class A5,F1,F4,AP1,AP2 changed
```

## Subsystems

IO (`_internal/datasource_v2/common/` and `formats/parquet/`). The new
reader and the indexer fix carry the behavioral change. The `FileReader`
and `ParquetFileReader` edits move existing code behind hooks; Parquet's
behavior is unchanged, checked by the Parquet V2 tests below.

## Testing

- `pytest
python/ray/data/tests/unit/datasource_v2/test_line_chunking.py` (new):
33 passed. It covers:
- chunks joining back into the original file for every `chunk_size` over
300 random files, with probe sizes of 1, 4 and 64 KiB;
- indexer rows, with compressed, `.br` and upper-case extensions kept
whole;
- reads through a minimal JSONL subclass: each row exactly once,
per-chunk types, null-filled projection with and without a schema, and
unit ids and offsets;
- a key first seen after the first MiB, and whole numbers then decimals,
each read split and whole. All four cases fail with a default-block
reader;
  - a small file opened once;
- a chunk of only blank lines, which the hook may skip by returning no
fragment;
- `one_block_size`: the buffer length, floored at 1 for an empty buffer
and capped at `2**31 - 1`.
- `pytest python/ray/data/tests/unit/datasource_v2
python/ray/data/tests/unit/datasource/test_pickle_gate_coverage.py`:
1035 passed, 168 skipped. This includes the Parquet reader and
`row_hash` unit tests, which run through the new hooks.
- `pytest python/ray/data/tests/datasource/test_orc.py
python/ray/data/tests/datasource/test_parquet.py`: 477 passed, 13 failed
(`large_string` vs `string` schemas, plus `test_orc_roundtrip[*-2]`).
Run at this PR and at its parent, the result is the same, down to the
failing test ids.
- `pytest python/ray/data/tests/datasource/test_read_parquet_v2.py`: 147
passed, 1 failed.
`test_read_parquet_v2_retries_transient_filesystem_errors` fails the
same way on the parent commit, with `No module named
'test_read_parquet_v2'` in a Ray worker, so it doesn't come from this
change.
- `pre-commit run` on the changed files: clean.

## Notes

- Not a duplicate. This fills in #67725's skeleton; no open PR
implements `LineChunkableFileReader`. #65743 migrates `read_csv` with
its own chunker; the CSV PR in this stack supersedes it.
- Written with AI assistance (Claude Code).

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

---------

Signed-off-by: Dhruvil Shah <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
NightWing1998 added a commit that referenced this pull request Nov 23, 2026
…asks

read_csv now runs on DataSource V2 when use_datasource_v2 is on (the
default). A large uncompressed file is listed as byte-range chunks
(LineChunkFileIndexer) and each chunk is read by its own task, so one big
CSV no longer bottlenecks a single task. Files stay whole when
newlines_in_values is set, read_options skips rows, the encoding isn't
UTF-8, or the file is compressed. arrow_open_stream_args and CSV options
other than read/parse/convert options go to V1.

- LineChunkableDatasourceV2: shared base for CSV and JSONL datasources.
- CsvDatasourceV2, CsvScanner, CsvFileReader. Column types are inferred per
  chunk, as V1 infers them per file.
- Each split file's chunks are named from that file's own header, read once
  while listing, so a file whose columns are in another order, or that also
  holds a partition column, reads correctly.
- RoundRobinPartitioner sizes read tasks with a new OnDiskSizeEstimator:
  bytes on disk, as V1 sizes CSV reads, with a chunk row weighing its own
  bytes rather than its file's. Nothing is read while listing. With
  preserve_order the partitioner fills one bucket at a time.
- Reads go through the retrying filesystem, so a transient IO error retries
  only the failing chunk.
- Snappy decompression moves to a module function shared by V1 and V2.
- Doctest outputs for read_csv on V2, and a strict-xfail test that pins the
  known quoted-newline gap.

Supersedes #65743; credit to its author for the CSV-on-DSv2 groundwork.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Dhruvil Shah <[email protected]>
sampan-s-nayak pushed a commit that referenced this pull request Nov 23, 2026
…ead tasks (#67904)

## Summary

`read_csv` runs on DataSource V2 when `use_datasource_v2` is on (the
default). A large uncompressed CSV file is split into byte ranges with
the line chunker from #67725, and separate read tasks read them, so one
big file no longer runs in a single task. Where V2 falls back to V1 or
behaves differently, see [Gaps with V1](#gaps-with-v1).

## Before

`read_csv` always used V1 `CSVDatasource`, which reads each file whole
in one task. A 1 GiB CSV is read by one task.

## After

- **Routing.** `read_csv` builds `CsvDatasourceV2` and goes through
`ListFiles -> ReadFiles`. It falls back to V1 in the cases listed under
[Falls back to V1](#falls-back-to-v1).
- **Splitting.** `CsvFileIndexer` lists a large uncompressed file as
`RAY_DATA_LINE_CHUNK_BYTES` (128 MiB) chunks, reading only its header
line. A file stays whole in the cases listed under [Read whole, not
split](#read-whole-not-split).
- **Header.** A chunk after the first has no header line.
`CsvFileIndexer` reads each split file's header line once and stores the
column names in that file's chunk rows. The reader parses the file's
later chunks with those names, so each file uses its own header, as in
V1. That covers:
- a file whose columns are in a different order from the sampled files;
- a file that also holds its partition column (`country=US/a.csv` with a
`country` column). The path value must equal the file's values, as in
V1, or the read raises `ValueError`.

The first 32 split files (`RAY_DATA_CSV_HEADER_BATCH_SIZE`) read their
headers inline in the listing task, so a few large files pay no actor
startup. Further header reads are dispatched to a pool of `HeaderReader`
Ray actors — the same protocol Parquet footer readers use:
SPREAD-scheduled actors (8 by default), files sent in batches (32 by
default), round-robin, with two batches in flight per actor so manifest
assembly never waits unless every batch is still reading. The pool is
made when the first file past the inline headers is listed, so a dataset
with few split files starts no actors. Each read goes through the
retrying filesystem, so a transient IO error retries that file instead
of failing the listing. `max_restarts`/`max_task_retries` are 10, so an
actor death or OOM re-runs its batch. `RAY_DATA_CSV_HEADER_NUM_ACTORS=0`
reads the headers inline in the listing task; that pool feeds one
GET-sized range read per file, not one per read task, which matters for
object stores. Knobs: `RAY_DATA_CSV_HEADER_NUM_ACTORS` (8),
`RAY_DATA_CSV_HEADER_IO_CONCURRENCY` (32),
`RAY_DATA_CSV_HEADER_BATCH_SIZE` (32).
- **Partitioning.** Hive/directory partition keys resolve through the
same shared helper Parquet, ORC and Text use, over every sampled file's
path. A file column with a partition key's name goes through V1's
`_add_partitions_to_table` unchanged: the path value is cast to the file
column's type and compared, a null path value matches only an all-null
column, and a mismatch raises `ValueError`. That check is in
`FileReader._apply_partition_values`, which CSV and JSON reach; Parquet
and ORC don't, because their dataset schema leaves the partition keys
out and a same-named file column is never read.
- **Types.** Each chunk is parsed as one pyarrow block, so its types
come from all of its rows, not just its first MiB. Types are inferred
per chunk, as V1 infers them per file, and unified afterwards.
- **Unknown size.** A file whose size the filesystem doesn't report,
such as an HTTP file without `Content-Length`, is listed as a whole file
and read as one stream, as in V1. Its size stays unknown (`NaN`) through
task sizing, and the reader takes sizes from the listing instead of
asking an open file for its size, which a streaming file can't report.
- **Task sizing.** `RoundRobinPartitioner` sizes read tasks with a new
`OnDiskSizeEstimator`: bytes on disk, as V1 sizes CSV reads, with a
chunk weighing its own bytes. Sizing reads nothing. With
`preserve_order`, tasks fill one at a time in listing order, so a file's
chunks stay in order.
- **Filters.** Filter pushdown stays off, as in V1.
- **Errors.** Both CSV read errors include pyarrow's own error
(`Original error: ...`). A failing piece of a split file no longer
claims a quoted newline is the cause: it lists a mistyped value or a row
with the wrong number of columns first (fix the file, or pass
`ConvertOptions(column_types=...)`) and names a quoted newline as one
possible cause (pass `ParseOptions(newlines_in_values=True)`).
- **Snappy.** Snappy files still read: V2 decompresses through
`read_snappy_buffer` in `common/line_chunkable_file_reader.py` (where
the stacked JSON PR also reads it from), which unwraps the retrying
filesystem before calling `_decompress_snappy`, the module function this
PR extracts for V1, so the Hadoop filesystem underneath applies Hadoop
framing.
- **Shared base.** `LineChunkableDatasourceV2` holds what CSV and JSON
share. The JSON PR in this stack uses it.
- **Reader.** `CsvFileReader` overrides `_get_fragments_to_read` only to
record each split file's column names, then calls the base template that
#67907 shares with Parquet. It sizes each chunk's `block_size` with
`one_block_size(lines)`, and a chunk's parse failure raises with
pyarrow's error and the likely causes (see Errors and the known
limitation).

```mermaid
flowchart TD
    subgraph Before
        subgraph B_API["API: read_api.read_csv"]
            B1["CSVDatasource (V1)"] -->|"one task per file"| B2["pyarrow.csv.open_csv"]
        end
    end
    subgraph After
        subgraph A_API["API: read_api.read_csv"]
            A0{"use_datasource_v2 and V2-supported args"}
        end
        subgraph A_IO["IO: datasource_v2"]
            A1["CsvDatasourceV2 (LineChunkableDatasourceV2)"] --> A2["CsvFileIndexer: 128 MiB chunks, no IO"]
            A2 --> H["HeaderReader: first 32 split files inline,<br/>the rest in an actor pool (SPREAD, 8), batched + retried"]
            H --> A3["RoundRobinPartitioner + OnDiskSizeEstimator"]
            A3 --> A4["CsvScanner -> CsvFileReader (LineChunkableFileReader)"]
        end
        A0 -->|yes| A1
        A0 -->|no| A5["CSVDatasource (V1)"]
        H -. "actors killed after listing" .- A2
    end
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class A1,A2,A3,A4,H added
    class A0 changed
```

## Gaps with V1

V2 reads CSV the same way V1 does in most cases. The cases below are
where it doesn't: V1 still runs, V2 runs without splitting, or V2 runs
and gives a different result.

### Falls back to V1

`read_csv` builds the V1 `CSVDatasource` when any of these holds:

| Condition | Note |
|---|---|
| `use_datasource_v2` is off |
`DataContext.get_current().use_datasource_v2 = False`, or
`RAY_DATA_USE_DATASOURCE_V2=0` before importing Ray. |
| `arrow_open_stream_args` is set | For example `{"compression":
"gzip"}`. |
| a CSV option other than `read_options`, `parse_options` or
`convert_options` is passed | For example `memory_pool`. |

### Read whole, not split

These files read on V2 but as one read task per file, as in V1:

- `parse_options.newlines_in_values` or `parse_options.escape_char` is
set;
- `read_options` skips rows;
- the encoding isn't UTF-8;
- the file is compressed (gzip, snappy, and so on);
- the file's size is unknown, such as an HTTP file without
`Content-Length`: it reads as one stream, as in V1, and read-task sizing
treats its size as unknown (`NaN`).

### Behaves differently from V1

| | V1 | V2 |
|---|---|---|
| `Dataset.input_files()` | The file paths. | `[]`: files are listed at
execution, not planning. Parquet, ORC and Text on V2 do the same. The
`input_files` docstring example now uses `read_binary_files` (V1). |
| `override_num_blocks=N` on a small file | The read task splits its
output into N blocks (`ReadCSV->SplitBlocks(N)`). | N only sets how
files and chunks are dealt to read tasks, so one small file is 1 block.
`SetReadParallelismRule` sets the split factor for V1 `Read` ops only,
and `plan_read_files_op` has no equivalent. Parquet on V2 has the same
gap. |
| `LogicalPlan.initial_num_blocks()` before execution | A count. |
`None`, because listing runs at execution. |
| Block count under `target_max_block_size` | Sized from estimated
in-memory bytes. | Sized from the chunks' bytes on disk, so the rows are
the same but boundaries differ. A 9.5 MiB file at a 3 MB target gives 3
blocks on V2 and 4 on V1. |
| Operator and task names | `ReadCSV`, `ReadCSV->MapBatches(...)`. |
`ListFiles` and `ReadFilesCsvV2`. Anything keyed on the names (stats
output, metrics, tests) changes. |
| Memory per read task | Streams with `open_csv` and holds about a block
at a time. | Reads a split chunk, or a whole file that fits in one
chunk, into memory and parses it as one block: peak about 1.1 GiB per
task at the default 128 MiB chunk (about 420 MiB at 32 MiB), independent
of file size, and chunks in one task add up. Whole files that stream
(`newlines_in_values`, unknown size) stay at about 270 MiB. Tune with
`RAY_DATA_LINE_CHUNK_BYTES`; streaming a chunk with `open_csv` is not
done here. |
| `include_columns` naming a column a file lacks | The read of that file
raises (`Column ... in include_columns does not exist in CSV file`). |
The file's rows get `null` for the column, with no error. A file in the
schema sample that lacks it still raises at planning, as in V1. |
| Schema before execution | Not known; the repr printed
`Dataset(num_rows=?, schema=...)`. | Known at planning, so the repr
prints the schema table. It is inferred from about the first 1 MiB of up
to 16 sampled files, so it's a guess. Types are inferred per chunk, so
one file's pieces can produce different types for the same column (V1
infers per file), unified downstream. |

### Tests that stay V1-only

- `test_splitblocks.py::test_small_file_split_v1` is pinned to V1,
because it asserts the V1 task names and the `override_num_blocks` split
above. V2 has no equivalent test. The Parquet counterpart
(`test_parquet.py::test_max_block_size_none_respects_override_num_blocks`)
is skipped on V2 for the same reason.

### Known limitation: newlines inside CSV values

Splitting assumes every newline byte ends a row. That's false for:

- a raw newline inside a quoted value (`"line1⏎line2"`, valid RFC 4180);
- a raw newline after `escape_char`, when one is set.

A two-character `\n` (a backslash, then `n`) contains no newline byte
and isn't affected.

Files whose parse options set `newlines_in_values` or `escape_char` are
read whole, so only a file with a quoted newline and the default parse
options can hit this. It takes a file larger than
`RAY_DATA_LINE_CHUNK_BYTES` (128 MiB) and a chunk boundary falling
inside such a value; the chunk after the boundary then starts mid-value.
Two outcomes:

- **If the piece's rows don't fit the header's column count, pyarrow
raises**, and the error shows pyarrow's message and lists the usual
causes. It names a quoted newline as one of them, with the fix
`parse_options=pyarrow.csv.ParseOptions(newlines_in_values=True)`, which
reads files whole.
- **If stray rows happen to match the column count, pyarrow parses them
and the read returns wrong rows without failing.** In a repro, a 50-row
file came back as 51 rows: `(25, 'line1\n')` plus a bogus `(null,
'line2"')`. This case stays a known gap, with a `TODO` in
`CsvDatasourceV2._can_split_files`: detecting an unclosed quote at a
chunk boundary would need a scan of each chunk's bytes or a second pass
over every file. Support for quoted newlines in split reads is left to a
follow-up.

- **JSON Lines** isn't affected: a JSON string can't hold a raw newline,
and pyarrow rejects one.

## Data flow

How one `read_csv` moves through planning, listing and reading. Chunk 0
parses its own header; later chunks use the column names the listing
read from the same file.

```mermaid
sequenceDiagram
    autonumber
    participant D as Driver (read_csv)
    participant L as ListFiles task<br/>CsvFileIndexer
    participant H as HeaderReader actor pool
    participant P as RoundRobinPartitioner
    participant R as ReadFiles task<br/>CsvFileReader
    participant S as Storage (S3 or local)
    participant O as Downstream operators

    Note over D,S: Planning, on the driver
    D->>S: list until 16 files
    D->>S: inspect each sampled file's first block (about 1 MiB)
    D->>D: schema = sampled columns + partition and path columns
    D->>R: CsvScanner carries the schema, options and chunk_size

    Note over L,H: Execution: listing
    L->>S: list every file with its size
    L->>L: chunk arithmetic per file, no IO
    loop each batch of split files (round-robin, 2 in flight per actor)
        L->>H: read_headers(batch of files)
        H->>S: read each file's header line (line holding byte 0), retried per file
        S-->>H: name,id
        H-->>L: column names per file
    end
    L->>L: one row per 128 MiB chunk with column_names [name, id] and one whole-file row per small or compressed file
    L->>H: ray.kill: the pool dies with the listing task
    L->>P: manifest rows
    P->>P: weigh each row by its own bytes on disk
    P->>R: one manifest bucket per read task

    Note over R,S: Execution: reading, each unit in a scan thread, retried on failure
    R->>R: keep column_names per file, then plan units without IO<br/>(base template, one unit per chunk from LineChunkableFileReader)
    loop each unit
        alt chunk 0
            R->>S: one ranged read [0, end + 64 KiB)
            S-->>R: whole lines, header included
            R->>R: parse as one block with the user's ReadOptions
        else chunk i after the first
            R->>S: one ranged read [start - 1, end + 64 KiB)
            S-->>R: whole lines (a line belongs to the chunk holding its first byte)
            R->>R: parse as one block with column_names from the listing<br/>(a parse failure raises with pyarrow's error and the likely causes)
        else small uncompressed file
            R->>S: one read of the whole file
            R->>R: parse as one block, header from the bytes
        else compressed, large or unknown-size file
            R->>S: pyarrow streams it, decompressing by extension (snappy in memory)
        end
        R->>R: scan with the fragment's own types and null-fill missing columns
        R->>R: check partition columns against the file's own, add the rest and the path column
        R->>O: Arrow blocks, types unified downstream
    end
```

## Subsystems

IO (behavior change: `_internal/datasource_v2/`), API (routing in
`read_api.py`), plus small refactors reusing V1 snappy handling
(`datasource/file_based_datasource.py`), the shared partitioning
resolution, and the reader actor-pool protocol, now one implementation
shared with the Parquet footer indexer (`common/actor_pool.py`,
`listing_utils.batch_file_infos`). No Parquet behavior changes: same
actor scheduling, batch size, window and teardown, verified by the
existing footer tests.

## Testing

- `pytest python/ray/data/tests/unit/datasource_v2
python/ray/data/tests/unit/datasource/test_pickle_gate_coverage.py`:
1509 passed, 226 skipped. The new `test_csv_datasource_v2.py` covers:
  - split files read exactly once;
  - per-chunk types;
  - headerless files;
- a file holding its own partition column, first or last in the header;
- a file column that differs from its partition value raising, with or
without a projection that selects the column;
- a file column that differs from its partition value raises, and a null
path value matches only an all-null column (which used to fail the cast
of the path value to a null type);
- a split file named from its own header when its column order differs
from the sample;
- each split file's column names in its chunk metadata (`HeaderReader`,
as a plain class); the actor pool is covered end to end, and a listing
of a few split files, or of only small files, provisions none of it;
  - types from every row of a chunk larger than 1 MiB, split and whole;
  - the whole-file conditions, including `escape_char`;
- a boundary inside a quoted value raising with the `newlines_in_values`
hint, and the hint shown only for a column-count error;
  - `include_columns`, split and whole, in file and in requested order;
- unknown size: batching keeps size-less rows, a `NaN` weight, no header
read for an unknown size, and a whole-file read that never asks the file
for its size;
  - gzip and snappy;
  - V1's error message;
- partition keys resolved from a file later than the first sample, and
with no sample;
  - chunk weighting and `preserve_order`;
  - V1/V2 routing.
- `pytest
python/ray/data/tests/datasource_v2/test_csv_header_listing.py`: 1
passed. 20 small files split into 64-byte chunks, headers read by a
2-actor pool with batches of 3; assert row count, the union of column
names, and every row of every column.
- `pytest python/ray/data/tests/datasource/test_csv.py`, now run under
V1 and V2: 42 passed. 4 failed, the four `test_csv_roundtrip[*-2]`
params, under both V1 and V2. They fail on V1 too in my environment
(`'numpy.ndarray' object has no attribute 'columns'`).
- `-k http_file_system`: 16 passed (V1 and V2, `no-size` and
`no-ranges`, 1 or 2 paths, fsspec or auto-resolved filesystem), modelled
on `test_text.py::test_fsspec_http_file_system`.
- The new V2 tests cover a split file with hive partitions and
`include_paths`, `preserve_order` across two split files, and a split
file whose column order differs from the sampled file.
- `pytest python/ray/data/tests/datasource/test_binary.py -k snappy` (V1
snappy path): 2 passed.
- `pytest python/ray/data/tests/datasource/test_orc.py
python/ray/data/tests/datasource/test_parquet.py`: 477 passed. 13
failed, the same 13 as before the #67907 refactor of the Parquet reader
(`large_string` vs `string` schemas, plus `test_orc_roundtrip[*-2]`).
- End to end, a 1.0 GiB single CSV file (33M rows) on a 10-CPU machine:

  | | Read tasks | Time | Rows |
  |---|---|---|---|
  | V1 | 1 | 5.6 s | count, sum, min and max of `id` |
  | V2 | 9 | 3.3 s | identical to V1 |

- Doctests for the updated examples (`pytest --doctest-modules -p
ray.data.tests.doctest_pytest_plugin`):
- `Dataset.input_files`, `Dataset.serialize_lineage`,
`Dataset.deserialize_lineage` and `read_csv`: passed.
- Both `to_tf` examples pass their repr lines, then need TensorFlow,
which my environment lacks. CI covers the rest.
- Fixes for the CI failures this PR caused, each passing locally:
-
`test_dataset_aggregrations.py::test_count_after_caching_after_execution`
asserts the V2 repr (`shape: (?,`) instead of `num_rows=?`;
- `test_splitblocks.py::test_small_file_split_v1`, renamed and pinned to
V1 (see Gaps);
- `test_size_estimation.py::test_split_read_csv` accepts 3 or 4 blocks
at a 3 MB target (`2 < len(nrow) < 5`), the Parquet test's bound.
- `pre-commit run` on the changed files: clean.

## Notes

- This supersedes #65743, which migrated `read_csv` to DSv2 with its own
chunker. This PR uses the shared CSV/JSONL chunker from #67725 instead,
so CSV and JSON Lines split files the same way. Thanks to @400Ping for
#65743 and the parity cases it worked through.
- Written with AI assistance (Claude Code).

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

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] Migrate CSV Datasource to Datasource v2

3 participants