Skip to content

[Data] Migrate read_webdataset to DataSource V2 - #68017

Merged
richardliaw merged 20 commits into
ray-project:masterfrom
Hyunoh-Yeo:webdatasetv2
Nov 24, 2026
Merged

richardliaw merged 20 commits into
ray-project:masterfrom
Hyunoh-Yeo:webdatasetv2

Conversation

@Hyunoh-Yeo

@Hyunoh-Yeo Hyunoh-Yeo commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Description

Read WebDataset on DataSource V2, following the Parquet, ORC and MCAP migrations. read_webdataset now goes through the V2 path whenever DataContext.use_datasource_v2 is set, like the other formats. The write path stays on the existing datasink, with one encoder fix (see Additional information).

New files in datasource_v2/formats/webdataset/:

  • webdataset_datasource_v2.py: WebDatasetDatasourceV2. Lists tar shards with NonSamplingFileIndexer and groups them into read tasks with RoundRobinPartitioner, using a fixed in-memory/file-size ratio measured on Imagenette (0.7 without decoding, 8.9 with the default decoder). A shard is never split, since a tar is read sequentially.
  • webdataset_scanner.py: WebDatasetScanner. Carries the read options to the workers. No filter, projection or limit pushdown.
  • webdataset_reader.py: WebDatasetReader. Streams each shard and yields a pa.Table every 512 samples. Opens files with DataContext.streaming_read_buffer_size and handles .snappy shards with python-snappy.
  • webdataset_utils.py: the tar, grouping and decoding helpers, plus iter_webdataset_rows, which yields one decoded sample at a time.

Schema inference

infer_schema returns None, so ds.schema() is resolved from the first read block. A tar shard stores no schema and decoded types depend on the decoder, so the schema is only known after decoding samples. Decoding the first chunk on the driver instead holds a whole chunk in driver memory at read_webdataset() time: on test_write_large_data_webdataset (200 rows of 10 MB) the driver peaked at 4.58 GB, versus 0.20 GB when returning None. Returning None also keeps decode errors at execution time and lets ds.schema() see keys that first appear after the first chunk.

No other V2 datasource returns None here. The logical layer already treats None as an unknown schema, and projection pushdown skips it.

Behavior differences from V1

  • Grayscale images: the default decoder returns them as (H, W, 1) instead of (H, W), so grayscale and color images share one tensor type. Without this, a chunk that mixes them falls back to objects and can't be concatenated with an all-color chunk.
  • Missing keys: a sample that lacks a key gets a null, and the column keeps its type (int64, string, tensor). In V1 such a column is object with NaN, or float64 for integers. A column where only some samples have an image now reads; V1 fails on it.
  • to_pandas() returns Arrow-backed dtypes (string[pyarrow], binary[pyarrow]), since V2 blocks are Arrow tables.
  • Retries: a transient error while reading a shard reopens the shard and replays it from the start. V1 retries on the same tar stream, which can't be rewound, so it silently drops samples (600 to 804 of 2,000 in a local repro).
  • expand_json: a sample without a .json member is left as is instead of raising KeyError, and a JSON field that matches an existing column raises a ValueError that names the field instead of an AttributeError.

Known limitations

  • A column whose dtype changes between chunks fails when chunks are concatenated (for example uint8 and uint16 images).
  • A custom decoder or .npy members whose ndim is mixed within a chunk fail when concatenated with a chunk that isn't mixed.

Tests

  • test_webdataset.py: tests whose results differ by version now run on both through a use_datasource_v2 fixture. Added tests for grayscale expansion, mixed grayscale and color images across chunks, the two known limitations, retrying a transient error mid-read, source_paths, the expand_json edge cases, and a grayscale read-then-write round trip.
  • test_webdataset.py passes on both V1 and V2 (50 tests). test_write_large_data_webdataset passes on both.
  • Imagenette (100 shards, 102,400 samples): V1 and V2 return the same keys, labels and pixels. Only the 1,878 grayscale images change shape.
  • Also compared V1 and V2 on include_paths, shuffle, partition_filter, override_num_blocks, concurrency, select_columns, limit, compressed shards (.tar.gz, .tar.bz2, .tar.zst), and retries when opening a file. All match except the casing of the "no files found" message.

Related issues

Design doc: https://docs.google.com/document/d/1Zw98x4Ic5TiDkXZ6FXH0BMPIaGWQSC743OU4TNR0FJA/edit?usp=sharing

Additional information

webdataset_utils.py and common/image_utils.py copy the legacy WebDataset read helpers and _ALLOWED_PIL_FORMATS (type hints fixed for pyrefly), so the legacy read path stays untouched. A follow-up PR will make the legacy modules import from datasource_v2.

write_webdataset's default encoder now drops a trailing singleton channel axis before PIL.Image.fromarray, so grayscale images read as (H, W, 1) can be written back.

@Hyunoh-Yeo
Hyunoh-Yeo requested a review from a team as a code owner November 10, 2026 11:26

@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 a new V2 datasource implementation for WebDataset tar shards, including WebDatasetDatasourceV2, WebDatasetReader, WebDatasetScanner, and helper utilities, along with corresponding test coverage. The review feedback highlights several critical issues: a type mismatch when checking for local paths, potential KeyError and AttributeError exceptions during JSON expansion and metadata access, and a resource leak due to an unclosed TarFile stream.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 262e82a. Configure here.

Signed-off-by: Hyunoh-Yeo <[email protected]>
@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Nov 10, 2026
@AarryaSaraf

Copy link
Copy Markdown
Contributor

Returning grayscale images as (H, W, 1) breaks writing them back: write_webdataset's default encoder hands the array to PIL.Image.fromarray, which rejects the trailing 1 axis. For eg., with a shard holding a 28x28 grayscale 000.png and 000.cls:

ds = ray.data.read_webdataset("shards/")
ds.take(1)[0]["png"].shape   # (28, 28, 1)
ds.write_webdataset("out/")
# TypeError: Cannot handle this data type: (1, 1, 1), |u1

This also changes the shape for every all-grayscale dataset, not only mixed ones.

@Hyunoh-Yeo

Copy link
Copy Markdown
Contributor Author

@AarryaSaraf Thanks for pointing this out! I reproduced it and fixed it. The encoder now drops the third axis when it has size 1, before PIL.Image.fromarray.

For the shape change, I would keep 3D in the reader. Whether a dataset mixes grayscale and color is only known after reading. Without the expansion, a chunk that mixes them fails to concatenate, and a grayscale-only chunk next to a color chunk silently comes out as (1, H, W).

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

webdataset_utils.py copies the V1 helpers as they are on master, so it doesn't have the fixes from #67896 (open, approved), which changes the same code in V1. use_datasource_v2 defaults to True, so after this PR these are what read_webdataset returns by default. Same tar files read with read_webdataset(..., override_num_blocks=1) on the merge base 3e20c5f (V1), on #67896's head f412c42 (V1), and on 794a4a6 (V2):

case master, V1 #67896, V1 this PR, V2
expand_json, JSON field also a member (txt) AttributeError member's txt kept ValueError
expand_json, one sample without .json KeyError reads, n is float64 reads, n is int64
.json is ["a"] "a" ["a"] "a"
["a"] in the first 512 samples, ["a", "b"] after reads (Python objects) list<string> fails
0.jpeg, 0.JPG, 0.TXT raw bytes decoded raw bytes

Only the fourth row is worse than master (first inline comment). The rest will become V1/V2 differences once #67896 merges, and the planned follow-up that makes V1 import from datasource_v2 would undo #67896 in V1. Whichever of the two lands second probably needs to carry the other's changes.

test_webdataset.py on 794a4a6: 50 passed (WSL, Python 3.12, pyarrow 26.0.0). This PR's V1 path gives the same results as master for every row above.

Comment on lines +395 to +398
yield {
k: v[0] if isinstance(v, list) and len(v) == 1 else v
for k, v in sample.items()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This unwrapping makes a column's type depend on the values: a .json member holding ["a"] comes out as the string "a", while ["a", "b"] stays a list. V1 ends up with a pandas object column, so it still reads. Here each 512-sample chunk becomes its own Arrow table, so a shard whose first 512 samples hold one-element lists and the rest two-element ones fails in the read task, with both take_all() and iter_batches():

ArrowSchemaUnificationError: Error converting data to Arrow: Failed to unify schemas across 2 blocks.
pyarrow.lib.ArrowTypeError: Unable to merge: Field json has incompatible types: string vs list<item: string>

Master reads the same shard. Unlike the uint8/uint16 limitation in the description, the data here has a single type. The [v] in the expand_json loop above is only there so this line can take it off again; #67896 removes both in V1, and with that the shard reads as list<string>.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for pointing out. Removed the [v] wrapping and the unwrapping so a single element list stays a list and the shard reads as list

sample[key] = value.decode("utf-8")
elif extension in ["cls", "cls2"]:
sample[key] = int(value.decode("utf-8"))
elif extension in ["jpg", "png", "ppm", "pgm", "pbm", "pnm"]:

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.

jpeg isn't in this list, and the extension isn't lowercased on L260, so 0.jpeg, 0.JPG and 0.TXT come back as raw binary. Same as master V1; #67896 adds "jpeg" here and .lower() on the extension.

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.

Agreed! I'd keep this out of scope for this PR, since #67896 is already handling it thoroughly. Whichever lands second can carry the changes over to the other.

Comment on lines +388 to +393
if k in sample:
raise ValueError(
f"expand_json can't add JSON field {k!r} to sample "
f"{sample.get('__key__')!r} in {path}: the sample already "
f"has a column named {k!r}."
)

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.

#67896 handles this case the other way: it keeps the sample's own value, and documents that in the expand_json docstring of read_webdataset ("Keys already present in the sample take precedence over keys in the JSON object"). Either choice seems fine, but the two paths should probably agree, since that docstring covers both. This also raises when the JSON object has a field named json, i.e. the member being expanded.

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.

Agreed the two paths should match. Since master also fails on this case (the only difference is that this PR displays the error with a clearer pessage) and #67896 already defines the behavior along with the docstring, I'd keep this out of scope here too.

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

Re-ran on d881125. The shard with ["a"] in the first 512 samples and ["a", "b"] after now reads in V2 as a single list<string> column (1024 rows through take_all(), to_pandas() and repartition(1).count()), and the V1 path still matches master on every row of my table. test_webdataset.py: 51 passed.

One behavior change worth knowing about: with V2 on by default, a .json holding ["a"] now comes back as ["a"] rather than master's "a". That's what #67896 does in V1 too, so the two paths will agree once both land. Agreed on leaving the other two to whichever PR lands second.

@AarryaSaraf

Copy link
Copy Markdown
Contributor

@AarryaSaraf Thanks for pointing this out! I reproduced it and fixed it. The encoder now drops the third axis when it has size 1, before PIL.Image.fromarray.

For the shape change, I would keep 3D in the reader. Whether a dataset mixes grayscale and color is only known after reading. Without the expansion, a chunk that mixes them fails to concatenate, and a grayscale-only chunk next to a color chunk silently comes out as (1, H, W).

Makes sense, thanks. The padding covers images, but .npy members (or a custom decoder's arrays) still hit it. For eg., with shards/ holding one tar of (4, 5) .npy members and one of (4, 5, 3):

ds = ray.data.read_webdataset("shards/")
batch = next(iter(ds.iter_batches(batch_size=200, batch_format="numpy")))
{a.shape for a in batch["npy"]}   # {(4, 5, 3), (1, 4, 5)}

This comes from Ray's tensor concat (Parquet hits it too), so the fix can be separate. Could you note it in read_webdataset's docstring, along with grayscale images coming back as (H, W, 1)?

chunk = []
for row in rows:
chunk.append(row)
if len(chunk) >= WEBDATASET_READ_CHUNK_SIZE:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The reader holds 512 decoded samples before it cuts a table, so a read task's peak memory grows with sample size instead of staying near target_max_block_size.

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.

Agreed! I also added additional cutting condition when it reaches target_max_block_size

@@ -0,0 +1,395 @@
# Copyright NVIDIA Corporation 2023
# SPDX-License-Identifier: Apache-2.0
"""WebDataset read helpers shared by the V2 WebDataset datasource and reader."""

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.

Can V1 import these helpers and _ALLOWED_PIL_FORMATS from here in this PR instead of a follow-up? The module docstring should say some functions are called in V1 too. Each function header should include this info if its called in V1

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.

Resolved!

if self._decoder is None
else WEBDATASET_ENCODING_RATIO_DECODED
)
return RoundRobinPartitioner(

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.

When several shards share a read task, rows come out of shard order even with preserve_order=True. For eg., with shards/ holding shard-00.tar … shard-07.tar, one sample each (keys 00 … 07):

ray.data.DataContext.get_current().execution_options.preserve_order = True
ds = ray.data.read_webdataset("shards/", override_num_blocks=4)
[r["__key__"] for r in ds.take_all()]   # ['00', '04', '01', '05', '02', '06', '03', '07']

RoundRobinPartitioner doesn't keep input order and adding another partitioner here would be too big of a change. Can you document this for now? This can be fixed in a follow up

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.

Reproduced the issue. I have documented it in read_api.py and noted in get_file_partitioner with a TODO to use an order-preserving partitioner. I'll fix it in a follow-up!

""" # noqa: E501

ctx = DataContext.get_current()
if ctx.use_datasource_v2:

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.

Nit: use_datasource_v2's docstring in context.py still says only read_parquet() and read_orc() route through V2. Could you add read_webdataset() there?

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.

fixed!

WebDatasetDatasourceV2,
)

datasource_v2 = WebDatasetDatasourceV2(

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.

A field whose dtype differs between shards fails the whole read.
The description lists this under known limitations; read_webdataset's docstring should say it too

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.

reproduced the issue and noted it!


schema: Optional[pa.Schema]
filesystem: "FileSystem"
decoder: Optional[Any] = True

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.

Could decoder, fileselect, filerename and suffixes use the types from WebDatasetDatasourceV2.__init__ (Optional[Union[bool, str, Callable, list]] for decoder, Optional[Union[list, Callable]] for the rest) instead of Optional[Any]? Same in WebDatasetReader.__init__.

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.

fixed!

from pyarrow.fs import FileSystem


def rows_to_arrow(rows: List[Dict[str, Any]]) -> pa.Table:

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.

Nit: could rows_to_arrow be private (_rows_to_arrow), with BlockAccessor and BlockType imported at module level as parquet_file_reader.py does? Its only caller is _finalize.

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.

Done

# The resolved paths above lose their URI scheme; lineage tracking
# reads the caller's paths through ``source_paths``.
self._source_paths: List[str] = _normalize_paths_to_strings(paths)
# Retry ``DataContext.retried_io_errors`` on every filesystem call.

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.

Nit: this comment and the one at line 156 say what the next line does without adding anything

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.

Done

@pytest.mark.parametrize(
"expand_grayscale, expected_gray_shape", [(False, (3, 4)), (True, (3, 4, 1))]
)
def test_default_decoder_expand_grayscale(expand_grayscale, expected_gray_shape):

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.

Could the tests be trimmed? Each of these tests an internal, pins a known failure, or repeats coverage:

  • test_default_decoder_expand_grayscale: both shapes are already covered through read_webdataset by test_read_webdataset_v2_grayscale_and_color_images and test_webdataset_grayscale_round_trip.
  • test_read_webdataset_v2_mixed_image_dtypes, test_read_webdataset_v2_npy_mixed_ndim: they assert known failures, so fixing those breaks the tests.
  • test_webdataset_datasource_v2_keeps_source_paths: checks the constructor stores its argument.
  • test_group_by_keys_duplicate_member_without_meta: read_webdataset always passes meta.
  • The two expand_json tests can be asserts in test_webdataset_expand_json.
  • test_read_webdataset_v2_one_element_lists: list("a") == ["a"] also holds for the unwrapped value, so it only fails through the cross-chunk concat; two samples, ["ab"] and ["a", "b"], catch it in one chunk.
  • _FailOnceFileSystemHandler can be a LocalFileSystem subclass behind pa.fs.PyFileSystem(pa.fs.FSSpecHandler(...)) that overrides _open, ~10 lines instead of 56.

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.

Done, trimmed as instructed!

Signed-off-by: Hyunoh-Yeo <[email protected]>
@richardliaw

Copy link
Copy Markdown
Contributor

@Hyunoh-Yeo still looking for addressing the below comments - thanks

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]>
@Hyunoh-Yeo

Copy link
Copy Markdown
Contributor Author

@AarryaSaraf Thanks for pointing this out! I reproduced it and fixed it. The encoder now drops the third axis when it has size 1, before PIL.Image.fromarray.
For the shape change, I would keep 3D in the reader. Whether a dataset mixes grayscale and color is only known after reading. Without the expansion, a chunk that mixes them fails to concatenate, and a grayscale-only chunk next to a color chunk silently comes out as (1, H, W).

Makes sense, thanks. The padding covers images, but .npy members (or a custom decoder's arrays) still hit it. For eg., with shards/ holding one tar of (4, 5) .npy members and one of (4, 5, 3):

ds = ray.data.read_webdataset("shards/")
batch = next(iter(ds.iter_batches(batch_size=200, batch_format="numpy")))
{a.shape for a in batch["npy"]}   # {(4, 5, 3), (1, 4, 5)}

This comes from Ray's tensor concat (Parquet hits it too), so the fix can be separate. Could you note it in read_webdataset's docstring, along with grayscale images coming back as (H, W, 1)?

Added both to read_webdataset's docstring!

Signed-off-by: Hyunoh-Yeo <[email protected]>
Signed-off-by: Hyunoh-Yeo <[email protected]>
Signed-off-by: Hyunoh-Yeo <[email protected]>

# Conflicts:
#	python/ray/data/context.py
Signed-off-by: Hyunoh-Yeo <[email protected]>

# Conflicts:
#	python/ray/data/context.py
if self._decoder is None
else WEBDATASET_ENCODING_RATIO_DECODED
)
# TODO: Use an order-preserving partitioner.

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.

Since this went up, read_text, read_csv and read_json on V2 started keeping file order under preserve_order by giving the partitioner a single bucket (see get_file_partitioner in text_datasource_v2.py). The same lines here would fix shard order, and the TODO and the first bullet of the read_webdataset note could go:

if DataContext.get_current().execution_options.preserve_order:
    # One bucket fills in listing order; several deal shards round-robin.
    hints = dataclasses.replace(hints, num_buckets=1)

With 8 shards of 2 MiB and override_num_blocks=4, keys come back as 00 01 02 … 07 instead of 00 04 01 05 …. Same trade-off as the other formats: with preserve_order on, small shards get packed into fewer read tasks.


Generated by Claude Code

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.

Added the condition.

self._target_block_size is not None
and chunk_bytes >= self._target_block_size
):
yield self._finalize(chunk, unit, rows_before)

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.

Thanks for adding the byte cap. One more small thing on memory: chunk still points at the decoded rows while the table is yielded, so whatever processes that block next (a fused map_batches, say) runs with both the rows and the table alive. Building the table first and clearing chunk before the yield frees the rows:

table = self._finalize(chunk, unit, rows_before)
rows_before += len(chunk)
chunk = []
chunk_bytes = 0
yield table

On a shard of 64 × 4 MiB .npy samples with a 64 MiB target, the reader's Python/NumPy memory at each yield drops from ~139 MiB to ~76 MiB.


Generated by Claude Code

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.

thank you for pointing out. updated!

compression = infer_compression(path)
if compression != "snappy":
return self._filesystem.open_input_stream(path, **open_args)
# Arrow can't decompress Snappy as a stream, so decompress the whole

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This Snappy/HDFS branch duplicates read_snappy_buffer from datasource_v2/common/line_chunkable_file_reader.py. Could you import that and use pa.BufferReader(read_snappy_buffer(path, self._filesystem)) here, as the JSON reader does, so there's one copy of the decompression?


Generated by Claude Code

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.

done

Comment thread python/ray/data/read_api.py Outdated
With ``DataContext.use_datasource_v2`` enabled:

- ``preserve_order`` doesn't guarantee shard order.
- A field whose dtype differs between shards fails the read.

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.

These two bullets happen inside one shard too, not only between shards: a block is cut every 512 samples (or at the target block size), and blocks are what get concatenated. For example, one tar with 512 uint8 .npy members followed by 88 uint16 ones fails at ds.schema() with Can't unify tensor types with divergent scalar types. Maybe "A field whose dtype differs between samples, even within one shard, can fail the read", and the same wording for the dimensions bullet.


Generated by Claude Code

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.

fixed the docstring

@@ -0,0 +1,56 @@
from dataclasses import dataclass, field

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.

nit: this file has no module docstring and the reader's is one line.


Generated by Claude Code

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.

done

@AarryaSaraf
AarryaSaraf self-requested a review November 23, 2026 23:12
@richardliaw
richardliaw merged commit 91aa765 into ray-project:master Nov 24, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants