Repository navigation
[Data](2/n) Read CSV on DataSource V2, splitting large files across read tasks - #67904
Conversation
143d4dc to
e34d7e9
Compare
There was a problem hiding this comment.
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.
4deecf2 to
5388d31
Compare
5388d31 to
027a52b
Compare
027a52b to
e19b21a
Compare
e19b21a to
3e5c86c
Compare
## 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]>
|
@NightWing1998 please address merge conflicts |
| ) | ||
|
|
||
| @override | ||
| def _can_split_files(self) -> bool: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
3e5c86c to
7de9ffa
Compare
7de9ffa to
5514d98
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ 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.
|
What's still needed before we can delete V1
Once these are done, the V1 check in |
cc1f86f to
ee41f59
Compare
## 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]>
…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]>
ee41f59 to
da4e96d
Compare
…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
left a comment
There was a problem hiding this comment.
Approving, thanks for the fixes. A few things are still open. Could you file issues for them so they're tracked?
- Mixed column types in one file. Pieces of a split file guess types on their own, so a column can be
int64in some blocks andstringin others. V1 fails at read time; V2 fails later (for example inwrite_parquet) or not at all. - HTTP servers without range requests. A file bigger than the chunk size fails on V2 but reads on V1.
- 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) |

Summary
read_csvruns on DataSource V2 whenuse_datasource_v2is 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_csvalways used V1CSVDatasource, which reads each file whole in one task. A 1 GiB CSV is read by one task.After
Routing.
read_csvbuildsCsvDatasourceV2and goes throughListFiles -> ReadFiles. It falls back to V1 in the cases listed under Falls back to V1.Splitting.
CsvFileIndexerlists a large uncompressed file asRAY_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.
CsvFileIndexerreads 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:country=US/a.csvwith acountrycolumn). The path value must equal the file's values, as in V1, or the read raisesValueError.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 ofHeaderReaderRay 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_retriesare 10, so an actor death or OOM re-runs its batch.RAY_DATA_CSV_HEADER_NUM_ACTORS=0reads 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_tableunchanged: 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 raisesValueError. That check is inFileReader._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.
RoundRobinPartitionersizes read tasks with a newOnDiskSizeEstimator: bytes on disk, as V1 sizes CSV reads, with a chunk weighing its own bytes. Sizing reads nothing. Withpreserve_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 passConvertOptions(column_types=...)) and names a quoted newline as one possible cause (passParseOptions(newlines_in_values=True)).Snappy. Snappy files still read: V2 decompresses through
read_snappy_bufferincommon/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.
LineChunkableDatasourceV2holds what CSV and JSON share. The JSON PR in this stack uses it.Reader.
CsvFileReaderoverrides_get_fragments_to_readonly 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'sblock_sizewithone_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 changedGaps 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_csvbuilds the V1CSVDatasourcewhen any of these holds:use_datasource_v2is offDataContext.get_current().use_datasource_v2 = False, orRAY_DATA_USE_DATASOURCE_V2=0before importing Ray.arrow_open_stream_argsis set{"compression": "gzip"}.read_options,parse_optionsorconvert_optionsis passedmemory_pool.Read whole, not split
These files read on V2 but as one read task per file, as in V1:
parse_options.newlines_in_valuesorparse_options.escape_charis set;read_optionsskips rows;Content-Length: it reads as one stream, as in V1, and read-task sizing treats its size as unknown (NaN).Behaves differently from V1
Dataset.input_files()[]: files are listed at execution, not planning. Parquet, ORC and Text on V2 do the same. Theinput_filesdocstring example now usesread_binary_files(V1).override_num_blocks=Non a small fileReadCSV->SplitBlocks(N)).SetReadParallelismRulesets the split factor for V1Readops only, andplan_read_files_ophas no equivalent. Parquet on V2 has the same gap.LogicalPlan.initial_num_blocks()before executionNone, because listing runs at execution.target_max_block_sizeReadCSV,ReadCSV->MapBatches(...).ListFilesandReadFilesCsvV2. Anything keyed on the names (stats output, metrics, tests) changes.open_csvand holds about a block at a time.newlines_in_values, unknown size) stay at about 270 MiB. Tune withRAY_DATA_LINE_CHUNK_BYTES; streaming a chunk withopen_csvis not done here.include_columnsnaming a column a file lacksColumn ... in include_columns does not exist in CSV file).nullfor the column, with no error. A file in the schema sample that lacks it still raises at planning, as in V1.Dataset(num_rows=?, schema=...).Tests that stay V1-only
test_splitblocks.py::test_small_file_split_v1is pinned to V1, because it asserts the V1 task names and theoverride_num_blockssplit 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:
"line1⏎line2", valid RFC 4180);escape_char, when one is set.A two-character
\n(a backslash, thenn) contains no newline byte and isn't affected.Files whose parse options set
newlines_in_valuesorescape_charare read whole, so only a file with a quoted newline and the default parse options can hit this. It takes a file larger thanRAY_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 aTODOinCsvDatasourceV2._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_csvmoves 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 endSubsystems
IO (behavior change:
_internal/datasource_v2/), API (routing inread_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 newtest_csv_datasource_v2.pycovers: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;escape_char;newlines_in_valueshint, and the hint shown only for a column-count error;include_columns, split and whole, in file and in requested order;NaNweight, no header read for an unknown size, and a whole-file read that never asks the file for its size;preserve_order;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 fourtest_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-sizeandno-ranges, 1 or 2 paths, fsspec or auto-resolved filesystem), modelled ontest_text.py::test_fsspec_http_file_system.include_paths,preserve_orderacross 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_stringvsstringschemas, plustest_orc_roundtrip[*-2]).End to end, a 1.0 GiB single CSV file (33M rows) on a 10-CPU machine:
idDoctests for the updated examples (
pytest --doctest-modules -p ray.data.tests.doctest_pytest_plugin):Dataset.input_files,Dataset.serialize_lineage,Dataset.deserialize_lineageandread_csv: passed.to_tfexamples 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_executionasserts the V2 repr (shape: (?,) instead ofnum_rows=?;test_splitblocks.py::test_small_file_split_v1, renamed and pinned to V1 (see Gaps);test_size_estimation.py::test_split_read_csvaccepts 3 or 4 blocks at a 3 MB target (2 < len(nrow) < 5), the Parquet test's bound.pre-commit runon the changed files: clean.Notes
read_csvto DSv2 with its own chunker. This PR uses the shared CSV/JSONL chunker from [Data] Add a shared byte-range line chunker for CSV and JSONL on DataSource V2 #67725 instead, so CSV and JSON Lines split files the same way. Thanks to @400Ping for [Data] Migrate CSV datasource to DatasourceV2 #65743 and the parity cases it worked through.🤖 Generated with Claude Code