Repository navigation
[Data] Bound CSV and JSON whole file readers - #68484
NightWing1998 wants to merge 5 commits into
Conversation
07f3763 to
9304bdf
Compare
9304bdf to
4777bd9
Compare
There was a problem hiding this comment.
Code Review
This pull request introduces streaming support for compressed, unsplit, or unknown-size CSV and JSON Lines files in Ray Data's DataSource V2, preventing unbounded memory usage by reading and parsing files in chunks or block-by-block. Key additions include iter_line_pieces for streaming bytes by line boundaries, block-by-block CSV streaming with projection/filtering/null-filling, and chunked streaming for JSON Lines. Feedback on the changes highlights two performance optimization opportunities: converting lists to sets in _with_file_partition_keys and _scan_block to avoid O(N) linear scans during column membership checks.
4777bd9 to
1edded4
Compare
…e V2 pyarrow's dataset scan of a CSV stream reads ahead of its consumer without bound, so a compressed, unknown-size or unsplittable CSV file filled worker memory with about twice its size. Read those with `pcsv.open_csv`, as V1 does, and apply the projection, null fill and filter per block. A JSON `lines=False` file was parsed whole, holding several times its size, and failed above 2 GiB. Read a compressed, unknown-size or unsplittable `.jsonl` file as pieces of whole lines, each parsed like a split chunk. A `.json` file may be one document, so it is still parsed whole. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: Dhruvil Shah <[email protected]>
Fix a regression in the streamed CSV path, make `iter_line_pieces` linear, and align the docs and tests with the behavior of the bounded reads. Streamed CSV ignored `include_columns` as a projection. It passed the original `ConvertOptions`, with `include_columns` set, to `pcsv.open_csv`, so a column outside `include_columns` was never read and came back as nulls when requested. A file column named like a hive partition key but left out of `include_columns` was never read either, so it was never checked against the path value. The scan and chunk paths use the reader's convert options, whose `include_columns` is emptied and applied as the projection afterwards. Use the same options in the streamed path, so `a.csv` and `a.csv.gz` return the same rows. All file columns are now parsed per block and then projected, as V1 does; pushing the projection into `open_csv` is left for later, because it needs the header to decide which columns to request without breaking the null fill of a missing column or the partition-key check. `iter_line_pieces` rescanned the whole buffer for the last newline after every read once the buffer reached the piece size, which is quadratic for a line longer than a piece, and copied each piece twice. Remember how far the buffer has been searched, search only the bytes added since, and copy the piece once. A single 256 MiB line takes 0.14 s instead of 1.7 s. The output is unchanged: the cut stays at the last newline in the buffer. `_streams_in_pieces` no longer checks `size > chunk_size`. The indexer already splits a known-size uncompressed `.jsonl` file larger than a chunk, so only compressed or unknown-size files reach the check. Document that a `.jsonl` file is read as JSON Lines, one object per line, in the `read_json` docstring, and pin with a test that a top-level array in a `.jsonl.gz` file raises. Update the line chunk reader docstrings to name `_iter_streamed_unit_tables` as the path for larger, compressed and unknown-size files. Tests: `include_columns` with a projection outside it, and a partition column outside it, on plain and gzip CSV; more `iter_line_pieces` cases (a newline in an earlier read, only newlines, no newline) and a seeded random test that the pieces re-join to the stream; the JSON array test above. Move `test_iter_line_pieces_cuts_a_stream_at_newlines` above the `__main__` block so running the file as a script includes it. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: Dhruvil Shah <[email protected]>
1edded4 to
238a4b7
Compare
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> Signed-off-by: Dhruvil Shah <[email protected]>
Each streamed CSV block now goes through `_iter_fragment_tables` as an in-memory fragment, replacing the duplicated `_scan_block`. Add a test that fails if the CSV read pulls the whole file before the first table, and cover `.jsonl.snappy` in the compressed JSON Lines pieces test. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: Dhruvil Shah <[email protected]>
f8ab976 to
9b133ea
Compare
abhishekverma-ray
left a comment
There was a problem hiding this comment.
LGTM, thanks! Small one: the description still says Snappy files are unchanged, but .jsonl.snappy now streams in pieces.
Pass the projection to `pcsv.open_csv` as `include_columns` with `include_missing_columns`, so a streamed read no longer converts columns it drops. A file column named like a requested hive key is still read, found from the file's header, so the partition-key check keeps working. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: Dhruvil Shah <[email protected]>
| return lines | ||
|
|
||
|
|
||
| def iter_line_pieces( |
There was a problem hiding this comment.
let's make this a common util by passing in delimiter to the function
Summary
Bounds the memory of whole-file CSV and JSON reads on DataSource V2. A whole-file CSV read held about 2.4x the file in one worker, and a whole-file JSON
lines=Falseread held about 4.5x and failed above 2 GiB. After this PR a read holds about one block (CSV) or one chunk's worth of lines (JSON), whatever the file size.Follows #67904 (CSV) and #67905 (JSON), both merged; this PR is five commits on
master:5abe13f603[Data] Bound the memory of whole-file CSV and JSON reads on DataSource V2238a4b7d18[Data] Address review of the bounded whole-file CSV and JSON reads99f90433f7Apply batched suggestions from code review9b133ea04f[Data] Scan CSV stream blocks through the shared fragment path22342654aa[Data] Convert only the projected CSV columns of a streamed fileBefore
A V2 read that can't be done as a ranged chunk read streams or parses the whole file in one task. That is a file that is compressed, of unknown size (such as an HTTP file without
Content-Length), or can't be split (newlines_in_values,escape_char,skip_rows, a non-UTF-8 encoding).pyarrow.dataset. Its CSV scan reads ahead of the consumer without bound (batch_readahead=1makes no difference), so a worker that consumes slower than the source reads buffers the whole file. V1 usespcsv.open_csv, which parses a block only when asked for it, and stays flat.lines=False:JsonFileReaderreads the whole file and parses it as one block, so a task holds several times the file and a.jsonlfile over 2 GiB fails (block_sizeis a 32-bit int).After
pcsv.open_csv, as V1 does.include_columnsis applied as a projection, as the scan and chunk paths do, and each block is scanned as an in-memory fragment through_iter_fragment_tables, the path a chunk takes, so projection, null fill of a column the file lacks and the partition-key check are shared code. CSV keeps filters above the read, so none reaches the reader. The projection is passed toopen_csvasinclude_columns(withinclude_missing_columns, so a column the file lacks null-fills), so only the projected columns are converted. A file column named like a requested hive key is also read, found from the file's header, so the partition-key check still works.lines=False: a.jsonlfile that is compressed, of unknown size or can't be split is read in pieces of whole lines of aboutRAY_DATA_LINE_CHUNK_BYTESeach (iter_line_pieces). Each piece is parsed as one block, as a split chunk is. A.jsonlfile is read as JSON Lines, one object per line, as theread_jsondocstring now says. A.jsonfile may be one document, so it is still parsed whole.iter_line_piecesfinds each cut by searching only the bytes read since the last search, so a line longer than a piece no longer costs quadratic time (a 256 MiB line: 1.7 s before, 0.14 s after).Behavior that changes:
.jsonlfile is typed per piece, not per file, as split files already are.Unchanged: files read as ranged chunks, known-size files that fit in one chunk,
.jsonfiles,lines=True(already streams in frames), and Snappy CSV and.json.snappyfiles. A.jsonl.snappyfile is still decompressed whole, since pyarrow can't stream Snappy, and then cut into pieces, so its memory is not bounded; only its typing changes.flowchart TD subgraph Before subgraph BIO["IO: datasource_v2, whole-file unit (compressed, unknown size, unsplittable)"] B1["CsvFileReader: pyarrow.dataset scan<br/>reads ahead without bound"] B2["JsonFileReader: read whole file,<br/>parse as one block"] end end subgraph After subgraph AIO["IO: datasource_v2, whole-file unit (compressed, unknown size, unsplittable)"] A1["CsvFileReader._iter_streamed_unit_tables:<br/>pcsv.open_csv, one block at a time"] A2["JsonFileReader: .jsonl in pieces of whole lines<br/>(iter_line_pieces), .json whole"] 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 B1,B2 removed class A1,A2 changedSubsystems
IO (
_internal/datasource_v2/), plus the API docstring ofread_json(read_api.py). The behavior change is inCsvFileReaderandJsonFileReader;LineChunkableFileReadergains an_iter_streamed_unit_tableshook and a_with_file_partition_keyshelper (extracted from the existing partition-key check, no change), andline_chunking.pygainsiter_line_pieces.Testing
pytest python/ray/data/tests/unit/datasource_v2: 1485 passed, 227 skipped. New tests cover:iter_line_piecescutting at newlines (a long line, no final newline, an empty stream, a newline in an earlier read, only newlines) and re-joining to the stream over 200 random inputs with short reads;open_csv);include_columnswith a projection outside it, and a partition column outside it, on plain and gzip CSV;.jsonl(gzip and Snappy) read in pieces, a.jsonread whole, and a top-level array in a.jsonl.gzraising.End to end with
ray.init(num_cpus=2)and V2 on:read_csv(p, convert_options=ConvertOptions(include_columns=["id"])).select_columns(["id", "name"])returnsname='a'for botha.csvanda.csv.gz.pre-commit runon the changed files: clean.Not re-run on this head:
tests/datasource/test_csv.py,test_json.pyandtests/datasource_v2/test_csv_header_listing.py(they need a Ray cluster).Memory, measured on real files on local disk, one run each,
ray.init(num_cpus=4),read_*(...).count(). Unknown-size files were served by a local HTTP server that sends noContent-Length. The figure is the peak private memory (resident minus shared) of the largestray::process, sampled once a second:newlines_in_values=True, 3.9 GBlines=False, unknown size, 3.5 GBlines=False, gzip.jsonl, about 0.9 GB decompressedThe "before" CSV figure grows with file size (2.3 GiB at 1 GB, 9.5 GiB at 3.9 GB). I did not run a 75 GB file. I did not measure S3, GCS or HDFS. The JSON 1.1 GiB is one piece at the default 128 MiB chunk; lower
RAY_DATA_LINE_CHUNK_BYTESto lower it. These figures were taken before the review fixes, which makeiter_line_piecescopy each piece once instead of twice; I did not re-measure.Notes
.jsonlis detected by extension only. A JSON Lines file named.json, or with no extension, is still parsed whole and fails above 2 GiB.🤖 Generated with Claude Code