Repository navigation
[Data] Fix WebDataset expand_json key collision, 1-element list unwrapping, and .jpeg decoding - #67896
[Data] Fix WebDataset expand_json key collision, 1-element list unwrapping, and .jpeg decoding#67896deep1blue wants to merge 5 commits into
Conversation
…pping, and .jpeg decoding Co-authored-by: Copilot <[email protected]> Signed-off-by: Parth Vadera <[email protected]>
There was a problem hiding this comment.
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().
| for key, value in sample.items(): | ||
| extension = key.split(".")[-1] | ||
| extension = key.split(".")[-1].lower() | ||
| if key.startswith("__"): | ||
| continue |
There was a problem hiding this comment.
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()There was a problem hiding this comment.
Done in 30ecb8e424: moved if key.startswith("__"): continue before key.split(".")[-1].lower() in _default_decoder.
| for key, value in sample.items(): | ||
| extension = key.split(".")[-1] | ||
| extension = key.split(".")[-1].lower() | ||
| if key.startswith("__"): | ||
| continue |
There was a problem hiding this comment.
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()There was a problem hiding this comment.
Done in 30ecb8e424: moved if key.startswith("__"): continue before key.split(".")[-1].lower() in _default_encoder.
| 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 |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
…and_json Co-authored-by: Copilot <[email protected]> Signed-off-by: Parth Vadera <[email protected]>
|
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
left a comment
There was a problem hiding this comment.
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
.jsonfollowed by 512 with it, so one read chunk has nojsoncolumn at all:read_webdataset(..., expand_json=True).to_pandas()returns all 1,024 rows, with the missing values as null. The merge base raisesKeyError: 'json'. - Collisions with
txt,cls,__key__andjsonitself: the sample's values are kept (inline comment on the docstring). The merge base raisesAttributeError, 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 raisedKeyError: '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).
| import json | ||
| import pyarrow.fs |
There was a problem hiding this comment.
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.
| import json | |
| import pyarrow.fs | |
| import json | |
| import pyarrow.fs |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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".
There was a problem hiding this comment.
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]>
abhishekverma-ray
left a comment
There was a problem hiding this comment.
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:
- The unwrapping of one-element lists is removed for all reads, not only
expand_json. A.jsonmember whose value is["x"]now reads as["x"]instead of"x". That's more consistent, but it changes existing output. extension.lower()makes the decoder case-insensitive for every extension:- A tar with
0.PKL,.PTor.PTHused to read as raw bytes, and now fails with "Refusing to unpickle". - Uppercase
.TXT,.JPG,.JSON,.CLSand.NPYcolumns change type (bytes → str, ndarray, dict, int).
- A tar with
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
txtcollision assert and fold it into the existingtest_webdataset_expand_json. - The
single_listandcountasserts pass on master. - The non-dict case calls the private
_read_stream.read_webdataset(...).take_all()underpytest.raises(TypeError)would cover it through the public API.
- Keep the
test_webdataset_duplicate_suffix_without_url_meta: the only caller of_group_by_keysalways passesmeta, so this branch can't be reached.test_default_encoder_decoder_jpeg_and_case_insensitive: addingjpeg/PHOTO.JPGkeys to the existingtest_webdataset_codinground trip would test this through the public API.- Please add
"000000.PKL"totest_default_decoder_rejects_unsafe_extensions.
|
Thanks @abhishekverma-ray! Updated
Verified locally with |
235a2ca to
49c8755
Compare
…heck Co-authored-by: Copilot <[email protected]> Signed-off-by: Parth Vadera <[email protected]>
49c8755 to
43f86db
Compare
|
CI on 43f86db fails because the branch is still based on 255cf35, before #68017, so 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 Also, |
…bdataset docstring Co-authored-by: Copilot <[email protected]> Signed-off-by: Parth Vadera <[email protected]>
Why are these changes needed?
Fixes four correctness issues in
ray.data'sWebDatasetDatasource(python/ray/data/_internal/datasource/webdataset_datasource.py):expand_json=Truekey collision and missing.jsonhandling in_read_stream:parsed_jsoninitializedsample[k] = []whenk not in sampleand then calledsample[k].append(v). Ifparsed_jsoncontained a keykthat collided with an existing non-list sample entry (e.g.,"txt","cls","__key__", or"json"),sample[k].append(v)raisedAttributeError: '...' object has no attribute 'append'(or mutated an existing list value)..jsonmember,sample["json"]raisedKeyError: 'json'whenexpand_json=True.sample[k] = vwhenk not in sampleand guarding on"json" in sampleavoids both crashes and removes the redundant intermediate list wrapping._read_stream:_read_streampreviously 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 thesample[k] = [v]wrapping fromexpand_json. Whenexpand_json=False, this unconditionally unwrapped any legitimate 1-element list column (e.g., a.json,.mp, or.pklpayload containing["only_item"]) into a scalar while leaving[]and 2+-element lists aslist, producing inconsistent column types across rows..jpeg,.text, and case-insensitive extension symmetry between_default_encoderand_default_decoder:_default_encoderencoded"jpeg"images (extension in ["jpg", "jpeg", "png", ...]), whereas_default_decoderomitted"jpeg"and checkedextensioncase-sensitively (extension in ["jpg", "png", ...]), leaving.jpegfiles written byDataset.write_webdataset()or uppercase extensions (.JPG,.TXT, etc.) undecoded as rawbytes.meta.get('__url__')lookup in_group_by_keys:_group_by_keys, the duplicate-suffixValueErrornow usesmeta.get('__url__')instead ofmeta['__url__']so callers passing defaultmeta=Nonereceive the descriptiveValueErrorinstead ofKeyError: '__url__'.Acknowledgments
Credits to @goutamvenkat-anyscale (#67752), @Hyunoh (#65394), @stripathy-anyscale (#63407), and @bveeramani (#63469) for their recent improvements to
WebDatasetDatasourcesafety, chunked DataFrame emission, and key grouping, and to @Yin-1022 and @rayo5o for their reviews,expand_jsondocstring precedence clarification, and test validation.Related issue number
N/A
Checks
git commit -s) in this PR.scripts/format.shto lint the changes in this PR.python/ray/data/tests/datasource/test_webdataset.py)Behavior Changes & Release Notes
read_webdatasetreads: Previously,_read_streamunwrapped any 1-elementlistcolumn (v[0] if isinstance(v, list) and len(v) == 1 else v) on every sample, regardless ofexpand_json. Removing the[v]wrapping inexpand_jsonalso removes that unconditional unwrap, so 1-element lists (for example a.jsonmember whose value is["x"]withexpand_json=False, or a 1-element list field inside an expanded JSON object) are now preserved as["x"]instead of being unwrapped to"x"._default_decoderand_default_encoder: Extensions are now normalized with.lower()before matching:.TXT,.JPG/.JPEG,.JSON,.CLS, and.NPYare now decoded/encoded consistently with their lowercase counterparts (instead of remaining rawbyteson read)..PKL,.PICKLE,.PT,.PTH) are now also blocked by the default unsafe-deserialization guard unlessRAY_DATA_WEBDATASET_ALLOW_UNSAFE_DESERIALIZATION=1is set.