Skip to content

[Data] Bound CSV and JSON whole file readers - #68484

Open
NightWing1998 wants to merge 5 commits into
masterfrom
dsv2-bounded-whole-file-reads
Open

NightWing1998 wants to merge 5 commits into
masterfrom
dsv2-bounded-whole-file-reads

Conversation

@NightWing1998

@NightWing1998 NightWing1998 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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=False read 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 V2
  • 238a4b7d18 [Data] Address review of the bounded whole-file CSV and JSON reads
  • 99f90433f7 Apply batched suggestions from code review
  • 9b133ea04f [Data] Scan CSV stream blocks through the shared fragment path
  • 22342654aa [Data] Convert only the projected CSV columns of a streamed file

Before

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

  • CSV: the file is scanned through pyarrow.dataset. Its CSV scan reads ahead of the consumer without bound (batch_readahead=1 makes no difference), so a worker that consumes slower than the source reads buffers the whole file. V1 uses pcsv.open_csv, which parses a block only when asked for it, and stays flat.
  • JSON lines=False: JsonFileReader reads the whole file and parses it as one block, so a task holds several times the file and a .jsonl file over 2 GiB fails (block_size is a 32-bit int).

After

  • CSV: a whole-file unit that isn't read as one chunk is read with pcsv.open_csv, as V1 does. include_columns is 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 to open_csv as include_columns (with include_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.
  • JSON lines=False: a .jsonl file that is compressed, of unknown size or can't be split is read in pieces of whole lines of about RAY_DATA_LINE_CHUNK_BYTES each (iter_line_pieces). Each piece is parsed as one block, as a split chunk is. A .jsonl file is read as JSON Lines, one object per line, as the read_json docstring now says. A .json file may be one document, so it is still parsed whole.
  • iter_line_pieces finds 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:

  • A compressed (including Snappy) or unknown-size .jsonl file 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, .json files, lines=True (already streams in frames), and Snappy CSV and .json.snappy files. A .jsonl.snappy file 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 changed
Loading

Subsystems

IO (_internal/datasource_v2/), plus the API docstring of read_json (read_api.py). The behavior change is in CsvFileReader and JsonFileReader; LineChunkableFileReader gains an _iter_streamed_unit_tables hook and a _with_file_partition_keys helper (extracted from the existing partition-key check, no change), and line_chunking.py gains iter_line_pieces.

Testing

  • pytest python/ray/data/tests/unit/datasource_v2: 1485 passed, 227 skipped. New tests cover:

    • iter_line_pieces cutting 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;
    • a compressed CSV streamed with projection and null fill, converting only the projected columns on plain and hive-partitioned files (fails if the projection isn't passed to open_csv);
    • a CSV read that opens the stream once and has read under half the file when the first table comes out (fails on the pre-PR dataset scan);
    • include_columns with a projection outside it, and a partition column outside it, on plain and gzip CSV;
    • a compressed .jsonl (gzip and Snappy) read in pieces, a .json read whole, and a top-level array in a .jsonl.gz raising.
  • 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"]) returns name='a' for both a.csv and a.csv.gz.

  • pre-commit run on the changed files: clean.

  • Not re-run on this head: tests/datasource/test_csv.py, test_json.py and tests/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 no Content-Length. The figure is the peak private memory (resident minus shared) of the largest ray:: process, sampled once a second:

    Read Before After V1
    CSV, unknown size, 3.9 GB 9.5 GiB, 36 s 0.18 GiB, 23 s 0.62 GiB, 28 s
    CSV, local, newlines_in_values=True, 3.9 GB 9.0 GiB 0.19 GiB 0.55 GiB
    CSV, gzip, about 1 GB decompressed not measured 0.18 GiB not measured
    JSON lines=False, unknown size, 3.5 GB failed 1.1 GiB, 25 s not measured
    JSON lines=False, gzip .jsonl, about 0.9 GB decompressed not measured 1.1 GiB not measured

    The "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_BYTES to lower it. These figures were taken before the review fixes, which make iter_line_pieces copy each piece once instead of twice; I did not re-measure.

Notes

🤖 Generated with Claude Code

@NightWing1998
NightWing1998 force-pushed the dsv2-bounded-whole-file-reads branch from 07f3763 to 9304bdf Compare November 23, 2026 16:48
Base automatically changed from dsv2-json to master November 23, 2026 17:35
@sampan-s-nayak
sampan-s-nayak force-pushed the dsv2-bounded-whole-file-reads branch from 9304bdf to 4777bd9 Compare November 23, 2026 17:35
@NightWing1998
NightWing1998 marked this pull request as ready for review November 24, 2026 08:13
@NightWing1998
NightWing1998 requested review from a team as code owners November 24, 2026 08:13

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

@NightWing1998 NightWing1998 changed the title [WIP][Data] Bound CSV and JSON whole file readers [Data] Bound CSV and JSON whole file readers Nov 24, 2026
@ray-gardener ray-gardener Bot added performance data Ray Data-related issues labels Nov 24, 2026
@NightWing1998
NightWing1998 force-pushed the dsv2-bounded-whole-file-reads branch from 4777bd9 to 1edded4 Compare November 25, 2026 13:50
NightWing1998 and others added 2 commits November 25, 2026 19:22
…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]>
NightWing1998 and others added 2 commits November 27, 2026 15:11
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]>
@NightWing1998
NightWing1998 force-pushed the dsv2-bounded-whole-file-reads branch from f8ab976 to 9b133ea Compare November 27, 2026 09:41

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

LGTM, thanks! Small one: the description still says Snappy files are unchanged, but .jsonl.snappy now streams in pieces.

@abhishekverma-ray abhishekverma-ray added the go add ONLY when ready to merge, run all tests label Nov 27, 2026
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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

let's make this a common util by passing in delimiter to the function

This branch has not been deployed

No deployments
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 performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants