Skip to content

[Data](1/n) Implement the line-chunk reader for CSV and JSONL on DataSource V2 - #67907

Merged
richardliaw merged 5 commits into
masterfrom
dsv2-line-chunk-reader
Nov 18, 2026
Merged

richardliaw merged 5 commits into
masterfrom
dsv2-line-chunk-reader

Conversation

@NightWing1998

@NightWing1998 NightWing1998 commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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

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

🤖 Generated with Claude Code

@NightWing1998
NightWing1998 marked this pull request as ready for review November 11, 2026 16:51
@NightWing1998
NightWing1998 requested a review from a team as a code owner November 11, 2026 16:51

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request implements the core logic for line-chunked file reading in LineChunkableFileReader and LineChunkFileIndexer, enabling reading and parsing of CSV and JSONL files in byte-range chunks, and adds comprehensive unit tests. The review feedback identifies a potential crash in _iter_fragment_tables when no schema is provided and projected columns are missing from a chunk, a vulnerability in _is_compressed when paths contain query parameters or fragments, and suggests adding a test case to cover projection without a schema.

Comment on lines +97 to +100
def _is_compressed(path: str) -> bool:
# ``infer_compression`` misses upper-case extensions and ``.br``.
lowered = path.lower()
return infer_compression(lowered) is not None or lowered.endswith(".br")

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.

high

_is_compressed checks if the path ends with .br using lowered.endswith(".br"). However, if the path contains query parameters or fragments (e.g., S3 version IDs like s3://bucket/file.csv.br?versionId=123), endswith(".br") will return False. This will cause the indexer to incorrectly treat the Brotli-compressed file as uncompressed and attempt to split it, leading to corrupted reads or crashes. We should parse the URL/path to extract the actual file path before checking the extension.

Suggested change
def _is_compressed(path: str) -> bool:
# ``infer_compression`` misses upper-case extensions and ``.br``.
lowered = path.lower()
return infer_compression(lowered) is not None or lowered.endswith(".br")
def _is_compressed(path: str) -> bool:
# ``infer_compression`` misses upper-case extensions and ``.br``.
import urllib.parse
lowered = path.lower()
if infer_compression(lowered) is not None:
return True
return urllib.parse.urlparse(lowered).path.endswith(".br")

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.

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.

For a.csv.gz?versionId=1, infer_compression returns None and so does pyarrow.Codec.detect. pyarrow only picks a codec from the end of the path string, so the file is read as uncompressed bytes whether or not the path is split. a.csv.br?versionId=1 is the same. If _is_compressed parsed the URL, the indexer would skip splitting a path pyarrow still reads as plain bytes, and the two would disagree. Essentially today both indexer and pyarrow readers do not support the query params in s3 path. Without pyarrow support this does not change the outcome of the job. Hence I've skipped making this change.

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

Stale Bugbot comment from a previous run.

@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Nov 11, 2026

JSONL can't stream this way before pyarrow 20, which added
``pyarrow.json.open_json``.
- Column types are inferred per fragment, as V1 infers them per file, not

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The skeleton in #67725 said chunks would use the plan-time schema. With per-chunk inference, pyarrow guesses each chunk's types from its first 1 MB and then enforces them. A chunk that starts with a quiet stretch fails, so a file V1 reads can fail here once it is big enough to split. Sparse columns make this common.

Repro on pyarrow 23.0.1:

import pyarrow as pa, pyarrow.csv as pcsv, pyarrow.dataset as pds

rows = lambda n, note, price: "".join(f"{i},{'x'*60},{note},{price}\n" for i in range(n))
chunk = (rows(30000, "", "10") + rows(30000, "late", "7.5")).encode()
fmt = pds.CsvFileFormat(read_options=pcsv.ReadOptions(column_names=["id", "pad", "note", "price"]))
frag = fmt.make_fragment(pa.py_buffer(chunk))
frag.scanner(schema=frag.physical_schema).to_table()
# ArrowInvalid: CSV conversion error to null: invalid value 'late'

Pinning the plan-time schema reads this chunk fine. So does parsing the chunk as one block. Please pick one and make it the rule.

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.

thanks for pointing this out. I went with parsing each chunk as one block. That keeps per-chunk inference, as V1 infers per file, but makes it look at every row of the chunk.

I didn't pin the plan-time schema because it also rejects files the 16-file sample doesn't represent. For example, if price is int64 in the sample and 7.5 in another file, the read fails with a conversion error, while V1 reads that file.

The module docstring now states the rule, and _make_chunk_fragment documents it as the hook's contract, with one_block_size as the helper. The CSV reader in #67904 applies it, and the JSON reader in #67905 already did.

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.

One-block parsing fixes both repros, thanks.

One gap left: two chunks of the same file can get different types for a column. Ray merges int with float, and empty with anything. It can't merge number with text, or timestamp with text:

  • sort, groupby, repartition and iter_batches fail with Failed to unify schemas
  • write_parquet writes files with different types, and 01234 becomes 1234 in the numeric chunk

V1 gives one type per file, so it reads these files fine.

Could #67904 read a column as string in every chunk when the sample saw it as string? Please also fix the docstring line here that says these get promoted.

Not blocking this PR.

@abhishekverma-ray

Copy link
Copy Markdown
Contributor

The byte-range splitting and line alignment look solid, and the randomized join-back test is a good one.

My concerns are about how chunks get their column types: see my comments on the module docstring, on _make_chunk_fragment, and on the test reader. I checked those with plain pyarrow 23.0.1, restating the scan logic in _iter_fragment_tables, not by running this branch. Happy to share the scripts.

@NightWing1998
NightWing1998 force-pushed the dsv2-line-chunk-reader branch 2 times, most recently from 9336a70 to 91e36cb Compare November 12, 2026 12:01

@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 using default effort and found 2 potential issues.

There are 3 total unresolved issues (including 1 from previous review).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 91e36cb. Configure here.

@override
def _on_batch_read(self, table: pa.Table) -> None:
super()._on_batch_read(table)
raise_on_pickle_object_columns(table)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pickle-column reject test is missing

Medium Severity

⚠️ Externally read Arrow data may carry ray.data.arrow_pickled_object columns, which unpickle on access and execute arbitrary code. Call raise_on_pickle_object_columns(table) right after the read and add a reject test proving a planted pickle payload never runs. Blocks built in-process from Python values are exempt.

Additional Locations (1)
Fix in Cursor Fix in Web

Triggered by project rule: Bugbot Rules

Reviewed by Cursor Bugbot for commit 91e36cb. Configure here.

@NightWing1998

NightWing1998 commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

The byte-range splitting and line alignment look solid, and the randomized join-back test is a good one.

My concerns are about how chunks get their column types: see my comments on the module docstring, on _make_chunk_fragment, and on the test reader. I checked those with plain pyarrow 23.0.1, restating the scan logic in _iter_fragment_tables, not by running this branch. Happy to share the scripts.

Thanks for the review and the repros @abhishekverma-ray. Summary of the changes:

NightWing1998 added a commit that referenced this pull request Nov 12, 2026
Addresses review on #67907.

`LineChunkableDatasourceV2` used the resolved filesystem as is, so
listing, schema inference, the header read and chunk reads failed on the
first transient S3 error. V1 and `ParquetDatasourceV2` retry
`DataContext.retried_io_errors`, so it now wraps the filesystem in
`RetryingPyFileSystem` as they do.

Also updates the `print(ds)` output in the inspecting-data guide: a V2
CSV read knows its schema at planning, so the repr is the schema table.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Dhruvil Shah <[email protected]>

@abhishekverma-ray abhishekverma-ray left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approved. Please check my request regarding PR #67904.

@NightWing1998 NightWing1998 added the go add ONLY when ready to merge, run all tests label Nov 12, 2026

@override
def _get_fragments_to_read(
def _get_chunk_fragments(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why is this function name changing?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

the control loop got moved to the parent class FileReader._get_fragments_to_read as discussed in the previous review comments. so instead of over-riding the same function we are changing the name to get_chunk_fragments which holds the part we may want to handle per data source type.

NightWing1998 and others added 5 commits November 16, 2026 16:15
…e V2

Fill in LineChunkableFileReader, the skeleton from #67725: one read unit
per byte-range chunk, fetched with read_line_aligned inside the retry loop
and scan threads, then scanned as an in-memory fragment. Column types are
inferred per fragment, as V1 infers them per file, and plan-time columns a
fragment lacks are null-filled. Batches pass raise_on_pickle_object_columns.

LineChunkFileIndexer now keeps .br and upper-case compressed extensions
(e.g. .CSV.GZ) whole; infer_compression misses both, so they were split.

Adds the unit tests #67725 left out: chunk round-trips, indexer rows, and
reads through a minimal JSONL subclass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Dhruvil Shah <[email protected]>
…uest

Addresses review on #67907.

- A fragment's scan pins its physical schema, which pyarrow infers from
  the first block (1 MiB by default). A later value of another type then
  failed to convert, and a JSON key first seen later was dropped. The
  `_make_chunk_fragment` contract now asks for one block, with
  `one_block_size` as the helper, and the test reader follows it. Tests
  cover a key first seen after 1 MiB and whole numbers then decimals.
- A whole uncompressed file of at most `chunk_size` bytes is now read
  with one request and scanned like a chunk. Before, its schema and its
  scan each opened it. Files open through their fragment, which knows
  the size from the listing, so S3 skips the size lookup.
- `_iter_fragment_tables` also null-fills projected columns a fragment
  lacks, which matters when the reader has no schema.
- The docs say row numbers for `row_hash` depend on `chunk_size`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Dhruvil Shah <[email protected]>
…e-chunk reader

Addresses review on #67907.

- `FileReader._get_fragments_to_read` now owns the per-row loop and
  delegates to `_get_whole_file_fragment` and `_get_chunk_fragments`.
  `ParquetFileReader` and `LineChunkableFileReader` override those instead
  of repeating the loop.
- `FileReader._iter_fragment_tables` takes its scan schema from
  `_get_scan_schema`. The line-chunk reader overrides only that hook.
- `one_block_size` returns the buffer length, floored at 1 and capped at
  pyarrow's int32 limit. A larger caller `block_size` changes neither the
  parse nor the peak memory.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Dhruvil Shah <[email protected]>
Addresses review on #67907.

The reader tests compared `to_pylist()` results. They now sort the merged
table and compare the column against an explicit `pa.Array` through one
helper, so the assertions stay in pyarrow and don't depend on chunk order.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Dhruvil Shah <[email protected]>
…k lines

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Dhruvil Shah <[email protected]>
@richardliaw
richardliaw merged commit e63d850 into master Nov 18, 2026
6 checks passed
@richardliaw
richardliaw deleted the dsv2-line-chunk-reader branch November 18, 2026 02:21
columns = scanner_kwargs.get("columns")
if columns is None:
columns = (self._file_dataset_schema or pa.schema([])).names
missing_fields = [

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.

Pushed-down filter columns are never null-filled, so a chunk missing a filtered column fails the scan.

_get_scan_schema only null-fills columns named by the projection (or the plan schema), never the columns the pushed-down filter references.

scanner_kwargs always carries filter (FileReader.read builds it from self._predicate) and _iter_fragment_tables splats it into fragment.scanner(**scanner_kwargs, schema=...). Read a JSONL file where key b only appears in rows past the first chunk, with columns=["a"] and predicate b > 1: for chunk 0 physical_schema has no b, columns == ["a"] so missing_fields is empty, and the scanner raises pyarrow.lib.ArrowInvalid: No match for FieldRef.Name(b). Same with no projection and no caller schema — columns falls back to pa.schema([]).names == [], so no filter column is ever added. The module docstring was even edited to drop the word "filter", but the code still forwards it.

columns, so they null-fill instead of failing: the projected ones, or
without a projection, the plan-time file columns.
"""
physical_schema = fragment.physical_schema

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.

Dropping the _file_dataset_schema pin lets two chunks of one file return different Arrow types.

Column types are now inferred per chunk, diverging from the schema the plan advertised and from an explicit caller schema=.

test_reader_infers_types_per_chunk_and_null_fills_missing_columns asserts exactly this: x_types == {pa.int64(), pa.float64()} for a single file. ParquetScanner.create_reader passes schema=self.schema and Scanner.read_schema() advertises those types downstream. Blocks that violate it only survive where concat uses promote_types=True (ArrowBlockBuilder._combine_tables); transform_pyarrow.concat / concat_and_sort default to promote_types=False → pa.unify_schemas(promote_options="default") cannot merge int64 with double → ArrowSchemaUnificationError on a later sort/aggregate/shuffle. A user-supplied schema= to read_csv/read_json also no longer pins types at all, and a column absent from every fragment comes back typed null instead of its declared type.

for name in columns
if physical_schema.get_field_index(name) == -1
]
return pa.schema(list(physical_schema) + missing_fields)

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.

Emitting physical_schema + missing_fields lets blocks carry columns the plan never advertised.

Columns the fragment has but the plan-time schema does not are now emitted.

test_reader_reads_a_key_first_seen_after_the_first_mib reads key k that is deliberately absent from the passed schema [("i", int64), ("x", int64), ("pad", string)] and asserts it comes back. The base FileReader._get_scan_schema would have pinned the caller schema and dropped k. Downstream code built on Scanner.read_schema() (projection-pushdown validation, Dataset.schema(), reorder_columns_by_schema — which raises ValueError when the table has columns not in schema.names — and writing with a fixed output schema) now sees blocks wider than the declared schema.

The fragment knows the file's size from the listing, so opening it
through the fragment skips the filesystem's size lookup.
"""
if _is_compressed(fragment_to_read.unit.source):

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.

_read_small_file bypasses pyarrow's decompression and the format's read/parse/convert options.

It decides compression from the filename alone and reads raw bytes via fragment.open(), for every whole file at or under chunk_size.

pds.FileFragment.open() calls FileSource::Open(), not OpenCompressed(), so the bytes are undecoded. LineChunkFileIndexer's own docstring says to use NonSamplingFileIndexer "when arrow_open_stream_args forces a compression codec the file extension doesn't show" — but the reader has no such switch: with that indexer every row is a whole-file unit, every file ≤ chunk_size takes _read_small_file, _is_compressed(path) is False, and _make_chunk_fragment is handed raw gzip/zstd bytes to parse as text. The same shortcut also routes small files through _make_chunk_fragment instead of _make_format(), so any ParseOptions/ConvertOptions a subclass only wires into _make_format are silently skipped for small files and applied for large ones.

"""Fetch a chunk unit's whole lines; ``None`` when it holds no rows."""
unit = fragment_to_read.unit
with fragment_to_read.fragment.open() as file:
file_size = file.size()

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.

Recomputing the chunk byte range from the read-time file.size() breaks when the file changed since listing.

The listing size the manifest carries is available but discarded (_get_chunk_fragments receives file_size and documents it as "Unused").

A 100 MB file listed into 10 chunks at chunk_size=10 MB is truncated to 30 MB before the read task runs: chunk 5 calls line_chunk_byte_range(index=5, chunk_size=10MB, file_size=30MB) and trips assert 0 <= start < file_size — an AssertionError, which is not in ctx.retried_io_errors, so the task fails hard rather than surfacing a readable error (and under python -O the assert vanishes and read_at is called with a negative nbytes). If the file instead grew, every chunk but the last keeps its old range while the last chunk's end silently stretches to the new size, and bytes past num_listed_chunks * chunk_size are never read.

"""
if _is_compressed(fragment_to_read.unit.source):
return None
with fragment_to_read.fragment.open() as file:

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.

_read_small_file opens the file just to read file.size(), then throws the handle away.

That's an extra open for every whole-file unit larger than chunk_size.

For a whole-file row of an uncompressed 1 GB CSV, _iter_unit_tables opens the file, calls size(), returns None, closes it, and then super()._iter_unit_tables → _iter_fragment_tables → fragment.scanner(...) opens it again. On S3 that is a wasted GetObject/open per fragment per retry. The size is already on the manifest (FileManifest.known_file_sizes, which _get_chunk_fragments receives as file_size and discards) and on the FileInfo the dataset was built from, so the branch can be decided without any IO.

]


def _is_compressed(path: str) -> bool:

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 belongs in infer_compression, not as a private helper on the indexer.

infer_compression in ray.data._internal.util is the shared helper (used by the V1 file datasources' open_input_stream(compression=...) path among others); all of its callers still return None for a.CSV.GZ and a.csv.br. line_chunkable_file_reader.py:75 now imports the underscore-private _is_compressed from the indexer module, inverting the reader→listing layering, when both already share line_chunking.py. Fixing infer_compression (lower-case the suffix, add br) would fix the indexer, the reader, and V1 in one place.

Returns:
The units to scan for this row, in order.
"""
return [self._get_whole_file_fragment(fragment)]

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.

Making "ignore the chunk metadata and read the whole file" the inheritable default silently duplicates rows.

Pair any non-chunking FileReader subclass (e.g. OrcFileReader) with an indexer that emits chunk metadata — a 4-chunk file produces 4 manifest rows, each resolving to [self._get_whole_file_fragment(fragment)], so the file's rows are emitted 4 times with no warning and no error. Making this the silent default (rather than raising, or asserting the reader opted into chunking) hides the mismatch at the one layer that can detect it.

Returns:
``len(lines)``, within pyarrow's bounds of 1 and 2**31 - 1.
"""
return max(1, min(len(lines), _MAX_BLOCK_SIZE))

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.

one_block_size silently caps at 2**31 - 1, breaking the invariant it exists to guarantee.

_make_chunk_fragment's contract is "the fragment's schema must come from every line" because the scan pins physical_schema. With chunk_size above 2 GiB, one_block_size returns the cap, pyarrow splits the chunk into multiple blocks, inference again sees only the first block, and the exact failures the docstring warns about return: a JSON key first seen after the cap is dropped and a later value of another type fails to convert — silently, with no log line and no error.



# Rows past the first MiB, the default ``block_size`` pyarrow infers types from.
_EARLY_ROWS = [{"i": i, "x": 1, "pad": "y" * 100} for i in range(12_000)]

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 module lands in the size = "small" (60s) Bazel target but builds ~24k dicts at import time and runs a ~100k-iteration randomized loop.

python/ray/data/BUILD.bazel:35-47 globs tests/unit/**/test_*.py into py_test_module_list(size = "small", ...). _EARLY_ROWS / _LATE_ROWS (24,000 dicts, ~3 MB of JSON each when serialized) are evaluated at collection time for every test in the module; test_reader_reads_a_key_first_seen_after_the_first_mib and test_reader_reads_whole_numbers_then_decimals each write and parse that file twice; and test_chunks_join_back_into_the_file runs 300 files × up to 42 chunk sizes × 3 probe sizes, with probe_bytes=1 forcing _read_through_newline to advance one byte per request. Verified under plain pytest, not under the 60s small-test budget — this is a timeout/flake risk in CI.

eugenepaniot added a commit to eugenepaniot/ray that referenced this pull request Nov 19, 2026
…floop-input

* upstream/master:
  [Data][3/n] update progress bar on lineage reconstruction (ray-project#67366)
  [Data] Enable the Top-N rewrite by default and expose it on DataContext (ray-project#68329)
  [Data] Adaptively skip map-side partial aggregation for high-cardinality keys (ray-project#68118)
  [Core] Spawn specific servers without preexec_fn to fix intermittent startup crashes (ray-project#67947)
  [Serve] Stop the __wrapped__ walk at non-callables (ray-project#67117)
  [Data] Deflake test_read_parquet_v2 by cutting redundant Ray Data executions (ray-project#68318)
  [Data] Retry FooterReader actor deaths with Ray Core and yield footers in listing order (ray-project#67988)
  [Data] Fix order-dependent schema unification when a list<null> arm is present (ray-project#68259)
  [Serve] Make @serve.batch work when wrapped in another decorator (ray-project#68177)
  [serve] Deflake test_metrics_3 - record the batch queue length once a batch is taken (ray-project#68302)
  [serve] Drop completed requests from the multiplexed model ID index (ray-project#68085)
  [Data] Fix flaky test_hudi: read each table once instead of sorting in Ray Data, keep size small (ray-project#68162)
  [Data] Fix flaky test_context: start 2 Ray clusters instead of 5 and keep size small (ray-project#68161)
  [Data] Fix flaky test_kafka: use recent timestamps in test_read_kafka_datetime_partial_range (ray-project#68248)
  [Data] Iceberg DSv2 [2/5]: The listing-to-reading manifest for Iceberg (ray-project#67951)
  [Train] Report training errors when the post-mortem debugger raises a BaseException (ray-project#68317)
  [RLlib] Skip the PPOConfig docstring example that crashes the rllib doctest target (ray-project#68306)
  [Train] Support post-mortem debugging for training function errors (ray-project#68296)
  [train][1/n] Give each health probe its own timeout (ray-project#68191)
  [Data] Fix unifying a fixed-shape tensor array with a lower-ndim variable-shaped one (ray-project#67266)
  [Train] Add a guide to debugging failures and hangs (ray-project#68299)
  [Data] Persist BlockMetadata.num_rows and batch ray.get in _calculate_blocks_rows (ray-project#67662)
  [Data] Vectorize LeRobot delta segment preparation and validate index contiguity (ray-project#67845)
  [Data] Avoid full-DataFrame apply in _AbstractKBinsDiscretizer._transform_pandas (ray-project#67862)
  [doc] Refresh intersphinx inventory snapshots (ray-project#68303)
  [Data] Fix SimpleImputer on categorical columns in append mode and with existing category values (ray-project#67467)
  [Data] Replace O(N) list.pop(0) with deque.popleft() in PushBasedShuffleTaskScheduler (ray-project#67243)
  [Train] Reject an elastic ScalingConfig with max_workers=0 (ray-project#68218)
  [core][move semantics][3/n]Populate task args with is_move for movable refs (ray-project#66803)
  [core][sandbox] Remove the readonly option (ray-project#68088)
  [Data](1/n) Implement the line-chunk reader for CSV and JSONL on DataSource V2 (ray-project#67907)
  [Data] Set MIMALLOC_PURGE_DELAY=0 on random_shuffle to fix the pyarrow 25 OOM regression (ray-project#68151)
  [core] Quote each `uv run` argument in the uv runtime env hook (ray-project#68156)
  [core] Don't let gRPC cancel calls that wait over 30s in the server queue (ray-project#68210)
  [Data] Fix shuffle and join on native tensor columns with pyarrow 25+ (ray-project#68072)
  [serve][llm] Remove decode load progress (ray-project#68258)
  [ci] Bump sglang to 0.5.23 in release tests (ray-project#68250)
  [Core] Build the test auth token file locally so Windows tests can read it (ray-project#68262)
  [image] Bump EFA installer to 1.51.0 in CPU base-extra images (ray-project#67730)
  [serve] Observe the result of rank reassignment reconfigures (ray-project#67923)
  [Serve][Docs] Explain imperative vs declarative deploys and in-place updates from Python (ray-project#68243)
  [Data] (Fault tolerance) Ray Data lineage reconstruction docs (ray-project#68061)
  [RLlib] Add a multi-node footsies APPO memory release test (ray-project#67595)
  [Train] Remove local mode (ray-project#68239)
  [Data] Fix filtered Lance row-count metadata (ray-project#67228)
  [Serve][2/2] Propagate TracingConfig to proxies at startup (ray-project#65437)
  [Data] Fix synthesized path filtering in DataSourceV2 (ray-project#67079)
  [RLlib] Run the BCConfig Tune example one trial at a time to unblock the rllib doctest target (ray-project#68242)
  [Data][Delta DSv2][2/7] List Delta Lake table files from the log (ray-project#67888)
  [Data] Parallelize Parquet and ORC full-schema reads (ray-project#67542)
  [Data] Random Shuffle on Shuffle V2 Map/Reduce Operators (ray-project#68004)
  [Data] Propagate metadata prefetch thread failures to executor (ray-project#68171)
  [core] Send generator consumed-progress updates from io_service_ (ray-project#67160)
  [Data] Add @ray-data-connectors as codeowner for datasource/sinks files (ray-project#68154)
  [data][llm] Keep the prompt in vLLM error rows (ray-project#67665)
  [data][actor-only][3/n] Actor-only backend: operator fusion (ray-project#67699)
  [Data] Read text files on DataSource v2 (ray-project#68063)
  [Autoscaler][KubeRay] Never patch worker group replicas below minReplicas (ray-project#67332)
  [Serve] Show progress of updating (ray-project#67107)
  [core][test] Trigger usage-stats OOM test without exhausting host memory (ray-project#68009)
  [Serve] Remove unused RAY_SERVE_HAPROXY_INGRESS_RETRY_ON and RAY_SERV… (ray-project#68175)
  [Data] Implement lineage tracker garbage collection upon marking operator durable (ray-project#67788)
  [Core] Fix recovery suppression race in ObjectRecoveryManager (ray-project#64974)
  [serve] Pass grpc.so_reuseport to gRPC as an integer (ray-project#66816)
  [Autoscaler][v2] Preserve retry accounting when trimming status history (ray-project#67360)
  [doc] Refresh intersphinx inventory snapshots (ray-project#68069)
  [Doc] Add item to AGENTS.md to update documentation when modifying API-facing code. (ray-project#68204)
  [Train] Preserve `num_boost_round=0` and avoid mutating `callbacks` in legacy LightGBM/XGBoost trainers (ray-project#68145)
  [Train] Raise in prepare_data_loader instead of dropping a custom batch_sampler (ray-project#68201)
  [air] Return None in skip_exceptions when exc or StartTraceback cause is None (ray-project#68172)
  [Train] Fix `checkpoint_manager` to support metrics only reported in a validation function (ray-project#67909)
  [Train] Count elastic workers in resource units for fractional resources (ray-project#68139)
  [Data] Refactor Disk shuffle map to use map Operator (ray-project#67130)
  [core][move semantics][2/n] Change state to moved on consumption and add enforcements (ray-project#66767)
  [Data] Propagate labels to object-store SHUFFLE_V2 map/reduce tasks (ray-project#67135)
  feat(core): add Cambricon MLU resource support (ray-project#66368)
  [Data] Make `zero_copy_batch=False` copy default batches (ray-project#67154)
  [data] Fix Parquet filename suffix detection (ray-project#67156)
  [data] Fix docstring/behavior mismatches in read_json and Dataset.sort (ray-project#66927)
  [Data] Run video_object_detection.ray on T4s with more memory (ray-project#68149)
  [core][sandbox] Let a node override network="public" sandboxes' default resolvers (ray-project#67691)
  [Data] read_mcap: resolve each sample's steps and lay out its row (ray-project#67925)
  [Data] read_mcap: sample read inputs: TopicSpec, steps, match and samples checks (ray-project#67924)
  [Data] Keep a map task's buffered rows when max_errored_blocks skips its error; read past corrupt MCAP chunks (ray-project#67167)
  [core][move semantics][1/n] Adding consume_once flag in actor methods (ray-project#66620)
  [Data] Size the schema pin and the columns Ray adds in the Parquet decoded-size estimate [3/6] (ray-project#67838)
  [Serve][LLM][1/3] Token based autoscaling: track autoscaling workload in KV router (ray-project#67937)
  [Data] Add native direct reads for nonpartitioned Hive tables (ray-project#67114)
  [Train] Count elastic workers in resource units for fractional resources (ray-project#68139)
  [Data] Add `condition` to `Dataset.join` and extract equi-join keys from it (ray-project#67590)
  [data] Add Top-N execution (ray-project#66931)
  [build] Bazel 8.8.1: bump protobuf to v29.6, rules_java to 8.12.0 and gRPC to 1.69.0 (ray-project#66483)
  [build] Use Arena::Create and pin Java 8 bytecode ahead of protobuf 29 / rules_java 8 (ray-project#67720)
  [core][sandbox] Don't join a sandbox's cgroup on every exec (ray-project#67690)
  [Data] Run `training_ingest_regression_test` on Instances that can be Provisioned (ray-project#68110)
  [Data] Run Sort on Disk-based Shuffle under SHUFFLE_V2 (ray-project#67850)
  [core] Deflake tests that race on timing (ray-project#67717)
  [ci] Bump pypa manylinux2014 base image to 2026.10.22-0 for CPython 3.15 (ray-project#67285)
  [Data] Make Mcap Data Column Test Insensitive to Struct Field Order (ray-project#68109)
  [Data] read_mcap V2: cut large files where their log-time order holds (ray-project#67166)
  [core][sandbox] Commit sandbox as new registry image (ray-project#67972)
  [Data] read_mcap V2: read neighbouring chunks in one ranged request (ray-project#67930)
  [train][4/n] Wire WorkerProbes through the HealthManager (ray-project#67915)
  [train][3/n] Add WorkerProbe results and health reports to the HealthState (ray-project#67879)
  [Data] (Data fault tolerance ray-project#6/6) Add a manual release test for lineage reconstruction (ray-project#67519)
  [train][6/n] Act on health decisions in the Ray Train controller (ray-project#67856)
  [Train] Do not start an elastic worker group with zero workers (ray-project#68101)
  [Train] Keep the last checkpoint after a metrics-only report in local mode (ray-project#68070)
  [Data][2/n] Migrate GPU Shuffle to Unified Phase Metrics (ray-project#67359)
  [Data][Chkpt] Fix `ArrowInvalid` when loading large generated-ID checkpoints (ray-project#68065)
  [core][test] Create auth token in test_redis_wrong_password (ray-project#68014)
  [data][actor-only][2/n] Actor-only backend: promote task pools to actor pools (ray-project#67698)
  [Data] Fix typing mismatches in Dataset public API (ray-project#62077)
  [Data] read_mcap V2: carry read tasks' summary records in the manifest (ray-project#67929)
  [Data] Distinguish generated ID collisions with synthesized columns (ray-project#67164)
  [Data] Fix incorrect scale-up in rate-based autoscaler for custom resources (ray-project#66647)
  [Data][Delta DSv2][1/7] Shared Parquet and partitioning fixes for the Delta reader (ray-project#67887)
  [Data] Eliminate redundant aggregation shuffle (ray-project#67198)
  [Data] Raise minimum supported pyarrow to 23.0.0 and test up to 26.0.1 (ray-project#68005)
  [Train] Use the default validation timeout when a report's ValidationTaskConfig has none (ray-project#68045)
  [doc][train] Use the global batch size in the TensorFlow Train examples (ray-project#68006)
  [TPU] Default multi-slice MASTER_ADDR to slice 0 host 0 in SlicePlacementGroup (ray-project#67878)
  [Data] Estimate a Parquet row group's decoded Arrow bytes from its footer [2/6] (ray-project#67837)
  [Data] Predicate pushdown through joins: split conjuncts, derive one-sided OR weakenings (ray-project#67122)
  [Data] Add partition_filters to read_delta and take file sizes from the log (ray-project#67900)
  [Data] Stop writing Unity Catalog vended credentials to the environment (ray-project#67899)
  [Data] Raise an error for Delta tables with column mapping in write_delta (ray-project#67898)
  [Core] Add initial foundational configurations and flags for fork server (ray-project#67356)
  [core][sandbox] Image layers caching (ray-project#67874)
  [Doc][Train] Add device stream batch prefetching section to accelerator guide (ray-project#67779)
  [Train] Use user-defined train function name in training thread name and error stack traces (ray-project#64292)
  [serve][docs] Remove beta label from custom autoscaling policies (ray-project#68046)
  [core] Don't treat a gRPC client with calls in flight as idle (ray-project#67718)
  [train] Fix checkpoint sorting to support nested metrics (ray-project#59130)
  [train][5/n] Run ControllerProbes on the controller's node monitor (ray-project#67671)
  [Train] Rank a checkpoint without the score attribute as worst in min order (ray-project#67901)
  [Core][RuntimeEnv] Stream runtime environment package downloads (ray-project#67184)
  [core] Deflake `_run_hanging_command` tests (ray-project#67461)
  [Data] Add Gravitino Iceberg REST catalog provider (ray-project#67007)
  [Data] Fix mixed-root partition filtering in Parquet and ORC V2 (ray-project#67067)
  [core] Keep absl logging at ERROR unless GRPC_VERBOSITY is set (ray-project#67719)
  [Data][1/n]Add Shuffle Metrics Unification Instrumentation (ray-project#66968)
  [ci][release] Stop publishing Python 3.10 wheels and images (ray-project#67722)
  [serve] Copy the ASGI lifespan state into each request scope (ray-project#67844)
  [Serve][LLM][4/5] Support scale-to-zero application routing (ray-project#67087)
  [core][sandbox] Let GPU sandboxes request NVIDIA profiling capabilities (ray-project#67974)
  [Serve][LLM] Exclude LLMRouter from dashboard QPS (ray-project#67873)
  [Data] Read the Parquet SizeStatistics PyArrow doesn't expose [1/6] (ray-project#67836)
  Add perf metrics for 2.60.0 (ray-project#67727)
  [Observability / Train] Add Grafana Annotation support with Ray Train usage (ray-project#66958)

Signed-off-by: Eugene Paniot <[email protected]>

# Conflicts:
#	python/ray/data/_internal/planner/plan_udf_map_op.py
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.

4 participants