Skip to content

[data] Improve JSON read error context - #66878

Merged
owenowenisme merged 12 commits into
ray-project:masterfrom
Yin-1022:fix-json-read-error-context
Oct 12, 2026
Merged

owenowenisme merged 12 commits into
ray-project:masterfrom
Yin-1022:fix-json-read-error-context

Conversation

@Yin-1022

@Yin-1022 Yin-1022 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

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

  • ArrowJSONDatasource
    • Add file path context to JSONDecodeError while preserving the existing JSONDecodeError type and parsing location information.
  • PandasJSONDatasource: (lines=True)
    • Add file path context for failures during chunk-size estimation and streaming reads.
    • Preserve the original pandas parser message in the resulting ValueError.
  • Tests
    • Add regression tests for malformed JSON, invalid UTF-8, and JSONL parsing failures during both chunk-size estimation and streaming reads.
    • Existing JSON fallback and error-handling tests passed.
    • Full JSON datasource test suite on Windows: 48 passed, 12 failed, 2 errors.

Before / After Comparison

The following examples show the relevant exception messages, with Ray's surrounding task traceback omitted for clarity.

  1. Malformed JSON (lines=False)
  • 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)

  1. Malformed JSONL (lines=True)
  • Before:
    ValueError: Expected object or value

  • After:
    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 value

The updated messages identify the offending file while retaining the original parser diagnostics.

Related issues

Fixes #66877

Additional information

  • Existing JSON fallback and error-handling tests passed.
  • The same 12 failures (Windows path separator mismatches) and 2 HTTP-related test errors were also reproduced on the unmodified master branch. No additional failures were observed with this PR.

@Yin-1022
Yin-1022 requested a review from a team as a code owner October 9, 2026 05:31

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

Comment on lines +200 to +227
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

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

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 e

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.

I've consolidated them into a single try-except block while keeping the original parser error message and exception chaining. Thanks!

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

Stale Bugbot comment from a previous run.

@dancingactor

Copy link
Copy Markdown
Contributor

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
pre-commit run --from-ref master --to-ref HEAD

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Oct 9, 2026
@Jo-Leo-35

Jo-Leo-35 commented Oct 9, 2026 •

Copy link
Copy Markdown

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:

has_file_context=True
has_file_path=True
has_parser_detail=False

After including Original error: {e} in the outer message, all three checks became True.
Just sharing the reproduction result in case it is helpful. Please let me know if I misunderstood anything 🙂

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

left comments!

@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 and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 47abe07. Configure here.

@owenowenisme owenowenisme self-assigned this Oct 9, 2026
@400Ping 400Ping self-assigned this Oct 9, 2026
# 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',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Suggested change
b'{"name": "valid"}\n{"name": "\xff"}\n',
b'{"name": "valid"}\n' + b'{"name": "' + b"x" * 100 + b'"}\n' * 100 + b'{"name": "\xff"}\n',

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.

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!

@owenowenisme owenowenisme left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@owenowenisme
owenowenisme enabled auto-merge (squash) October 12, 2026 06:55
@github-actions github-actions Bot added the go add ONLY when ready to merge, run all tests label Oct 12, 2026
@owenowenisme
owenowenisme merged commit a1a2cc6 into ray-project:master Oct 12, 2026
8 checks passed
chia7712 pushed a commit to opensource4you/readme that referenced this pull request Oct 21, 2026
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))
chia7712 pushed a commit to opensource4you/readme that referenced this pull request Oct 23, 2026
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
chia7712 pushed a commit to opensource4you/readme that referenced this pull request Nov 25, 2026
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)))
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.

[Data] Include input file paths in JSON/JSONL parsing errors

7 participants