Repository navigation
[Data] Fix JSONL read retry with advanced file cursor - #63233
Merged
goutamvenkat-anyscale merged 2 commits intoMay 8, 2026
Merged
goutamvenkat-anyscale merged 2 commits into
goutamvenkat-anyscale merged 2 commits into
Conversation
Signed-off-by: Goutam <[email protected]> Co-authored-by: Cursor <[email protected]>
Contributor
There was a problem hiding this comment.
Code Review
This pull request modifies JSONDatasource to support retrying stream reads on the same file handle by ensuring the file pointer is reset to the beginning before and after chunk size estimation. A new test case was added to verify this behavior. Feedback was provided to use StrictBufferedReader as a context manager to ensure the file handle is correctly detached during exceptions, which prevents potential I/O errors during retries.
Signed-off-by: Goutam <[email protected]>
iamjustinhsu
approved these changes
May 8, 2026
Lucas61000
pushed a commit
to Lucas61000/ray
that referenced
this pull request
May 15, 2026
) ## Summary - Fix `PandasJSONDatasource` so seekable JSONL files are rewound before chunk-size estimation and again after sampling, including when sampling raises. - This prevents retries in `FileBasedDatasource` from recreating `_read_stream()` on a file handle whose cursor was already advanced. - Add a regression test that simulates retrying a JSONL stream read with a partially consumed file handle. ## Problem The `image_embedding_from_jsonl` release test can hit transient S3/read errors while reading JSONL input. `FileBasedDatasource` retries the stream read with the same open file handle, but `PandasJSONDatasource._estimate_chunksize()` previously asserted that seekable files always started at offset 0. If the first attempt advanced the cursor before failing, the retry raised `AssertionError: File pointer must be at the beginning`, masking the original transient read error and failing the release test. ## Fix For seekable files, `_estimate_chunksize()` now seeks to the beginning before sampling and uses a `finally` block to rewind the file before the actual read or any later retry. Non-seekable compressed streams keep using the existing default chunk size path. ## Test plan - `.venv/bin/python -m pytest python/ray/data/tests/datasource/test_json.py::TestPandasJSONDatasource::test_read_stream_with_advanced_file_pointer -q` Made with [Cursor](https://cursor.com) --------- Signed-off-by: Goutam <[email protected]> Co-authored-by: Cursor <[email protected]>
alexandrplashchinsky
pushed a commit
to alexandrplashchinsky/ray-alex
that referenced
this pull request
May 29, 2026
) ## Summary - Fix `PandasJSONDatasource` so seekable JSONL files are rewound before chunk-size estimation and again after sampling, including when sampling raises. - This prevents retries in `FileBasedDatasource` from recreating `_read_stream()` on a file handle whose cursor was already advanced. - Add a regression test that simulates retrying a JSONL stream read with a partially consumed file handle. ## Problem The `image_embedding_from_jsonl` release test can hit transient S3/read errors while reading JSONL input. `FileBasedDatasource` retries the stream read with the same open file handle, but `PandasJSONDatasource._estimate_chunksize()` previously asserted that seekable files always started at offset 0. If the first attempt advanced the cursor before failing, the retry raised `AssertionError: File pointer must be at the beginning`, masking the original transient read error and failing the release test. ## Fix For seekable files, `_estimate_chunksize()` now seeks to the beginning before sampling and uses a `finally` block to rewind the file before the actual read or any later retry. Non-seekable compressed streams keep using the existing default chunk size path. ## Test plan - `.venv/bin/python -m pytest python/ray/data/tests/datasource/test_json.py::TestPandasJSONDatasource::test_read_stream_with_advanced_file_pointer -q` Made with [Cursor](https://cursor.com) --------- Signed-off-by: Goutam <[email protected]> Co-authored-by: Cursor <[email protected]> Signed-off-by: Alexandr Plashchinsky <[email protected]>
sampan-s-nayak
pushed a commit
that referenced
this pull request
Sep 9, 2026
## Description
A retryable read error partway through a file silently drops data. No
exception, exit code 0.
### Repro
A datasource that yields one block per 1 KiB of an 8 KiB file, with one
transient error injected after the third read:
```python
class FlakyStream:
fired = False
def __init__(self, f):
self._f, self._reads = f, 0
def read(self, n=-1):
self._reads += 1
if not FlakyStream.fired and self._reads > 3:
FlakyStream.fired = True
raise OSError(DEFAULT_RETRIED_IO_ERRORS[0]) # transient network error
return self._f.read(n)
class ChunkedDatasource(FileBasedDatasource):
def _open_input_source(self, filesystem, path, **kw):
return FlakyStream(super()._open_input_source(filesystem, path, **kw))
def _read_stream(self, f, path):
while (data := f.read(1024)):
builder = DelegatingBlockBuilder()
builder.add({"data": data})
yield builder.build()
```
### Expected vs current
| | expected | current | this PR |
| ---------------- | -------- | ---------- | ------- |
| blocks delivered | 8 | **5** | 8 |
| bytes delivered | 8192 | **5120** | 8192 |
| data correct | yes | **no** | yes |
| error raised | no | no | no |
Current behavior loses 3072 bytes, 37.5% of the file, and the read
reports success.
### Cause
`read_files` opens the file once, then passes a closure over that handle
to `iterate_with_retry`:
```python
with RetryingContextManager(self._open_input_source(fs, read_path, ...)) as f:
for block in iterate_with_retry(lambda: self._read_stream(f, read_path), ...):
```
`iterate_with_retry` recreates the iterable on a retryable error and
skips the items the failed attempt already yielded, so the factory must
replay the same sequence from the start. This one does not: it reuses
the advanced handle, so attempt 2 resumes from wherever attempt 1
stopped, and the skip then discards real data instead of duplicates.
In the repro: attempt 1 yields 3 blocks and fails, attempt 2 resumes at
byte 3072 and yields the remaining 5, and the first 3 of those are
dropped as "already yielded". 3 + 2 = 5.
### Which formats are affected
Silent loss, cut at a record boundary with one injected error at ~50%:
| API | current behavior |
| ----------------------------------- |
--------------------------------------------- |
| `read_text` | silent, 1944 / 4000 rows |
| `read_binary_files` | silent, payload 32768 / 65536 bytes |
| `read_csv` with `column_names` | silent, 1501 / 4000 rows |
| `read_json` (Arrow) | silent, 1961 / 4000 rows |
| `read_csv` with inferred header | raises `ValueError: ...check the CSV
file has correct format` |
| `read_numpy` | raises `ValueError: contains pickled (object) data` |
| `read_json` (pandas JSONL) | unaffected |
All are correct after the fix. Whether CSV fails loudly is luck: Arrow
takes the first surviving line as a header, which usually fails to
parse. Supply `column_names` and the loss goes quiet.
Pandas JSONL escapes because #63233 added `f.seek(0)` to
`_estimate_chunksize` in May 2026, which fixed an `AssertionError` there
and incidentally restored replay-from-start for that one path. The
general problem was not addressed.
Parquet is unaffected: it is not a `FileBasedDatasource`, and its read
factory closes over a stateless fragment.
### Fix
Open the file inside the retry factory, with the `with` scoped inside a
generator so each attempt's handle is closed as soon as that attempt
ends, on both the success and the exception path:
```python
def open_and_read_stream() -> Iterator[Block]:
with RetryingContextManager(
self._open_input_source(fs, read_path, **open_stream_args),
context=self._data_context,
) as f:
yield from self._read_stream(f, read_path)
for block in iterate_with_retry(open_and_read_stream, ...):
```
Measured max 1 handle open at a time across a retry, with all handles
closed on the clean, retried, and abandoned-midway paths.
Alternatives considered:
- **Rewind when the handle is seekable.** `_open_input_source` returns
`open_input_stream`, whose `seekable()` is `False` even on a local
filesystem. This would fix only ORC and uncompressed JSON and leave
everything else failing silently.
- **`ExitStack` around the loop.** Correct, but a failed attempt's
handle stays open for the remainder of that file's read, up to 10 at
once.
Also documents the replay-from-start requirement on
`iterate_with_retry`, and corrects two comments in `json_datasource.py`
that asserted retries reuse the same handle.
### Behavior change worth noting
The open now sits inside `iterate_with_retry`, and the open path already
retries at two levels (`RetryingPyFileSystem.open_input_file` and
`RetryingContextManager.__enter__`, 10 attempts each). These multiply,
so a persistently retryable open can now take roughly 10x as many
attempts before giving up, with exponential backoff capped at 32s per
attempt. Bounded, and only in a case that was already failing.
Retries are also more expensive by design: attempt 2 re-parses the
blocks it will discard. Resuming was cheaper, and wrong.
## Related issues
None open. Searched open PRs and issues for `iterate_with_retry`,
`file_based_datasource retry`, `_read_stream retry`, and
`RetryingContextManager`. #63233 is merged and narrower, covering only
the pandas JSONL chunksize path.
## Additional information
**Known follow-up, deliberately not in this PR.**
`webdataset_datasource.py:439` wraps `_tar_file_iterator` in its own
`iterate_with_retry` whose factory closes over the stream it was handed.
That inner retry catches the error before the outer one can reopen, so a
transient error there becomes `tarfile.ReadError: invalid header`,
identically before and after this change. No regression, but it needs a
separate fix. Removing a retry layer seemed like a maintainer's call.
**Tests.**
```
pytest python/ray/data/tests/datasource/test_file_based_datasource.py
-> 32 passed, 3 skipped
```
New regression test `test_flaky_read_stream_retry_does_not_drop_data`:
delivers 5 of 8 blocks on master, 8 of 8 with this change.
Wider run across the Data file-format suites (`test_text`, `test_csv`,
`test_json`, `test_binary`, `test_image`, `test_avro`,
`test_webdataset`, `test_numpy`, `test_parquet`), per file: 226 passed,
21 skipped, 30 failed. Set-differenced against the same run with this
change reverted: zero new failures, one fixed. All 30 failures are
missing optional imports in this environment (tensorflow x22, torch x4,
decord x4) and fail identically on master.
`pre-commit run` is clean on the changed files.
**AI assistance was used** for this change: to build the repro,
implement the fix, and write the tests and this description.
Signed-off-by: Marwan Sarieddine <[email protected]>
NightWing1998
pushed a commit
to NightWing1998/ray
that referenced
this pull request
Sep 11, 2026
…oject#66011) ## Description A retryable read error partway through a file silently drops data. No exception, exit code 0. ### Repro A datasource that yields one block per 1 KiB of an 8 KiB file, with one transient error injected after the third read: ```python class FlakyStream: fired = False def __init__(self, f): self._f, self._reads = f, 0 def read(self, n=-1): self._reads += 1 if not FlakyStream.fired and self._reads > 3: FlakyStream.fired = True raise OSError(DEFAULT_RETRIED_IO_ERRORS[0]) # transient network error return self._f.read(n) class ChunkedDatasource(FileBasedDatasource): def _open_input_source(self, filesystem, path, **kw): return FlakyStream(super()._open_input_source(filesystem, path, **kw)) def _read_stream(self, f, path): while (data := f.read(1024)): builder = DelegatingBlockBuilder() builder.add({"data": data}) yield builder.build() ``` ### Expected vs current | | expected | current | this PR | | ---------------- | -------- | ---------- | ------- | | blocks delivered | 8 | **5** | 8 | | bytes delivered | 8192 | **5120** | 8192 | | data correct | yes | **no** | yes | | error raised | no | no | no | Current behavior loses 3072 bytes, 37.5% of the file, and the read reports success. ### Cause `read_files` opens the file once, then passes a closure over that handle to `iterate_with_retry`: ```python with RetryingContextManager(self._open_input_source(fs, read_path, ...)) as f: for block in iterate_with_retry(lambda: self._read_stream(f, read_path), ...): ``` `iterate_with_retry` recreates the iterable on a retryable error and skips the items the failed attempt already yielded, so the factory must replay the same sequence from the start. This one does not: it reuses the advanced handle, so attempt 2 resumes from wherever attempt 1 stopped, and the skip then discards real data instead of duplicates. In the repro: attempt 1 yields 3 blocks and fails, attempt 2 resumes at byte 3072 and yields the remaining 5, and the first 3 of those are dropped as "already yielded". 3 + 2 = 5. ### Which formats are affected Silent loss, cut at a record boundary with one injected error at ~50%: | API | current behavior | | ----------------------------------- | --------------------------------------------- | | `read_text` | silent, 1944 / 4000 rows | | `read_binary_files` | silent, payload 32768 / 65536 bytes | | `read_csv` with `column_names` | silent, 1501 / 4000 rows | | `read_json` (Arrow) | silent, 1961 / 4000 rows | | `read_csv` with inferred header | raises `ValueError: ...check the CSV file has correct format` | | `read_numpy` | raises `ValueError: contains pickled (object) data` | | `read_json` (pandas JSONL) | unaffected | All are correct after the fix. Whether CSV fails loudly is luck: Arrow takes the first surviving line as a header, which usually fails to parse. Supply `column_names` and the loss goes quiet. Pandas JSONL escapes because ray-project#63233 added `f.seek(0)` to `_estimate_chunksize` in May 2026, which fixed an `AssertionError` there and incidentally restored replay-from-start for that one path. The general problem was not addressed. Parquet is unaffected: it is not a `FileBasedDatasource`, and its read factory closes over a stateless fragment. ### Fix Open the file inside the retry factory, with the `with` scoped inside a generator so each attempt's handle is closed as soon as that attempt ends, on both the success and the exception path: ```python def open_and_read_stream() -> Iterator[Block]: with RetryingContextManager( self._open_input_source(fs, read_path, **open_stream_args), context=self._data_context, ) as f: yield from self._read_stream(f, read_path) for block in iterate_with_retry(open_and_read_stream, ...): ``` Measured max 1 handle open at a time across a retry, with all handles closed on the clean, retried, and abandoned-midway paths. Alternatives considered: - **Rewind when the handle is seekable.** `_open_input_source` returns `open_input_stream`, whose `seekable()` is `False` even on a local filesystem. This would fix only ORC and uncompressed JSON and leave everything else failing silently. - **`ExitStack` around the loop.** Correct, but a failed attempt's handle stays open for the remainder of that file's read, up to 10 at once. Also documents the replay-from-start requirement on `iterate_with_retry`, and corrects two comments in `json_datasource.py` that asserted retries reuse the same handle. ### Behavior change worth noting The open now sits inside `iterate_with_retry`, and the open path already retries at two levels (`RetryingPyFileSystem.open_input_file` and `RetryingContextManager.__enter__`, 10 attempts each). These multiply, so a persistently retryable open can now take roughly 10x as many attempts before giving up, with exponential backoff capped at 32s per attempt. Bounded, and only in a case that was already failing. Retries are also more expensive by design: attempt 2 re-parses the blocks it will discard. Resuming was cheaper, and wrong. ## Related issues None open. Searched open PRs and issues for `iterate_with_retry`, `file_based_datasource retry`, `_read_stream retry`, and `RetryingContextManager`. ray-project#63233 is merged and narrower, covering only the pandas JSONL chunksize path. ## Additional information **Known follow-up, deliberately not in this PR.** `webdataset_datasource.py:439` wraps `_tar_file_iterator` in its own `iterate_with_retry` whose factory closes over the stream it was handed. That inner retry catches the error before the outer one can reopen, so a transient error there becomes `tarfile.ReadError: invalid header`, identically before and after this change. No regression, but it needs a separate fix. Removing a retry layer seemed like a maintainer's call. **Tests.** ``` pytest python/ray/data/tests/datasource/test_file_based_datasource.py -> 32 passed, 3 skipped ``` New regression test `test_flaky_read_stream_retry_does_not_drop_data`: delivers 5 of 8 blocks on master, 8 of 8 with this change. Wider run across the Data file-format suites (`test_text`, `test_csv`, `test_json`, `test_binary`, `test_image`, `test_avro`, `test_webdataset`, `test_numpy`, `test_parquet`), per file: 226 passed, 21 skipped, 30 failed. Set-differenced against the same run with this change reverted: zero new failures, one fixed. All 30 failures are missing optional imports in this environment (tensorflow x22, torch x4, decord x4) and fail identically on master. `pre-commit run` is clean on the changed files. **AI assistance was used** for this change: to build the repro, implement the fix, and write the tests and this description. Signed-off-by: Marwan Sarieddine <[email protected]>
nadongjun
pushed a commit
to nadongjun/ray
that referenced
this pull request
Oct 6, 2026
…oject#66011) ## Description A retryable read error partway through a file silently drops data. No exception, exit code 0. ### Repro A datasource that yields one block per 1 KiB of an 8 KiB file, with one transient error injected after the third read: ```python class FlakyStream: fired = False def __init__(self, f): self._f, self._reads = f, 0 def read(self, n=-1): self._reads += 1 if not FlakyStream.fired and self._reads > 3: FlakyStream.fired = True raise OSError(DEFAULT_RETRIED_IO_ERRORS[0]) # transient network error return self._f.read(n) class ChunkedDatasource(FileBasedDatasource): def _open_input_source(self, filesystem, path, **kw): return FlakyStream(super()._open_input_source(filesystem, path, **kw)) def _read_stream(self, f, path): while (data := f.read(1024)): builder = DelegatingBlockBuilder() builder.add({"data": data}) yield builder.build() ``` ### Expected vs current | | expected | current | this PR | | ---------------- | -------- | ---------- | ------- | | blocks delivered | 8 | **5** | 8 | | bytes delivered | 8192 | **5120** | 8192 | | data correct | yes | **no** | yes | | error raised | no | no | no | Current behavior loses 3072 bytes, 37.5% of the file, and the read reports success. ### Cause `read_files` opens the file once, then passes a closure over that handle to `iterate_with_retry`: ```python with RetryingContextManager(self._open_input_source(fs, read_path, ...)) as f: for block in iterate_with_retry(lambda: self._read_stream(f, read_path), ...): ``` `iterate_with_retry` recreates the iterable on a retryable error and skips the items the failed attempt already yielded, so the factory must replay the same sequence from the start. This one does not: it reuses the advanced handle, so attempt 2 resumes from wherever attempt 1 stopped, and the skip then discards real data instead of duplicates. In the repro: attempt 1 yields 3 blocks and fails, attempt 2 resumes at byte 3072 and yields the remaining 5, and the first 3 of those are dropped as "already yielded". 3 + 2 = 5. ### Which formats are affected Silent loss, cut at a record boundary with one injected error at ~50%: | API | current behavior | | ----------------------------------- | --------------------------------------------- | | `read_text` | silent, 1944 / 4000 rows | | `read_binary_files` | silent, payload 32768 / 65536 bytes | | `read_csv` with `column_names` | silent, 1501 / 4000 rows | | `read_json` (Arrow) | silent, 1961 / 4000 rows | | `read_csv` with inferred header | raises `ValueError: ...check the CSV file has correct format` | | `read_numpy` | raises `ValueError: contains pickled (object) data` | | `read_json` (pandas JSONL) | unaffected | All are correct after the fix. Whether CSV fails loudly is luck: Arrow takes the first surviving line as a header, which usually fails to parse. Supply `column_names` and the loss goes quiet. Pandas JSONL escapes because ray-project#63233 added `f.seek(0)` to `_estimate_chunksize` in May 2026, which fixed an `AssertionError` there and incidentally restored replay-from-start for that one path. The general problem was not addressed. Parquet is unaffected: it is not a `FileBasedDatasource`, and its read factory closes over a stateless fragment. ### Fix Open the file inside the retry factory, with the `with` scoped inside a generator so each attempt's handle is closed as soon as that attempt ends, on both the success and the exception path: ```python def open_and_read_stream() -> Iterator[Block]: with RetryingContextManager( self._open_input_source(fs, read_path, **open_stream_args), context=self._data_context, ) as f: yield from self._read_stream(f, read_path) for block in iterate_with_retry(open_and_read_stream, ...): ``` Measured max 1 handle open at a time across a retry, with all handles closed on the clean, retried, and abandoned-midway paths. Alternatives considered: - **Rewind when the handle is seekable.** `_open_input_source` returns `open_input_stream`, whose `seekable()` is `False` even on a local filesystem. This would fix only ORC and uncompressed JSON and leave everything else failing silently. - **`ExitStack` around the loop.** Correct, but a failed attempt's handle stays open for the remainder of that file's read, up to 10 at once. Also documents the replay-from-start requirement on `iterate_with_retry`, and corrects two comments in `json_datasource.py` that asserted retries reuse the same handle. ### Behavior change worth noting The open now sits inside `iterate_with_retry`, and the open path already retries at two levels (`RetryingPyFileSystem.open_input_file` and `RetryingContextManager.__enter__`, 10 attempts each). These multiply, so a persistently retryable open can now take roughly 10x as many attempts before giving up, with exponential backoff capped at 32s per attempt. Bounded, and only in a case that was already failing. Retries are also more expensive by design: attempt 2 re-parses the blocks it will discard. Resuming was cheaper, and wrong. ## Related issues None open. Searched open PRs and issues for `iterate_with_retry`, `file_based_datasource retry`, `_read_stream retry`, and `RetryingContextManager`. ray-project#63233 is merged and narrower, covering only the pandas JSONL chunksize path. ## Additional information **Known follow-up, deliberately not in this PR.** `webdataset_datasource.py:439` wraps `_tar_file_iterator` in its own `iterate_with_retry` whose factory closes over the stream it was handed. That inner retry catches the error before the outer one can reopen, so a transient error there becomes `tarfile.ReadError: invalid header`, identically before and after this change. No regression, but it needs a separate fix. Removing a retry layer seemed like a maintainer's call. **Tests.** ``` pytest python/ray/data/tests/datasource/test_file_based_datasource.py -> 32 passed, 3 skipped ``` New regression test `test_flaky_read_stream_retry_does_not_drop_data`: delivers 5 of 8 blocks on master, 8 of 8 with this change. Wider run across the Data file-format suites (`test_text`, `test_csv`, `test_json`, `test_binary`, `test_image`, `test_avro`, `test_webdataset`, `test_numpy`, `test_parquet`), per file: 226 passed, 21 skipped, 30 failed. Set-differenced against the same run with this change reverted: zero new failures, one fixed. All 30 failures are missing optional imports in this environment (tensorflow x22, torch x4, decord x4) and fail identically on master. `pre-commit run` is clean on the changed files. **AI assistance was used** for this change: to build the repro, implement the fix, and write the tests and this description. Signed-off-by: Marwan Sarieddine <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
PandasJSONDatasourceso seekable JSONL files are rewound before chunk-size estimation and again after sampling, including when sampling raises.FileBasedDatasourcefrom recreating_read_stream()on a file handle whose cursor was already advanced.Problem
The
image_embedding_from_jsonlrelease test can hit transient S3/read errors while reading JSONL input.FileBasedDatasourceretries the stream read with the same open file handle, butPandasJSONDatasource._estimate_chunksize()previously asserted that seekable files always started at offset 0. If the first attempt advanced the cursor before failing, the retry raisedAssertionError: File pointer must be at the beginning, masking the original transient read error and failing the release test.Fix
For seekable files,
_estimate_chunksize()now seeks to the beginning before sampling and uses afinallyblock to rewind the file before the actual read or any later retry. Non-seekable compressed streams keep using the existing default chunk size path.Test plan
.venv/bin/python -m pytest python/ray/data/tests/datasource/test_json.py::TestPandasJSONDatasource::test_read_stream_with_advanced_file_pointer -qMade with Cursor