Skip to content

[Data](2/n) Read CSV on DataSource V2, splitting large files across read tasks - #67904

Merged
sampan-s-nayak merged 6 commits into
masterfrom
dsv2-csv
Nov 23, 2026
Merged

sampan-s-nayak merged 6 commits into
masterfrom
dsv2-csv

Conversation

@NightWing1998

@NightWing1998 NightWing1998 commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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.

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.

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

  • 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 [Data](1/n) Implement the line-chunk reader for CSV and JSONL on DataSource V2 #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).

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
Loading

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.

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
Loading

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 [Data](1/n) Implement the line-chunk reader for CSV and JSONL on DataSource V2 #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

🤖 Generated with Claude Code

@NightWing1998
NightWing1998 removed this pull request from stack #67906 November 6, 2026 13:59
@NightWing1998
NightWing1998 marked this pull request as ready for review November 11, 2026 16:50
@NightWing1998
NightWing1998 requested a review from a team as a code owner November 11, 2026 16:50

@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 introduces LineChunkableDatasourceV2 and a concrete CsvDatasourceV2 implementation to support reading CSV files in byte-range chunks under the DataSourceV2 pipeline. It also updates routing logic in read_csv and adds comprehensive unit tests. The review feedback suggests several robustness and performance improvements: replacing an assertion with a graceful None check in infer_schema, defaulting optional PyArrow parameters in CsvFileReader to prevent potential AttributeErrors, and replacing copy.deepcopy with copy.copy for PyArrow options to avoid compatibility issues with C-extensions.

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

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

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]>
Base automatically changed from dsv2-line-chunk-reader to master November 18, 2026 02:21
@richardliaw
richardliaw requested a review from a team as a code owner November 18, 2026 02:21
@richardliaw

Copy link
Copy Markdown
Contributor

@NightWing1998 please address merge conflicts

)

@override
def _can_split_files(self) -> 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.

Splitting assumes every newline ends a row. So a file over 128 MiB with a newline inside a quoted value can come back with wrong rows and no error (your repro: 50 rows came back as 51). Since read_csv now uses V2 by default, could this fail loudly before it ships? Either land "proposed fix 1" here (a piece that ends inside an open quoted value raises with the newlines_in_values hint), or keep splitting opt-in until it lands. Could we also read files whole when parse_options.escape_char is set? An escaped newline breaks the same assumption.

One correction to the description: V1 doesn't read these files correctly once they're over pyarrow's 1 MiB block. pyarrow.csv.open_csv on an 8.5 MiB file with a quoted newline in each row raises "CSV parser got out of sync with chunker" (pyarrow 23.0.1). So the change is from a clear error to silently wrong rows, and that's my concern.

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.

I've added the hint to use newlines_in_values if we see a parse error. for escape_char, we are falling back to read whole files for now. if custom escape chars is a highly used feature we can take this up later to update the chunker.

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.

Following up: the silent case is still there (the strict xfail). With V2 as the default, any CSV over 128 MiB with a multi-line quoted value goes from a clear V1 error to wrong rows. Could we detect it, or keep splitting opt-in until we can?

One cheap check: count quote characters in each piece. An odd count means a cut fell inside a quoted value, so raise the newlines_in_values error. It took ~50 ms per 128 MiB in my test, against ~160 ms to parse it. A quote inside an unquoted value (like 5" pipe) would also trip it, which is why the error should name the workaround.

Comment thread python/ray/data/read_api.py Resolved

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

@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 1 potential issue.

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 5514d98. Configure here.

Comment thread python/ray/data/read_api.py Resolved
@abhishekverma-ray

Copy link
Copy Markdown
Contributor

What's still needed before we can delete V1 read_csv:

  1. Some options still send reads to V1. arrow_open_stream_args does, and so does any arrow_csv_args key other than read_options, parse_options and convert_options. Tracked in [Data] CSV and JSON on DataSource V2: remove the remaining V1 fallbacks #68382. (The only other key V1 accepts is memory_pool, and that can't be sent to read tasks anyway.)
  2. Files over HTTP can go missing. V2 skips a file when the server doesn't report its size. Tracked in [Data] DataSource V2 silently skips files whose size is unknown (e.g. HTTP without Content-Length) #68381. There's no V1 fallback for this here, so merging makes it worse than today.
  3. input_files() returns [] on V2. V1 returns the list of files. This PR changes the docstring example to use read_binary_files rather than fixing it. read_parquet on V2 has the same gap.
  4. A file with its own partition column can silently change data. For country=US/a.csv with rows saying country=CA, V1 raises an error. V2 returns US and drops the file's CA. We should either match V1 or document this.
  5. Quoted newlines and per-piece types (see inline comments). In both cases V1 gives a clear error, while V2 returns wrong data or results that depend on how many read tasks run.

Once these are done, the V1 check in read_csv and CSVDatasource can be removed.

sampan-s-nayak pushed a commit that referenced this pull request Nov 23, 2026
## Summary
DataSource V2 now reads files whose size the filesystem doesn't report,
such as files on an HTTP server that sends no `Content-Length`. Before,
V2 dropped them, and `read_text` sent every HTTP read to V1 to avoid
that. Fixes #68381.

## Before
- V2 listing (`NonSamplingFileIndexer.list_file_infos`, which every V2
file indexer builds on) skipped any file with `size=None` and logged
"Skipping zero-size file". The text indexer, the driver-side sample and
the Parquet footer indexer skipped them too.
  - One such file: the read failed with "no files found".
  - Several: the files without a size were left out with no error.
- The code that groups files into read tasks assumed a real size.
`SamplingInMemorySizeEstimator` asserted sizes `>= 0`, `OnlineBinPacker`
called `int(file_size)`, and `LineChunkFileIndexer` asserted the size
wasn't `None`.
- `read_text` used V1 for any HTTP path or filesystem. CSV (#67904),
JSON (#67905) and WebDataset (#68017) have no such fallback, so they
would have silently skipped these files.

## After
- Listing keeps a file of unknown size and stores its size as null in
the manifest. Zero-size files are still skipped where they were before.
- The manifest's size column is always `int64`, so a listing where every
size is unknown doesn't get Arrow's `null` type.
- Memory estimates for these files stay unknown (`NaN`):
- `RoundRobinPartitioner` passes them as `None`, which
`WeightedRoundRobinPartitioner` already spreads across buckets. Before,
a `NaN` weight would have counted as 0 bytes and piled them into one
task.
  - `OnlineBinPacker` gives each such whole file its own read task.
- `LineChunkFileIndexer` reads such a file whole, since byte ranges need
the size.
- `read_text` no longer falls back to V1 for HTTP. It still does for
`arrow_open_stream_args` (#68380).
- The V2 text reader opens files with a `streaming_read_buffer_size` (32
MiB) buffer, as V1 does. Otherwise a file over 5 MiB on a server that
sends its size but ignores range requests (such as `python -m
http.server`) fails: fsspec reads in 5 MiB blocks, and the second block
needs a range request.
- Formats that read the end of a file (Parquet) can't read a
non-seekable HTTP stream on V1 either. They now fail on V2 with the same
error ("Cannot seek streaming HTTP file") instead of returning no rows.

```mermaid
flowchart TD
    subgraph Before
        subgraph BS[Subsystem: IO]
            subgraph BC[Component: DataSource V2 listing and partitioning]
                B1[list_file_infos] -->|size=None: skipped| B0[file dropped]
                B1 -->|size known| B2[FileManifest] --> B3[size estimator / partitioner]
            end
        end
    end
    subgraph After
        subgraph AS[Subsystem: IO]
            subgraph AC[Component: DataSource V2 listing and partitioning]
                A1[list_file_infos] -->|size known or None| A2[FileManifest: int64 size, null if unknown]
                A2 --> A3[estimator: NaN for unknown]
                A3 --> A4[RoundRobinPartitioner: spread unknowns across buckets]
                A2 --> A5[OnlineBinPacker: one task per unknown-size file]
                A2 --> A6[LineChunkFileIndexer: read unknown-size file whole]
            end
        end
    end
    classDef removed fill:#ffcdd2,stroke:#c62828,color:#000
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class B0 removed
    class A1,A2,A3,A4,A5 changed
    class A6 added
```

## Subsystems
IO (the behavior change, in `_internal/datasource_v2/`); API
(`read_text` routing in `read_api.py`).

## Testing
I extended or parametrized existing tests; there are no new test files.
Each test fails when its part of the fix is reverted:

| Test | Change | Fails on revert with |
|---|---|---|
| `test_text.py::test_fsspec_http_file_system` (V1/V2 × 1 or 2 paths ×
fsspec filesystem or auto-resolved × two test files). `no-size`: the
server sends no `Content-Length`. `no-ranges`: a 6.4 MiB file the server
sends whole, with its size, whatever range is asked for. | Listing and
sample keep the files; `read_text` HTTP routing removed; text reader
buffer | Whole fix reverted: the V2 cases fail the V2-route check (they
go to V1). Listing fix reverted: `ValueError: no files found`. Buffer
reverted: the 4 V2 `no-ranges` cases fail with "The HTTP server doesn't
appear to support range requests" |
| `test_online_bin_packer.py::test_whole_file_rows_pack_by_file_size`
(adds a row with an unknown size) | Bin packer | `ValueError: cannot
convert float NaN to integer` |
|
`test_file_partitioners.py::test_round_robin_partitioner_with_no_size_estimates`
(adds the sampling estimator) | Round robin, sampling estimator |
`assert 1 == 2` (all files in one task), `AssertionError` in the
estimator |
|
`test_line_chunking.py::test_indexer_keeps_a_file_that_fits_in_one_chunk_whole`
(adds an unknown size) | Line chunker | the old `assert file_info.size
is not None` |

`test_read_text_routes_to_v1` loses its `http` case, since HTTP reads
now go to V2.

Each module ran in its own pytest process, on macOS with Python 3.12,
pyarrow 23.0.1 and fsspec 2023.12.1:

| Command | Result |
|---|---|
| `pytest python/ray/data/tests/unit/datasource_v2` | 1365 passed, 225
skipped |
| `pytest python/ray/data/tests/unit/datasource` | 126 passed |
| `pytest python/ray/data/tests/datasource/test_text.py` | 29 passed, 1
skipped (after the buffer fix) |
| `pytest python/ray/data/tests/datasource/test_read_parquet_v2.py` |
130 passed |
| `pytest python/ray/data/tests/datasource/test_hive.py` | 36 passed |
| `pytest python/ray/data/tests/datasource_v2` | all passed
(`test_schema_worker_semantics.py` run on its own) |
| `pytest python/ray/data/tests/datasource/test_orc.py` | 217 passed, 6
failed |

The 6 ORC failures come from my local setup, not this change.
`test_read_orc_v2_partitioned_scan_optimizations` checks that the
reader's file path ends in `python/ray/data/...`, but my environment
loads Ray Data through a `site-packages` symlink. Every assertion before
that one passes. The MCAP tests were skipped locally because the `mcap`
library isn't installed. Pre-commit hooks pass, and pyrefly with CI's
settings reports 0 errors on the changed files.

Not a duplicate: no open PR addresses #68381. The CSV port (#67904)
lists it as a known gap.

This PR was written with AI assistance (Claude Code). I reviewed every
changed line and ran the tests above.

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

---------

Signed-off-by: Abhishek Verma <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
NightWing1998 and others added 5 commits November 23, 2026 14:43
…asks

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Dhruvil Shah <[email protected]>
CsvFileIndexer read each split file's header line one after another in
the listing task, a serial round trip per large file before any read
task starts. Header reads still run once per split file, but listing
now dispatches them to a spread HeaderReader actor pool with the footer
indexer's batching and in-flight window, restarting actors and re-running
their batches up to 10 times on death or OOM. RAY_DATA_CSV_HEADER_NUM_ACTORS=0
reads headers inline in the listing task.

- The batching and the pool protocol are shared with the Parquet footer
  indexer (listing_utils.batch_file_infos, common/actor_pool.py). The pool
  starts on the first split file, so a dataset of only small files starts
  no actors.
- A split piece that pyarrow rejects raises an error naming the file and
  pointing at ParseOptions(newlines_in_values=True). escape_char now reads
  files whole, as an escaped newline breaks the same assumption.
- read_snappy_buffer unwraps the retry wrapper, so HDFS .csv.snappy files
  keep Hadoop framing. resolve_partitioning uses the shared partition
  discovery that Parquet, ORC and Text use.

Co-Authored-By: Claude Code <[email protected]>
Signed-off-by: Dhruvil Shah <[email protected]>
…d_csv

- The Dataset.input_files doctest uses the V1 reader: V2 lists files at
  execution, so it returns an empty list.
- test_count_after_caching_after_execution asserts the V2 repr, which prints
  the schema table ("shape: (?,").
- test_split_read_csv accepts 3 or 4 blocks at a 3 MB target, as the
  Parquet test does, because V2 sizes blocks from bytes on disk.
- test_small_file_split is renamed test_small_file_split_v1: V2 doesn't split
  a small file's output into override_num_blocks blocks.
- read_csv's partitioning argument documents a file column that shares a
  partition key's name.

Signed-off-by: Dhruvil Shah <[email protected]>
… as V1 does

A file column with a partition key's name goes through V1's
_add_partitions_to_table instead of being dropped and replaced by the path
value. A mismatch raises ValueError, and a null path value matches only an
all-null column, which also fixes the cast of the path value to a null type.

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

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 V1 does.

- CsvFileIndexer._needs_header no longer asserts a size, and reads no header
  for a file of unknown size.
- OnDiskSizeEstimator returns float64 so an unknown size stays NaN, which the
  partitioner treats as unknown, instead of failing the int64 cast.
- LineChunkableFileReader takes a file's size from the listing instead of
  asking an open file for it, so an unknown-size file skips the in-memory
  whole-file read and takes the streaming path. That read is renamed
  _read_whole_file, because a task runs it for every whole file that fits in
  one chunk.

Errors. Any error in a later piece of a split file was reported as a quoted
newline, and pyarrow's message was dropped. Both CSV read errors now include
pyarrow's own error. The piece error lists the usual causes, a mistyped value
or a row with the wrong number of columns, and names a newline inside a quoted
value as one possible cause.

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

- Apply `include_columns` as the scan projection: pyarrow's dataset scan
  appended the projection to it and duplicated the column.
- Read whole-file snappy CSVs through the reader's filesystem so HDFS
  framing applies.
- Check a file column named like a partition key against the path value
  when a projection selects it.
- Read the first batch of split-file headers inline, so a few large files
  start no header actors.
- Show the quoted-newline hint only for column-count errors, and add a TODO
  for quoted newlines in split reads.
- Share the chunking rule between the base indexer and the CSV header
  lookup, and drop the dead `batch_no`.
- Move the CSV tests to the `datasource_v2` and `restore_data_context`
  fixtures.

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.

Approving, thanks for the fixes. A few things are still open. Could you file issues for them so they're tracked?

  1. Mixed column types in one file. Pieces of a split file guess types on their own, so a column can be int64 in some blocks and string in others. V1 fails at read time; V2 fails later (for example in write_parquet) or not at all.
  2. HTTP servers without range requests. A file bigger than the chunk size fails on V2 but reads on V1.
  3. Quoted newlines. The rare case that returns wrong rows with no error. Please bring back the strict-xfail test for it.

@NightWing1998

Copy link
Copy Markdown
Contributor Author

Approving, thanks for the fixes. A few things are still open. Could you file issues for them so they're tracked?

  1. Mixed column types in one file. Pieces of a split file guess types on their own, so a column can be int64 in some blocks and string in others. V1 fails at read time; V2 fails later (for example in write_parquet) or not at all.
  2. HTTP servers without range requests. A file bigger than the chunk size fails on V2 but reads on V1.
  3. Quoted newlines. The rare case that returns wrong rows with no error. Please bring back the strict-xfail test for it.

thanks @abhishekverma-ray. Yes I've filed https://anyscale1.atlassian.net/browse/DATA-3838 and https://anyscale1.atlassian.net/browse/DATA-3839 for 1 and 3. for http range requests I'll use the https://anyscale1.atlassian.net/browse/DATA-3818 (same as reading whole files without v1 readers)

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.

5 participants