Repository navigation
[Data] Wait for iter_threaded workers to exit when the consumer stops - #67868
pseudo-rnd-thoughts wants to merge 1 commit into
Conversation
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]>
There was a problem hiding this comment.
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.
Jadiouo
left a comment
There was a problem hiding this comment.
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.
|
Closing as we're going to investigate the solution upstream in core |
## 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]>
Summary
iter_threadednow waits, bounded at 1s, for its workers to exit when the consumer stops. Before, it only signaled them to stop, so they releasedfn's state, including theiter_batchespipeline's prefetched object refs, up to a poll interval later. Since #67355, a caller that abandons an iterator and immediately callsray.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_runnerdie with no test result in postmerge (build 20796).Before
iter_batchespartway through an epoch and drops the iterator when the test method returns.tearDownthen callsray.shutdown()._iter_batchesfinallycloses theiter_threadedgenerator and stops theWaitBlockPrefetcher. The prefetcher's thread now exits and drops its refs, so theiter_threadedworker'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.close()only setstopped. The worker noticed within its 0.1s poll, which by then was insideray.shutdown(), betweencore_worker.shutdown_driver()anddel global_worker.core_worker.ObjectRef.__dealloc__calledGetCoreWorker(), which callsQuickExit()(_Exit(1)), so pytest never wrote a result:After
When
close()(or garbage collection of the iterator) returns, the workers have exited and dropped whatfnheld, so a followingray.shutdown()has nothing left to release. Idle workers exit within their 0.1s poll. A worker blocked insidefncan't be interrupted, so the wait is bounded by_WORKER_JOIN_TIMEOUT_S(1s), after whichclose()returns and logs at debug level. Earlybreaklatency 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 changedData 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]: whenclose()returns, with no waiting, every worker has exited and itsfnstate is freed (checked with weakrefs).test_close_is_bounded_when_fn_blocks:close()returns after the timeout when a worker is blocked insidefn.A Ray Data-only end-to-end repro (abandon
iter_batches, thenray.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):
Related
ObjectRefduringray.shutdown()exits the process viaQuickExit(core_worker_process.cc). That's out of scope here and will be raised with Ray Core separately.Duplicate check
No open PR or issue covers this. I searched open PRs for
iter_threaded,67355andtest_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