Skip to content

[Data] Add a shared byte-range line chunker for CSV and JSONL on DataSource V2 - #67725

Merged
goutamvenkat-anyscale merged 4 commits into
ray-project:masterfrom
AarryaSaraf:dsv2-jsonl-csv-chunking
Nov 5, 2026
Merged

goutamvenkat-anyscale merged 4 commits into
ray-project:masterfrom
AarryaSaraf:dsv2-jsonl-csv-chunking

Conversation

@AarryaSaraf

@AarryaSaraf AarryaSaraf commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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

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
Loading

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, [Data] Migrate CSV datasource to DatasourceV2 #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

…Source V2

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@AarryaSaraf
AarryaSaraf marked this pull request as ready for review November 3, 2026 02:09
@AarryaSaraf
AarryaSaraf requested a review from a team as a code owner November 3, 2026 02:09
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

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

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 6590620. Configure here.

if paths:
yield FileManifest.construct_manifest(
paths=paths, sizes=sizes, chunk_metadatas=chunk_metadatas
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Chunk listing ignores unit exclusion

Medium Severity

LineChunkFileIndexer splits a file into multiple listing rows but never applies excluded_read_unit_ids to those chunks. The inherited filter only drops a file when its path is in the set, so per-chunk ids from a checkpoint cannot match and a resume would list and reread finished chunks.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6590620. Configure here.

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.

Right that LineChunkFileIndexer doesn't honor per-chunk ids yet, but nothing can produce one today: no datasource uses this indexer, and the reader that would report chunk ids (LineChunkFileReader) is a skeleton. Checkpoint support is out of scope for this PR; per-chunk exclusion belongs with the reader that defines the chunk id.

@Yin-1022

Yin-1022 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

A single chunked file can exceed max_paths_per_output

The threshold is checked only after all chunks of a file have been appended. As a result, a single large file can produce a manifest substantially larger than the configured output limit.

Minimal reproduction:

from ray.data._internal.datasource_v2.common.line_chunk_file_indexer import (
    LineChunkFileIndexer,
)
from ray.data._internal.datasource_v2.interfaces.file_indexer import FileInfo

indexer = LineChunkFileIndexer(
    chunk_size=100,
    ignore_missing_paths=False,
    max_paths_per_output=3,
    num_workers=1,
)

manifests = list(indexer.list_files_from_file_infos(
    [FileInfo(path="sample.jsonl", size=1000)],
    filesystem=None,
))

print([len(manifest) for manifest in manifests])

Actual: [10]

Expected: No manifest exceeding 3 rows (e.g., [3, 3, 3, 1]).

For large files with many chunks, this defeats the intended batching limit and could produce oversized manifest blocks during listing.

Could the threshold be checked after appending each chunk, rather than after processing the entire file?

@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Nov 3, 2026
@AarryaSaraf AarryaSaraf added the go add ONLY when ready to merge, run all tests label Nov 3, 2026
@AarryaSaraf

Copy link
Copy Markdown
Contributor Author

A single chunked file can exceed max_paths_per_output

The threshold is checked only after all chunks of a file have been appended. As a result, a single large file can produce a manifest substantially larger than the configured output limit.

Minimal reproduction:

from ray.data._internal.datasource_v2.common.line_chunk_file_indexer import (
    LineChunkFileIndexer,
)
from ray.data._internal.datasource_v2.interfaces.file_indexer import FileInfo

indexer = LineChunkFileIndexer(
    chunk_size=100,
    ignore_missing_paths=False,
    max_paths_per_output=3,
    num_workers=1,
)

manifests = list(indexer.list_files_from_file_infos(
    [FileInfo(path="sample.jsonl", size=1000)],
    filesystem=None,
))

print([len(manifest) for manifest in manifests])

Actual: [10]

Expected: No manifest exceeding 3 rows (e.g., [3, 3, 3, 1]).

For large files with many chunks, this defeats the intended batching limit and could produce oversized manifest blocks during listing.

Could the threshold be checked after appending each chunk, rather than after processing the entire file?

Good catch, thanks. Fixed.

Comment on lines +95 to +118
assert file_info.size is not None
if (
file_info.size <= self._chunk_size
or infer_compression(file_info.path) is not None
):
chunk_metadatas_of_file = [None]
else:
chunk_metadatas_of_file = [
chunk.to_metadata()
for chunk in split_into_line_chunks(
file_size=file_info.size, chunk_size=self._chunk_size
)
]
for chunk_metadata in chunk_metadatas_of_file:
paths.append(file_info.path)
sizes.append(file_info.size)
chunk_metadatas.append(chunk_metadata)
if len(paths) >= self._max_paths_per_output:
yield FileManifest.construct_manifest(
paths=paths, sizes=sizes, chunk_metadatas=chunk_metadatas
)
paths, sizes, chunk_metadatas = [], [], []

if paths:

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.

Instead of duplicating this logic of accumulating and flushing, can we not reuse this with the parent class

💬 via pr-lens

Comment on lines +507 to +510
Override this when the unit cannot be described as a pyarrow fragment,
for example a byte range of a CSV file. It runs inside the retry loop
and the scan threads, so IO done here is retried and parallel. Your
implementation should:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A little confused by this line. A pyarrow fragment just refers to a file path. Why would a CSV byte range not be representable by an arrow table?

💬 via pr-lens

"""
raise NotImplementedError

def _make_chunk_format(self, *, starts_at_file_start: bool) -> pds.FileFormat:

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 interface shouldn't be married to formats supported only by pyarrow. We should change this once we introduce a concept of an ArrowFileReader

💬 via pr-lens

self,
format: FileFormat,
*,
chunk_size: int,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Let's use a typealias here and have it refer to num_bytes. Let's put this type alias in a common util

💬 via pr-lens

from ray.data._internal.datasource_v2.interfaces.read_units import ReadUnitFragment


class LineChunkFileReader(FileReader):

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.

LineChunkableFileReader is a more apt name

💬 via pr-lens

The file's chunks, each holding one unit id: the chunk's index.
"""
assert chunk_size > 0, f"chunk_size must be positive, got {chunk_size}"
num_chunks = -(-file_size // chunk_size) # ceiling division

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 2 negatives?

💬 via pr-lens

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.

equivalent to ceil(). Ill change it coz its not super obvious.

lines = memoryview(data)[first_line_start : last_newline + 1]
elif fetch_end == file_size:
# The file's last line has no trailing newline.
lines = memoryview(data)[first_line_start:]

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.

Should be faster to do: b"".join((memoryview(data)[first_line_start:], tail))

💬 via pr-lens

break
newline = piece.find(b"\n")
if newline != -1:
pieces.append(piece[: newline + 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.

Why include the new line?

💬 via pr-lens

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.

To accomodate for the forward seeking logic I explained offline. Will Add to docstring to make it more obvious.

Comment on lines +88 to +89
chunk_size: Bytes per chunk. Must equal the indexer's
``chunk_size`` so a unit id maps to the same byte range.

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.

Say we move to an adaptive bin sizing strategy, then we will want to have chunk size be part of the manifest instead of being tied to the reader

💬 via pr-lens

"""
raise NotImplementedError

def _check_file_start(self, chunk_fragment: pds.Fragment, path: str) -> 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.

This should be part of a separate interface, and then the CSVReader should apply that interface with this method.

💬 via pr-lens

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit f492423 into ray-project:master Nov 5, 2026
6 checks passed
richardliaw pushed a commit that referenced this pull request Nov 17, 2026
## Description
`read_text` runs on DataSource v2 when `use_datasource_v2` is on (the
default).

### Before

`read_text` always used V1 `TextDatasource`, which reads each file whole
in one task and gets no
column, limit or partition pushdown.

### After

- **Routing.** `read_text` builds `TextDatasourceV2` and runs `ListFiles
-> ReadFiles`. It keeps
V1 when `arrow_open_stream_args` is set (no V2 equivalent) and for HTTP
paths or filesystems
  (V2 listing needs file sizes, which HTTP servers often omit).
- **Reading.** `TextReader` implements `Reader.read` directly, since
`pyarrow.dataset` has no
text format: read the file whole, decompress by extension, decode,
`str.splitlines()`, drop
whitespace-only lines when `drop_empty_lines`. Same semantics as V1.
Partition columns come
from the path; a file outside the partition directories gets nulls.
Empty files are listed and
  yield zero rows, as in V1.
- **Pushdowns.** Column pruning, limit and partition pruning. Filter
pushdown is not claimed, so
`Filter` stays above the read. A file whose path lacks a partition key
is kept at listing and
the reader evaluates the predicate on nulls before opening it, so
`col("year").is_null()`
  returns root files without opening the others.
- **Planning.** Fixed schema (`text` plus partition and `path` columns);
no file is opened while
  planning. Task sizing uses bytes on disk instead of a sampled read.

```mermaid
flowchart TD
    subgraph Before
        subgraph B_API["API: read_api.read_text"]
            B1["TextDatasource (V1)"] -->|"one task per file"| B2["FileBasedDatasource._read_stream"]
        end
    end
    subgraph After
        subgraph A_API["API: read_api.read_text"]
            A0{"use_datasource_v2 and arrow_open_stream_args is None"}
        end
        subgraph A_IO["IO: datasource_v2/formats/text"]
            A1["TextDatasourceV2 (FileDataSourceV2)"] --> A2["NonSamplingFileIndexer + RoundRobinPartitioner"]
            A2 --> A3["TextScanner (FileScanner + column/limit pushdown)"]
            A3 --> A4["TextReader.read: decode, splitlines, partition + path columns"]
        end
        A0 -->|yes| A1
        A0 -->|no| A5["TextDatasource (V1)"]
    end
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class A1,A2,A3,A4 added
    class A0 changed
```

## Related issues
None

## Additional information
**Not in this PR.** Splitting one text file across tasks (follow-up on
the line chunker from
#67725 once #67904 lands), and moving the partition/`path` finishing
step shared with
`MCAPReader` into a common helper.

---------

Signed-off-by: Jie-Kai Chang <[email protected]>
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]>
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 go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants