Skip to content

[Data] Stop the block prefetcher when iteration ends early - #67355

Merged
iamjustinhsu merged 1 commit into
ray-project:masterfrom
prasad-anyscale:prasad/data-stop-prefetcher-on-early-exit
Nov 4, 2026
Merged

iamjustinhsu merged 1 commit into
ray-project:masterfrom
prasad-anyscale:prasad/data-stop-prefetcher-on-early-exit

Conversation

@prasad-anyscale

Copy link
Copy Markdown
Contributor

Why are these changes needed?

When a consumer stops iter_batches / iter_torch_batches before the stream ends (for example PyTorch Lightning's limit_train_batches with streaming_split), the WaitBlockPrefetcher is never stopped:

  • prefetch_batches_locally calls prefetcher.stop() only after its loop, so GeneratorExit skips it. The prefetch_batches=0 path returns before reaching it.
  • The thread targets self._run, which keeps the prefetcher alive, so __del__ never runs. The parked thread still holds blocks_to_fetch.

So every abandoned epoch leaks a thread pinning its last prefetch window. Under memory pressure, those blocks are spilled into fused files that can't be deleted while any member is referenced, and long training jobs eventually fill the spill disk. With prefetch_batches=0, every iterator also leaks an idle thread.

What this PR does

  • BatchIterator._iter_batches closes the pipeline and stops the prefetcher in a finally, on the consumer's thread.
  • prefetch_batches_locally also stops it in a finally, covering the prefetch_batches <= 0 path.
  • prefetch_batches <= 0 uses a DisabledBlockPrefetcher that starts no thread.
  • WaitBlockPrefetcher._run drops fetched refs before parking.

Testing

9 new tests in block_batching/test_iter_batches.py and test_util.py: early close, upstream error, consumer stopping early, no thread without prefetching, idle prefetcher releasing refs, and streaming_split consumers stopping early. All failed before the fix and pass after it.

Run against the Ray nightly wheel with this branch's ray/data:

pytest python/ray/data/tests/block_batching/                  # 145 passed
pytest python/ray/data/tests/test_iterator.py                 # 30 passed
pytest python/ray/data/tests/test_split.py                    # 426 passed
pytest python/ray/data/tests/test_push_split_coordinator.py   # 13 passed
pytest python/ray/data/tests/test_data_iterator_checkpointer.py  # 24 passed
pytest python/ray/data/tests/test_torch_iter_batches.py       # 3 passed

A standalone repro (24 epochs, each breaking after 4 batches) goes from 18 leaked threads / 36 pinned refs to 0 / 0.

Duplicate check

No open PR or issue covers this. I searched open PRs and issues for prefetcher, WaitBlockPrefetcher, prefetch_batches_locally and "iter_batches leak".

AI assistance (Claude Code) was used. I reviewed every changed line and ran the tests above.

Consumers that stop iter_batches before the stream ends (for example
Lightning's limit_train_batches) never stopped the WaitBlockPrefetcher.
Its parked thread kept the last prefetched block refs alive, pinning
spilled objects until the disk filled.

- Stop the prefetcher in a finally, on the consumer's thread.
- Stop it in prefetch_batches_locally's finally as well.
- Start no prefetcher thread when prefetch_batches <= 0.
- Drop fetched refs before the prefetcher thread parks.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Prasad Palkar <[email protected]>

@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 resource management and prevents memory leaks in Ray's block batching prefetcher by ensuring prefetchers are stopped and block references are cleared when iteration ends early or fails. It also introduces a DisabledBlockPrefetcher to avoid starting threads when prefetching is disabled. The review feedback highlights two critical issues: first, after_epoch_end() should be moved to the finally block in _iter_batches to prevent resource accounting leaks when iteration is interrupted; second, a reference cycle leak in WaitBlockPrefetcher prevents garbage collection of the prefetcher, which can be resolved by using a weak reference for the background thread target.

Comment on lines +291 to 302
finally:
# A consumer that stops early (``break``, ``close()``, or dropping
# the iterator) leaves the pipeline suspended in its background
# thread, where the prefetcher would otherwise only be stopped if
# that thread's generators are garbage collected. A prefetcher
# that isn't stopped keeps its thread, and the blocks it last
# prefetched, alive for the life of the process. Stop it here, on
# the consumer's thread, after signaling the pipeline to stop.
batch_iter.close()
self._prefetcher.stop()

self.after_epoch_end()

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.

high

If the consumer stops early or an exception is raised, after_epoch_end() is never called. This means self._prefetch_bytes_callback(0) is never invoked, which can lead to a resource accounting leak in the executor's resource manager (as the manager will still believe the last reported prefetched bytes are active). Moving self.after_epoch_end() into the finally block ensures that the resource manager is always notified of 0 prefetched bytes when the iterator is terminated or closed.

Suggested change
finally:
# A consumer that stops early (``break``, ``close()``, or dropping
# the iterator) leaves the pipeline suspended in its background
# thread, where the prefetcher would otherwise only be stopped if
# that thread's generators are garbage collected. A prefetcher
# that isn't stopped keeps its thread, and the blocks it last
# prefetched, alive for the life of the process. Stop it here, on
# the consumer's thread, after signaling the pipeline to stop.
batch_iter.close()
self._prefetcher.stop()
self.after_epoch_end()
finally:
# A consumer that stops early (``break``, ``close()``, or dropping
# the iterator) leaves the pipeline suspended in its background
# thread, where the prefetcher would otherwise only be stopped if
# that thread's generators are garbage collected. A prefetcher
# that isn't stopped keeps its thread, and the blocks it last
# prefetched, alive for the life of the process. Stop it here, on
# the consumer's thread, after signaling the pipeline to stop.
batch_iter.close()
self._prefetcher.stop()
self.after_epoch_end()

Comment on lines +523 to +526
finally:
# Drop the references before parking, so an idle prefetcher
# doesn't keep the blocks it last fetched alive.
blocks_to_fetch = []

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

There is a classic catch-22 reference cycle leak in WaitBlockPrefetcher. The thread is started with target=self._run, which is a bound method holding a strong reference to self. Because the thread is kept alive in threading._active while running, it acts as a GC root, preventing WaitBlockPrefetcher from ever being garbage collected. Consequently, del is never called, and the thread is never stopped, leading to a permanent leak if the iterator is discarded without being iterated or if an exception is raised before iteration starts.

To fix this, we can use a weak reference to self for the thread target, and implement the run loop as a static method that dereferences the weakref. For example:

class WaitBlockPrefetcher(BlockPrefetcher):
    def __init__(self):
        self._blocks = []
        self._stopped = False
        self._condition = threading.Condition()
        self._thread = threading.Thread(
            target=self._run_prefetcher,
            args=(weakref.ref(self),),
            name="Prefetcher",
            daemon=True,
        )
        self._thread.start()

    @staticmethod
    def _run_prefetcher(weak_self):
        self = weak_self()
        if self is None:
            return
        condition = self._condition
        while True:
            try:
                with condition:
                    self = weak_self()
                    if self is None or self._stopped:
                        break
                    if len(self._blocks) == 0:
                        self = None
                        condition.wait()
                        self = weak_self()
                        if self is None or self._stopped:
                            break
                    blocks_to_fetch, self._blocks = self._blocks[:], []
                if len(blocks_to_fetch) > 0:
                    ray.wait(blocks_to_fetch, num_returns=1, timeout=0, fetch_local=True)
            except Exception:
                logger.exception("Error in prefetcher thread.")
            finally:
                blocks_to_fetch = []
                self = None

@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Oct 24, 2026

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

Verified against base 3c56135 and head 1faf3e1 (Python 3.13, CPU only).

  • With public APIs (ds.iter_batches(batch_size=100, prefetch_batches=k), breaking after 4 batches, 24 epochs), base leaves 24 live Prefetcher threads for both prefetch_batches=2 and 0; head leaves none. Base also leaks one idle thread per full iteration with prefetch_batches=0; head doesn't.
  • An exception in the loop, iter_torch_batches, streaming_split with one consumer stopping early, and next(it); del it also leak on base and not on head. Re-iterating after a break works.
  • The 9 new tests fail on base and pass on head; block_batching/ is 145 passed. I didn't run test_split.py.

On gemini's points: after_epoch_end() is already skipped on early exit on master, and moving it into the finally would also call CheckpointingBatchIterator's end_epoch() for a partial epoch, which advances the epoch index. The cycle no longer matters once stop() runs in the finally; the prefetcher is collected after a break.

LGTM.

dstrodtman added a commit that referenced this pull request Oct 30, 2026
…strings on iteration APIs (#67486)

## Summary

Corrects the `prefetch_batches` and `local_shuffle_buffer_size` argument
docstrings that are copied across the `Dataset` and `DataIterator`
iteration APIs, so they describe what `BatchIterator` and
`ShufflingBatcher` actually do. This is a docstring-only change.
Behavior is unchanged.

This came up while reviewing #67454, which documents the iteration
pipeline on the Ray Data internals page. The API reference pages that
section links to contradicted its diagram.

## Before

### `prefetch_batches`

The shared text said:

> The number of batches to fetch ahead of the current batch to fetch. If
set to greater than 0, a separate threadpool will be used to fetch the
objects to the local node, format the batches, and apply the collate_fn.
Defaults to 1.

That doesn't match
`python/ray/data/_internal/block_batching/iter_batches.py`:

- Iteration always runs in a background thread. `_iter_batches` wraps
the pipeline in `iter_threaded(...)` whatever the value of
`prefetch_batches`.
- The format and collate pool has
`min(RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS, prefetch_batches)`
workers, and that environment variable defaults to 4. Setting
`prefetch_batches` above 4 fetches further ahead but adds no threads,
and the docstring didn't say so.
- With `prefetch_batches=0`, there's no pool. `prefetch_batches_locally`
yields block refs without prefetching, and format and collate run
inline.
- `iter_batches`, `iter_tf_batches`, `to_tf`, and `to_torch` don't
accept a `collate_fn`, but their docstrings mentioned applying one.
- The first sentence repeated "to fetch". `iter_jax_batches` had a
different one-line version.

### `local_shuffle_buffer_size`

The docstrings disagreed with each other and with `ShufflingBatcher` in
`python/ray/data/_internal/batcher.py`:

- The `iter_torch_batches`, `iter_tf_batches`, `to_torch`, and `to_tf`
docstrings said the buffer size "must be greater than or equal to
`batch_size`." The code doesn't reject a smaller value. It rounds it up
to `batch_size`.
- `ShufflingBatcher` raises `ValueError` when `batch_size` is `None`.
Only some docstrings said `batch_size` is required, and `iter_batches`,
which accepts `batch_size=None`, didn't.
- `DataIterator.iter_jax_batches` had a one-line version, "Minimum rows
for local in-memory shuffle."
- None of them stated the trade-off that `ShufflingBatcher`'s own
docstring gives: a larger buffer is more random but adds latency to the
first batch.

## After

### `prefetch_batches`

Every `prefetch_batches` docstring now uses the same text. Methods that
accept `collate_fn` (`iter_torch_batches`, `iter_jax_batches`) mention
collation, and the others don't:

> The number of batches to fetch ahead of the current batch. Ray Data
prepares batches in background threads while your code consumes the
current one. If greater than 0, a thread pool formats the batches. The
pool has `prefetch_batches` threads, up to a limit of 4. To change the
limit, set the `RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS` environment
variable. If 0, Ray Data doesn't prefetch blocks and formats each batch
without the thread pool. Defaults to 1.

### `local_shuffle_buffer_size`

Every docstring now uses the same text:

> If not `None`, Ray Data randomly shuffles the data using a local
in-memory shuffle buffer, and this value serves as the minimum number of
rows that must be in the buffer to yield a batch. When there are no more
rows to add to the buffer, Ray Data drains the remaining rows. A larger
buffer makes the shuffle more random but might increase the latency to
the first batch. If this value is smaller than `batch_size`, Ray Data
rounds it up to `batch_size`. Local shuffling raises a `ValueError` if
`batch_size` is `None`.

I kept the "minimum number of rows" sentence's meaning as it was. It's
an approximation of the compaction watermarks in
`ShufflingBatcher.has_batch()`, and I've asked in a comment below
whether you want it more precise.

Updated methods, for both arguments:

- `DataIterator`: `iter_batches`, `iter_torch_batches`,
`iter_tf_batches`, `iter_jax_batches`, `to_torch`, and `to_tf`.
- `Dataset`: `iter_batches`, `iter_torch_batches`, `iter_tf_batches`,
`iter_jax_batches`, and `to_tf`.

## Subsystems

API (docstrings only)

## Not a duplicate

I searched open PRs for `prefetch_batches` and iterator docstring
changes. #67355 touches `iter_batches.py` and `util.py` to stop the
block prefetcher early, but it doesn't change these docstrings, the
thread-pool sizing, or `ShufflingBatcher`.

## Testing

- `pre-commit run --files python/ray/data/iterator.py
python/ray/data/dataset.py` passes, including ruff, black, pydoclint,
and the Ray docstyle check.
- I checked each claim against `iter_batches.py` (`_format_batches`,
`_iter_batches`, `prefetch_batches_locally`), `util.py`
(`iter_threaded`), and `batcher.py` (`ShufflingBatcher.__init__` and
`has_batch`) on master.
- I didn't run a local Sphinx build. The change is plain prose plus
inline literals.

The `docstring-only` label is applied to skip the heavy Ray Data test
suites.

I wrote this with AI assistance (Claude Code). I reviewed every changed
line and can defend the change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

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

LGTM, thanks for the fix. Left one comment

Comment on lines +201 to +202
assert batch_iterator._prefetcher._stopped
assert _new_prefetcher_threads_still_alive(baseline) == []

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.

Nit: ideally I don't think we should be asserting private variables. It makes sense here though but we can consider exposing this if required

@ayushk7102 ayushk7102 added the go add ONLY when ready to merge, run all tests label Nov 4, 2026
@iamjustinhsu
iamjustinhsu merged commit af6d064 into ray-project:master Nov 4, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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