Skip to content

[Data] Wait for iter_threaded workers to exit when the consumer stops - #67868

Closed
pseudo-rnd-thoughts wants to merge 1 commit into
ray-project:masterfrom
pseudo-rnd-thoughts:data/iter-threaded-join-workers-on-close
Closed

pseudo-rnd-thoughts wants to merge 1 commit into
ray-project:masterfrom
pseudo-rnd-thoughts:data/iter-threaded-join-workers-on-close

Conversation

@pseudo-rnd-thoughts

Copy link
Copy Markdown
Member

Summary

iter_threaded now waits, bounded at 1s, for its workers to exit when the consumer stops. Before, it only signaled them to stop, so they released fn's state, including the iter_batches pipeline's prefetched object refs, up to a poll interval later. Since #67355, a caller that abandons an iterator and immediately calls ray.shutdown() has those refs dropped while the core worker is torn down, which exits the process. This made //python/ray/rllib:test_offline_policy_evaluation_runner die with no test result in postmerge (build 20796).

Before

  1. RLlib's offline evaluation stops iter_batches partway through an epoch and drops the iterator when the test method returns. tearDown then calls ray.shutdown().
  2. Since [Data] Stop the block prefetcher when iteration ends early #67355, the _iter_batches finally closes the iter_threaded generator and stops the WaitBlockPrefetcher. The prefetcher's thread now exits and drops its refs, so the iter_threaded worker's pipeline (prefetch_batches_locally's window) holds the last references to the prefetched blocks. Before [Data] Stop the block prefetcher when iteration ends early #67355, the leaked prefetcher thread kept them alive forever, which hid this.
  3. close() only set stopped. The worker noticed within its 0.1s poll, which by then was inside ray.shutdown(), between core_worker.shutdown_driver() and del global_worker.core_worker. ObjectRef.__dealloc__ called GetCoreWorker(), which calls QuickExit() (_Exit(1)), so pytest never wrote a result:
    core_worker_process.cc:1115: The core worker has already been shutdown. ... The process will exit
    

After

When close() (or garbage collection of the iterator) returns, the workers have exited and dropped what fn held, so a following ray.shutdown() has nothing left to release. Idle workers exit within their 0.1s poll. A worker blocked inside fn can't be interrupted, so the wait is bounded by _WORKER_JOIN_TIMEOUT_S (1s), after which close() returns and logs at debug level. Early break latency only increases in that blocked case.

flowchart TD
    subgraph Before
        subgraph BS[Subsystem: block / data format]
            subgraph BC[Component: iter_threaded generator cleanup]
                B1[consumer closes iterator] --> B2[stopped.set] --> B3[return]
                B2 -.up to 0.1s later, possibly during ray.shutdown.-> B4[worker drops fn state / ObjectRefs]
            end
        end
    end
    subgraph After
        subgraph AS[Subsystem: block / data format]
            subgraph AC[Component: iter_threaded generator cleanup]
                A1[consumer closes iterator] --> A2[stopped.set] --> A5[join workers, bounded 1s] --> A3[return]
                A5 --- A4[worker drops fn state / ObjectRefs]
            end
        end
    end
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class A5 added
    class A4 changed
Loading

Data flow is unchanged; only the cleanup timing of iter_threaded's worker threads changes.

Subsystems

Block / data format (block_batching/)

Testing

New tests in block_batching/test_util.py::TestIterThreaded, all of which fail without the fix:

  • test_close_waits_for_workers_to_release_fn_state[1|4]: when close() returns, with no waiting, every worker has exited and its fn state is freed (checked with weakrefs).
  • test_close_is_bounded_when_fn_blocks: close() returns after the timeout when a worker is blocked inside fn.

A Ray Data-only end-to-end repro (abandon iter_batches, then ray.shutdown()) didn't trigger the race locally (0 of 6 runs), so the tests check the guarantee directly and the RLlib test is the end-to-end check.

Run locally (macOS, Python 3.12):

pytest python/ray/rllib/offline/tests/test_offline_policy_evaluation_runner.py
    # with fix: 6 passed (3/3 runs); without fix: process exits during first test (3/3 runs)
pytest python/ray/data/tests/block_batching/ python/ray/data/tests/test_iterator.py python/ray/data/tests/test_torch_iter_batches.py
    # 177 passed, 4 failed: tf tests, tensorflow not installed locally
pytest python/ray/data/tests/test_split.py python/ray/data/tests/test_push_split_coordinator.py
    # 438 passed, 3 failed: train_test_split tests, polars not installed locally (same 3 fail on master)

Related

Duplicate check

No open PR or issue covers this. I searched open PRs for iter_threaded, 67355 and test_offline_policy_evaluation_runner.

AI assistance (Claude Code) was used to investigate and write this change. I reviewed every changed line and ran the tests above.

🤖 Generated with Claude Code

When a consumer stops an `iter_threaded` generator early, the workers were
only signaled to stop and released `fn`'s state (for example the prefetched
object refs of the `iter_batches` pipeline) up to a poll interval later. Since
ray-project#67355 stops the block prefetcher on early exit, those workers now hold the
last references to the prefetched blocks. A caller that abandons an iterator
and immediately calls `ray.shutdown()` has the workers drop those refs while
the core worker is torn down, and `GetCoreWorker()` then exits the process.
This made `//python/ray/rllib:test_offline_policy_evaluation_runner` die
without a test result.

Wait, bounded by `_WORKER_JOIN_TIMEOUT_S` (1s), for the workers to exit
before the generator's cleanup returns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
@pseudo-rnd-thoughts
pseudo-rnd-thoughts requested a review from a team as a code owner November 5, 2026 14:39

@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 updates iter_threaded in python/ray/data/_internal/block_batching/util.py to wait for worker threads to exit (up to a bounded timeout of 1.0 second) when the consumer stops early. This ensures that resources and state held by the workers are released before the consumer continues, preventing issues such as process exits during ray.shutdown(). Corresponding unit tests have been added to verify this behavior. I have no feedback to provide as there are no review comments.

@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Nov 5, 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.

Tested c3bf602 against base 49720bc (which already includes #67355), Python 3.13, Ray nightly with only ray/data swapped, CPU.

Through ds.iter_batches(prefetch_batches=2) with an early break, base still had up to 3 iter_threaded/prefetcher threads alive right after the loop (they exited within 0.5 s); with the PR there were none, and break took the same time. An exception in the loop, del, .close(), a slow consumer and a _collate_fn gave the same result. With a collate that blocks for 2 s, break took about 1 s longer, matching the bound, and nothing hung. 24 epochs left no extra threads on either side.

Tests: the 3 new cases fail on base and pass with the PR; the rest of test_util.py passes.

Nit: the 6-line comment in the finally block could be cut to a line or two, since the docstring already explains it. LGTM.

@pseudo-rnd-thoughts

Copy link
Copy Markdown
Member Author

Closing as we're going to investigate the solution upstream in core

pseudo-rnd-thoughts added a commit that referenced this pull request Nov 23, 2026
## Why are these changes needed?

`:brain: rllib: docs example tests` (`//python/ray/rllib:doctest`)
crashes with exit code 1 and no traceback. #68306 skipped `PPOConfig`
for this, and the crash moved to `SACConfig`, the next module. Neither
example is at fault: the crash happens in whichever module runs after
`MARWILConfig`.

The first `MARWILConfig` example builds an `Algorithm` in the driver
with `num_learners=0` and `dataset_num_iters_per_learner=1`, so
`OfflineData.sample()` keeps a partly consumed `iter_batches()`
generator, and its Ray Data prefetch threads stay alive. The example
never calls `algo.stop()`, and `Algorithm.cleanup()` doesn't close that
generator anyway. When the plugin's module fixture calls
`ray.shutdown()` before the next module, one of those threads releases
an `ObjectRef` after the core worker is gone, and the process exits
through `QuickExit()`. The driver's core-worker log shows it, from a
non-main thread about 120 ms after shutdown:

```
core_worker_process.cc:1083: Driver shutdown complete. Removing the global worker.
core_worker_process.cc:1115: The core worker has already been shutdown. This happens when the language frontend accesses the Ray's worker after it is shutdown. The process will exit
```

This matches the diagnosis @vishalkotak posted on #68305.

This PR:
- Skips `MARWILConfig` (the source) with `# doctest: +SKIP_EXAMPLE` and
a `NOT TESTED IN CI` comment linking #68305.
- Reverts #68306's change to `ppo.py`, so `PPOConfig` runs again.

Follow-ups, not in this PR:
- RLlib: close the offline data iterator in `Algorithm.cleanup()` and
call `algo.stop()` in the MARWIL example, then remove this skip. I have
a local patch; with it, MARWIL → PPO → SAC passed 3/3 locally, and
without it the run crashed 2/2.
- Core: releasing an `ObjectRef` during `ray.shutdown()` shouldn't
`_Exit(1)` the process. #67868 (a Data-side workaround) was closed in
favor of a core fix.

## Related issue number

Related to #68305. Supersedes the skip from #68306.

## Duplicate check

No open PR references #68305 or touches `MARWILConfig`'s doctest. I
searched open PRs for `68305 in:body`, `rllib doctest`, and `MARWIL
doctest`.

## Testing

Locally on macOS, Python 3.12, editable build, using the target's
arguments and plugin (from `python/`):

```bash
RAY_LOG_TO_DRIVER=0 TF_USE_LEGACY_KERAS=1 PYTHONPATH=../bazel \
python -m pytest --doctest-modules --disable-warnings -v -c NO_PYTEST_CONFIG \
  -p default_doctest_pytest_plugin \
  ray/rllib/algorithms/marwil/marwil.py ray/rllib/algorithms/ppo/ppo.py ray/rllib/algorithms/sac/sac.py
```

- Before (MARWIL and PPO enabled): MARWIL passes, then the process exits
with code 1 at the start of the next module, 3/3 runs (MARWIL → SAC) and
2/2 (MARWIL → PPO → SAC). SAC alone passes.
- After: `2 passed, 1 skipped` (MARWIL skipped, PPO and SAC passed), 4/4
runs.
- The whole target's file set (the BUILD glob,
`--continue-on-collection-errors`): `84 passed, 29 skipped, 5 failed, 2
errors`, and the run completed. The 5 failures are `RolloutWorker.*`
examples that need TensorFlow, and the 2 errors are `open_spiel.py`
needing `pyspiel`. Neither package is in my local env, but both are on
CI.

My local run collected 118 examples against CI's 262, so it doesn't
stand in for CI. Premerge skips this target while it's flaky, so a
scheduled postmerge run will confirm it.

`pre-commit run` on the changed files passes.

## AI assistance

AI assistance (Claude Code) helped with the diagnosis, local runs, and
drafting. I reviewed the change and the results.

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

Signed-off-by: Mark Towers <[email protected]>
Co-authored-by: Mark Towers <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants