Repository navigation
[data] Improve JSON read error context - #66878
Conversation
Signed-off-by: Yin-1022 <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request improves error reporting when reading invalid JSON or JSONL files by including the file path in the raised exceptions. Specifically, it catches JSONDecodeError and ValueError during reading and chunk size estimation, raising descriptive errors with the file path, and adds corresponding unit tests. The feedback suggests combining the two identical try-except ValueError blocks in _read_stream into a single block to eliminate code duplication and improve readability.
| try: | ||
| chunksize = self._estimate_chunksize(f) | ||
| except ValueError as e: | ||
| raise ValueError( | ||
| f"Failed to read JSON file: {path}. " | ||
| "Please check that the file contains valid line-delimited JSON." | ||
| ) from e | ||
|
|
||
| try: | ||
| with StrictBufferedReader(f, buffer_size=self._BUFFER_SIZE) as stream: | ||
| if chunksize is None: | ||
| # When chunksize=None, pandas returns DataFrame directly | ||
| # (no context manager). | ||
| df = pd.read_json(stream, chunksize=chunksize, lines=True) | ||
| yield _cast_range_index_to_string(df) | ||
| else: | ||
| # When chunksize is a number, pandas returns JsonReader | ||
| # (supports context manager). | ||
| with pd.read_json( | ||
| stream, chunksize=chunksize, lines=True | ||
| ) as reader: | ||
| for df in reader: | ||
| yield _cast_range_index_to_string(df) | ||
| except ValueError as e: | ||
| raise ValueError( | ||
| f"Failed to read JSON file: {path}. " | ||
| "Please check that the file contains valid line-delimited JSON." | ||
| ) from e |
There was a problem hiding this comment.
The two try-except ValueError blocks in _read_stream are identical and duplicate both the exception handling logic and the error message. They can be combined into a single try-except block to improve readability and maintainability.
try:\n chunksize = self._estimate_chunksize(f)\n with StrictBufferedReader(f, buffer_size=self._BUFFER_SIZE) as stream:\n if chunksize is None:\n # When chunksize=None, pandas returns DataFrame directly\n # (no context manager).\n df = pd.read_json(stream, chunksize=chunksize, lines=True)\n yield _cast_range_index_to_string(df)\n else:\n # When chunksize is a number, pandas returns JsonReader\n # (supports context manager).\n with pd.read_json(\n stream, chunksize=chunksize, lines=True\n ) as reader:\n for df in reader:\n yield _cast_range_index_to_string(df)\n except ValueError as e:\n raise ValueError(\n f\"Failed to read JSON file: {path}. \"\n \"Please check that the file contains valid line-delimited JSON.\"\n ) from eThere was a problem hiding this comment.
I've consolidated them into a single try-except block while keeping the original parser error message and exception chaining. Thanks!
|
There's a linter error in CI https://buildkite.com/ray-project/microcheck/builds/55907/canvas?sid=01a11f2c-718c-456b-8814-5f15dcb14ce6&tab=output Please run the following command to fix the linter error |
|
Hi @Yin-1022, I was also able to reproduce this behavior across the Ray worker-to-driver boundary with Ray 2.59.0 and pandas 2.3.3: After including Original error: {e} in the outer message, all three checks became True. |
Signed-off-by: Yin-1022 <[email protected]>
Signed-off-by: Yin-1022 <[email protected]>
Signed-off-by: Yin-1022 <[email protected]>
Signed-off-by: Yin-1022 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 47abe07. Configure here.
Signed-off-by: Yin-1022 <[email protected]>
Signed-off-by: Yin-1022 <[email protected]>
Signed-off-by: Yin-1022 <[email protected]>
Signed-off-by: Yin-1022 <[email protected]>
Signed-off-by: Yin-1022 <[email protected]>
Signed-off-by: Yin-1022 <[email protected]>
| # Invalid UTF-8 in the first row. | ||
| b'{"name": "\xff"}\n', | ||
| # Invalid UTF-8 in a later row. | ||
| b'{"name": "valid"}\n{"name": "\xff"}\n', |
There was a problem hiding this comment.
Nit: this second case still fails inside _estimate_chunksize, not in the streaming read, because pandas' TextIOWrapper decodes in 8 KiB chunks and the whole 32-byte file lands in the first chunk. To actually exercise the "estimation succeeds, streaming read fails" branch (like the ValueError parametrization above does), the valid rows need to exceed 8 KiB, e.g.:
| b'{"name": "valid"}\n{"name": "\xff"}\n', | |
| b'{"name": "valid"}\n' + b'{"name": "' + b"x" * 100 + b'"}\n' * 100 + b'{"name": "\xff"}\n', |
There was a problem hiding this comment.
I see! I've updated the second test case to include more than 8 KiB of valid JSONL data before the invalid UTF-8 sequence.
I also verified both execution paths locally:
- chunk-size-estimation: Raises UnicodeDecodeError before _estimate_chunksize() returns.
- streaming-read: _estimate_chunksize() completes successfully, and the error occurs during the subsequent streaming read.
Both regression tests pass, with the UnicodeDecodeError subtype, original cause, and offending file path preserved.
Thanks for the suggestion!
Signed-off-by: Yin-1022 <[email protected]>
Add a nomination under `fellowship/ray/` Suggested level: 20k Highlights from 2026-09-01 to 2026-10-11: - [Contribution](https://github.com/opensource4you/readme/blob/main/fellowship/ray/fellow-contribution/400Ping/September/report.md) - Landed the Ray Data roadmap feature task-based shuffle v2 for `sort()`: ~35% faster, ~24% lower object-store peak and no spilling compared with v1 on an 11.92 GiB sort ([#64875](ray-project/ray#64875)) - As a senior contributor who can already approve Ray Data PRs, helps the community a lot by reviewing and guiding other contributors, for example, reviewing other fellows' PRs ([#66878](ray-project/ray#66878), [#65278](ray-project/ray#65278)) - Spent over a month with Ray Data maintainer Balaji researching how to cut Ray Data release test launch time([#66284](ray-project/ray#66284)) - Migrating the CSV datasource to DataSourceV2, with a design doc and a 5-PR stack for the Ray Data maintainers ([#65743](ray-project/ray#65743))
Add a nomination under `fellowship/ray/` Suggested level: 30k Highlights from 2026-09-01 to 2026-10-11: - [Contribution](https://github.com/opensource4you/readme/blob/main/fellowship/ray/fellow-contribution/viiccwen/September/report.md) - Merged 10 Ray Data PRs and filed 8 issues in 6 weeks - Made shuffle tasks up to 12.84x faster by pinning the fused map function, so large UDF closures are no longer serialized again for every shuffle task ([#65480](ray-project/ray#65480)) - Built a memory observability series to help users avoid OOM: exported task peak USS and logical memory metrics with Grafana charts ([#65666](ray-project/ray#65666), [#66044](ray-project/ray#66044)), added a warning with a suggested memory value when it is set below 1.25x max USS ([#65512](ray-project/ray#65512)), and updated the OOM prevention docs ([#65509](ray-project/ray#65509)) - Found, reported and fixed silent data loss in hash-shuffle (V2) anti joins, where rows were dropped when the other side was empty and had an unknown schema ([#66126](ray-project/ray#66126)) - Reviewed other fellows' PRs with suggestions ([#66878](ray-project/ray#66878)) - Merged the most PRs and filed the most issues of all Ray Fellowship participants - Solid work for an early contributor
fellowship: 提名 Yin-1022 (ray, 2026-11) 建議等級:2 萬 - [x] 關係人宣告:提名人與被提名者無親屬、僱傭、財務、業務合作或其他可能影響公正判斷之利害關係 - 在兩個月內自己找到 8 個 Ray Data Issue 並開了 PR,其中 6 個 PR 被 Merged ([Merged PRs](https://github.com/ray-project/ray/pulls?q=is%3Apr+author%3AYin-1022+is%3Amerged+merged%3A%3C%3D2026-11-24)) - 兩個月內共 review 28 個 PR,其中 10 個提出的問題有被作者採納修正([#68402](https://github.com/ray-project/ray/pull/68402)、[#68290](https://github.com/ray-project/ray/pull/68290)、[#67524](https://github.com/ray-project/ray/pull/67524)) - 大部分 PR 都有清楚列出 Before/After 的差距,performance 相關的會附上數據 ([#67935](ray-project/ray#67935), [#68403](ray-project/ray#68403)) - 對於 Maintainer 的 Review 會清楚了解之後回覆 ([#67935 comment](ray-project/ray#67935 (comment)), [#66878 comment](ray-project/ray#66878 (comment)), [#67505 comment](ray-project/ray#67505 (comment)))

Description
Improves error messages for malformed JSON and JSONL inputs in ray.data.read_json() by including the offending input file path while preserving the original parsing diagnostics.
Previously, parsing errors from ArrowJSONDatasource and PandasJSONDatasource did not identify which input file caused the failure, making debugging difficult when reading multiple files.
Changes
Before / After Comparison
The following examples show the relevant exception messages, with Ray's surrounding task traceback omitted for clarity.
Before:
JSONDecodeError: Expecting value: line 1 column 52 (char 51)After:
JSONDecodeError: Failed to read JSON file: /path/to/malformed.json. Please check that the file contains valid JSON. Expecting value: line 1 column 52 (char 51)Before:
ValueError: Expected object or valueAfter:
ValueError: Failed to read JSON file: /path/to/malformed.jsonl. Please check that the file contains valid line-delimited JSON. Original error: Expected object or valueThe updated messages identify the offending file while retaining the original parser diagnostics.
Related issues
Fixes #66877
Additional information