Skip to content

[Data] Fix WebDataset expand_json key collision, 1-element list unwrapping, and .jpeg decoding - #67896

Open
deep1blue wants to merge 5 commits into
ray-project:masterfrom
deep1blue:fix/webdataset-decoder-and-expand-json
Open

deep1blue wants to merge 5 commits into
ray-project:masterfrom
deep1blue:fix/webdataset-decoder-and-expand-json

Conversation

@deep1blue

@deep1blue deep1blue commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Fixes four correctness issues in ray.data's WebDatasetDatasource (python/ray/data/_internal/datasource/webdataset_datasource.py):

  1. expand_json=True key collision and missing .json handling in _read_stream:
    • Previously, expanding parsed_json initialized sample[k] = [] when k not in sample and then called sample[k].append(v). If parsed_json contained a key k that collided with an existing non-list sample entry (e.g., "txt", "cls", "__key__", or "json"), sample[k].append(v) raised AttributeError: '...' object has no attribute 'append' (or mutated an existing list value).
    • Additionally, in heterogeneous WebDataset archives where not every sample has a .json member, sample["json"] raised KeyError: 'json' when expand_json=True.
    • Assigning sample[k] = v when k not in sample and guarding on "json" in sample avoids both crashes and removes the redundant intermediate list wrapping.
  2. Unconditional unwrapping of single-element list values in _read_stream:
    • _read_stream previously applied {k: v[0] if isinstance(v, list) and len(v) == 1 else v for k, v in sample.items()} to every row solely to undo the sample[k] = [v] wrapping from expand_json. When expand_json=False, this unconditionally unwrapped any legitimate 1-element list column (e.g., a .json, .mp, or .pkl payload containing ["only_item"]) into a scalar while leaving [] and 2+-element lists as list, producing inconsistent column types across rows.
  3. .jpeg, .text, and case-insensitive extension symmetry between _default_encoder and _default_decoder:
    • _default_encoder encoded "jpeg" images (extension in ["jpg", "jpeg", "png", ...]), whereas _default_decoder omitted "jpeg" and checked extension case-sensitively (extension in ["jpg", "png", ...]), leaving .jpeg files written by Dataset.write_webdataset() or uppercase extensions (.JPG, .TXT, etc.) undecoded as raw bytes.
  4. Safe meta.get('__url__') lookup in _group_by_keys:
    • Consistent with the non-contiguous key error path in _group_by_keys, the duplicate-suffix ValueError now uses meta.get('__url__') instead of meta['__url__'] so callers passing default meta=None receive the descriptive ValueError instead of KeyError: '__url__'.

Acknowledgments

Credits to @goutamvenkat-anyscale (#67752), @Hyunoh (#65394), @stripathy-anyscale (#63407), and @bveeramani (#63469) for their recent improvements to WebDatasetDatasource safety, chunked DataFrame emission, and key grouping, and to @Yin-1022 and @rayo5o for their reviews, expand_json docstring precedence clarification, and test validation.

Related issue number

N/A

Checks

Behavior Changes & Release Notes

  1. Preserving 1-element list values across all read_webdataset reads: Previously, _read_stream unwrapped any 1-element list column (v[0] if isinstance(v, list) and len(v) == 1 else v) on every sample, regardless of expand_json. Removing the [v] wrapping in expand_json also removes that unconditional unwrap, so 1-element lists (for example a .json member whose value is ["x"] with expand_json=False, or a 1-element list field inside an expanded JSON object) are now preserved as ["x"] instead of being unwrapped to "x".
  2. Case-insensitive extension matching in _default_decoder and _default_encoder: Extensions are now normalized with .lower() before matching:
    • Uppercase extensions such as .TXT, .JPG/.JPEG, .JSON, .CLS, and .NPY are now decoded/encoded consistently with their lowercase counterparts (instead of remaining raw bytes on read).
    • Uppercase unsafe extensions (.PKL, .PICKLE, .PT, .PTH) are now also blocked by the default unsafe-deserialization guard unless RAY_DATA_WEBDATASET_ALLOW_UNSAFE_DESERIALIZATION=1 is set.

…pping, and .jpeg decoding

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>
@deep1blue
deep1blue requested a review from a team as a code owner November 6, 2026 08:45

@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 improves the WebDataset datasource by adding case-insensitive extension matching, supporting jpeg and text extensions, safeguarding JSON expansion when the json key is missing, and simplifying the JSON expansion logic. It also adds comprehensive test coverage for these changes. The reviewer feedback suggests optimizing the decoder and encoder loops by checking for metadata keys (starting with __) before performing string operations, and adding a defensive type check to ensure parsed_json is a dictionary before calling .items().

Comment on lines 251 to 254
for key, value in sample.items():
extension = key.split(".")[-1]
extension = key.split(".")[-1].lower()
if key.startswith("__"):
continue

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.

medium

We can optimize this loop by checking if the key starts with __ before performing the string split and .lower() operations. Since metadata keys like __key__ and __url__ are present in every sample, skipping these operations for them can save a significant number of CPU cycles over large datasets.

    for key, value in sample.items():
        if key.startswith("__"):
            continue
        extension = key.split(".")[-1].lower()

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 in 30ecb8e424: moved if key.startswith("__"): continue before key.split(".")[-1].lower() in _default_decoder.

Comment on lines 324 to 327
for key, value in sample.items():
extension = key.split(".")[-1]
extension = key.split(".")[-1].lower()
if key.startswith("__"):
continue

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.

medium

Similarly to _default_decoder, we can optimize this loop by checking if the key starts with __ before performing the string split and .lower() operations to avoid redundant work on metadata keys.

    for key, value in sample.items():
        if key.startswith("__"):
            continue
        extension = key.split(".")[-1].lower()

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 in 30ecb8e424: moved if key.startswith("__"): continue before key.split(".")[-1].lower() in _default_encoder.

Comment on lines 467 to +469
for k, v in parsed_json.items():
if k not in sample:
sample[k] = []
sample[k].append(v)
rows.append(
{
k: v[0] if isinstance(v, list) and len(v) == 1 else v
for k, v in sample.items()
}
)
sample[k] = v

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.

medium

If parsed_json is not a dictionary (e.g., if the JSON file contains a list or a primitive value), calling .items() will raise a confusing AttributeError. Adding a defensive check to ensure parsed_json is a dictionary and raising a clear TypeError improves error clarity.

Suggested change
for k, v in parsed_json.items():
if k not in sample:
sample[k] = []
sample[k].append(v)
rows.append(
{
k: v[0] if isinstance(v, list) and len(v) == 1 else v
for k, v in sample.items()
}
)
sample[k] = v
if not isinstance(parsed_json, dict):
raise TypeError(
f"Expected a JSON object (dict) for expand_json, but got {type(parsed_json)}"
)
for k, v in parsed_json.items():
if k not in sample:
sample[k] = v

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 in 30ecb8e424: added if not isinstance(parsed_json, dict): raise TypeError(...) before parsed_json.items() in _read_stream, plus unit test coverage in test_webdataset_expand_json_edge_cases.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Nov 6, 2026
@Yin-1022

Yin-1022 commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

I independently tested several edge cases involving JSON expansion, missing fields, key collisions, nested values, single-element lists, and custom decoder outputs. I also verified image encoding/decoding across different extensions and casing.

No issues found in the tested scenarios, LGTM! Thanks for the fixes!

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

Microcheck doesn't run the webdataset tests, so I ran test_webdataset.py locally. At 30ecb8e all 29 pass. With the same test file against the merge base (255cf35), exactly the four new tests fail, each for the reason in the description: AttributeError on the txt collision, ["only_item"] coming back as the string "only_item", KeyError: '__url__', and the .jpeg / .JPG images left as bytes.

A few inputs the tests don't cover, read through _read_stream on both commits:

  • 512 samples without .json followed by 512 with it, so one read chunk has no json column at all: read_webdataset(..., expand_json=True).to_pandas() returns all 1,024 rows, with the missing values as null. The merge base raises KeyError: 'json'.
  • Collisions with txt, cls, __key__ and json itself: the sample's values are kept (inline comment on the docstring). The merge base raises AttributeError, with or without a decoder.
  • 0.JSON: the decoder now parses it, but it isn't expanded, because the expand step looks up the exact key "json". The merge base raised KeyError: 'json' here, so this goes from an error to silently not expanding. Probably rare enough to leave, just mentioning it since the PR makes the decoder case-insensitive.

Environment: Python 3.12, pyarrow 26, pandas 3.0, webdataset 1.0.2 (the version in the CI lock files).

Comment on lines +94 to +95
import json
import pyarrow.fs

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 is the only failure in microcheck (lint: pre_commit): ruff's import sorting wants a blank line between the stdlib and third-party imports here.

Suggested change
import json
import pyarrow.fs
import json
import pyarrow.fs

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 @rayo5o — added the blank line between import json and import pyarrow.fs in f412c42b21.

if not isinstance(parsed_json, dict):
raise TypeError(
f"Expected a JSON object (dict) for expand_json, but got {type(parsed_json)}"
)
for k, v in parsed_json.items():
if k not in sample:

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.

On a collision the file's value wins and the JSON value is dropped with no warning. With 0.txt = file_txt, 0.cls = 3 and 0.json = {"txt": "json_txt", "cls": 7, "x": 1}, the row comes back with txt="file_txt", cls=3, x=1. Not crashing seems right to me, but the user can't tell a field went missing. Could the expand_json docstring in read_api.py say that keys already in the sample take precedence? It currently reads "expand JSON objects into individual samples".

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 @rayo5o! Updated the expand_json docstring in read_webdataset (python/ray/data/read_api.py) in f412c42b21 to note that keys already present in the sample take precedence over keys in the JSON object, and thank you for running the 29-test test_webdataset.py suite and multi-chunk _read_stream checks.

…in test_webdataset.py

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>

@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 test_webdataset.py at f412c42: 29 passed. The docstring and import changes are what I asked for, and the rest is unchanged since my review.

@abhishekverma-ray abhishekverma-ray added the go add ONLY when ready to merge, run all tests label Nov 18, 2026

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

Thanks, the crash fixes (the expand_json key collision and .jpeg) are real. Two changes affect every read_webdataset user, though, and they aren't mentioned in the description:

  1. The unwrapping of one-element lists is removed for all reads, not only expand_json. A .json member whose value is ["x"] now reads as ["x"] instead of "x". That's more consistent, but it changes existing output.
  2. extension.lower() makes the decoder case-insensitive for every extension:
    • A tar with 0.PKL, .PT or .PTH used to read as raw bytes, and now fails with "Refusing to unpickle".
    • Uppercase .TXT, .JPG, .JSON, .CLS and .NPY columns change type (bytes → str, ndarray, dict, int).

Could you either call both out in the description (and a release note), or narrow them, e.g. lowercase only image extensions?

Tests:

  • test_webdataset_expand_json_edge_cases:
    • Keep the txt collision assert and fold it into the existing test_webdataset_expand_json.
    • The single_list and count asserts pass on master.
    • The non-dict case calls the private _read_stream. read_webdataset(...).take_all() under pytest.raises(TypeError) would cover it through the public API.
  • test_webdataset_duplicate_suffix_without_url_meta: the only caller of _group_by_keys always passes meta, so this branch can't be reached.
  • test_default_encoder_decoder_jpeg_and_case_insensitive: adding jpeg / PHOTO.JPG keys to the existing test_webdataset_coding round trip would test this through the public API.
  • Please add "000000.PKL" to test_default_decoder_rejects_unsafe_extensions.

@deep1blue
deep1blue requested a review from a team as a code owner November 18, 2026 08:17
@deep1blue

Copy link
Copy Markdown
Contributor Author

Thanks @abhishekverma-ray! Updated ee9321bbc0 and the PR description:

  • Called out both user-visible behavior changes (preserving 1-element list values across all read_webdataset reads and case-insensitive extension matching in _default_decoder/_default_encoder, including blocking uppercase .PKL/.PT/.PTH) in the PR description / release notes.
  • Folded the txt key-collision assertion and the public-API read_webdataset(..., expand_json=True).take_all() non-dict TypeError check into test_webdataset_expand_json, and removed test_webdataset_expand_json_edge_cases.
  • Reverted the unreachable meta.get("__url__") change and removed test_webdataset_duplicate_suffix_without_url_meta.
  • Moved jpeg and PHOTO.JPG coverage into test_webdataset_coding and removed test_default_encoder_decoder_jpeg_and_case_insensitive.
  • Added "000000.PKL" to test_default_decoder_rejects_unsafe_extensions.

Verified locally with pytest python/ray/data/tests/datasource/test_webdataset.py -k "test_webdataset_expand_json or test_webdataset_preserves_single_element_list_without_expand_json or test_webdataset_coding or test_default_decoder_rejects_unsafe_extensions" (8 passed).

@deep1blue
deep1blue force-pushed the fix/webdataset-decoder-and-expand-json branch 3 times, most recently from 235a2ca to 49c8755 Compare November 26, 2026 00:33
@deep1blue
deep1blue force-pushed the fix/webdataset-decoder-and-expand-json branch from 49c8755 to 43f86db Compare November 26, 2026 00:34
@rayo5o

rayo5o commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

CI on 43f86db fails because the branch is still based on 255cf35, before #68017, so ray.data._internal.datasource_v2.formats.webdataset doesn't exist there (the dask job log shows the ModuleNotFoundError). With this PR's diff applied on master 8fd2958, test_webdataset.py passes (49 tests), so a rebase should clear most of it.

Checking on master, the new docstring line I suggested earlier, that keys already in the sample take precedence, only holds for V1. V2 is the default and raises on the same input: a sample with 000000.cls = 7 and {"cls": 99} in 000000.json gives ValueError: expand_json can't add JSON field 'cls' to sample '000000' ..., with or without this PR. The docstring should probably describe that, or say the precedence is V1 only.

Also, webdataset_datasource.py now replaces webdataset_utils._default_decoder at import time, so V2 gets case-insensitive extensions only because read_api.py imports the V1 module. Moving the lowercase and jpeg handling into _default_decoder in webdataset_utils.py would cover both paths without that.

…bdataset docstring

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>

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

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