Repository navigation
[Core] Guard local GC during core worker startup - #66514
Conversation
There was a problem hiding this comment.
Code Review
This pull request improves the robustness of the local garbage collection callback (gc_collect) in _raylet.pyx by wrapping the execution in a try...except BaseException block to prevent uncaught exceptions on C++ threads from causing segfaults, and adds a check for uninitialized core_worker instances. It also introduces a comprehensive test suite to verify recovery from various GC failure modes. The review feedback suggests further wrapping the exception logging call in a nested try...except block to prevent potential segfaults if logging fails during interpreter shutdown.
| except BaseException: | ||
| # This callback runs on a C++ thread without a Python caller to | ||
| # receive exceptions, including SystemExit and KeyboardInterrupt. | ||
| logger.exception("Error during garbage collection") |
There was a problem hiding this comment.
If logger.exception itself raises an exception (for example, during interpreter shutdown when logging handlers or standard streams are being cleaned up), that exception will escape the outer except BaseException block. Since gc_collect is a cdef void function with no exception signature, Cython will attempt to write the unhandled exception to sys.stderr and format a traceback, which triggers Python C API calls like PyTraceBack_Here. This can cause a crash/segfault under the same conditions described in the PR. Wrapping the logging call in a nested try...except BaseException: pass ensures that absolutely no exception can escape the GIL block.
except BaseException:
# This callback runs on a C++ thread without a Python caller to
# receive exceptions, including SystemExit and KeyboardInterrupt.
try:
logger.exception("Error during garbage collection")
except BaseException:
pass
karticam
left a comment
There was a problem hiding this comment.
Added a few comments. Please take a look
| core_worker = getattr(worker, "core_worker", None) | ||
| # LocalGC can arrive before CoreWorker construction has returned | ||
| # and worker.core_worker has been assigned. | ||
| if core_worker is None: |
There was a problem hiding this comment.
can you please add here in the comments why is it safe to skip the GC here?
| logger.debug( | ||
| "gc.collect() freed {} refs in {} seconds".format( | ||
| num_freed, end - start)) | ||
| except BaseException: |
There was a problem hiding this comment.
is this currently hit in practice or just a defensive measure?
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( |
There was a problem hiding this comment.
can you please explain what the different parameterizations do? From what it seems gc_mode = uninitialized is the path exercising the reported bug. what flows do the other parameterizations exercise?
|
Hi @bhushanasati25, since this is a fix for P0, we will be taking over it. The fix you added is correct. I just added a few comments justifying the fix. |
Signed-off-by: Bhushan Asati <[email protected]>
Signed-off-by: kartica.modi <[email protected]>
d245ceb to
77d8f94
Compare
…rent stack before py calls (#67132) (#67996) ## Description Cherry-pick of #67132 (master commit 6077a8a) onto `releases/2.60.1`. #64772, which is in 2.60, re-anchors CPython 3.14's stack-protection bounds to the async actor's fiber stack on each task switch, to fix a memory leak. But the re-anchor runs after `task_execution_handler` has already made a Python call on the new fiber. That call can see the stale bounds and raise a spurious `RecursionError`, which crashes the actor worker with `Check failed: objects_valid 1 return objects expected, 1 returned. Object at idx 0 was not stored.` This is #66399 (P1). #67132 re-anchors the boundary to the current stack before any Python call in `task_execution_handler`. ## Related issues Related to #67132 and #66399. ## Additional information ### Cherry-pick details Applied cleanly with `git cherry-pick -x`. It has the same 2 files, +287/-106, and the same `git patch-id --stable` as the master commit. No prerequisite commits are missing: - After the pick, `test_asyncio.py` is identical to master at 6077a8a. - `_raylet.pyx` differs from master at that commit only by #66514 ("Guard local GC during core worker startup"), which isn't on this branch. - #66514 changes only `gc_collect`, while #67132 changes only `task_execution_handler`, so this change doesn't depend on it. Not a duplicate: this branch doesn't contain #67132, and no PR against `releases/2.60.1` references it. ### Testing | Command | Result | |---|---| | `pre-commit run --files python/ray/_raylet.pyx python/ray/tests/test_asyncio.py` | Passed, including cython-lint | I didn't run the tests locally. `_raylet.pyx` needs a full Ray build, which wasn't practical on my machine. Both new tests in `test_asyncio.py` skip below CPython 3.14. Premerge CI runs the core Python tests on 3.10 and 3.12, so it runs the rest of `test_asyncio.py` against the changed `task_execution_handler`, but not these two tests. AI assistance was used to prepare this cherry-pick. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: davik <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: Kunchen (David) Dai <[email protected]>
…rent stack before py calls (#67132) (#68023) ## Description Cherry-pick of #67132 (master commit 6077a8a) onto `releases/2.59.2`. #64772, which is in 2.59, re-anchors CPython 3.14's stack-protection bounds to the async actor's fiber stack on each task switch, to fix a memory leak. But the re-anchor runs after `task_execution_handler` has already made a Python call on the new fiber. That call can see the stale bounds and raise a spurious `RecursionError`, which crashes the actor worker with `Check failed: objects_valid 1 return objects expected, 1 returned. Object at idx 0 was not stored.` This is #66399 (P1). #67132 re-anchors the boundary to the current stack before any Python call in `task_execution_handler`. ## Related issues Related to #67132 and #66399. The same pick for 2.60.1 is #67996. ## Additional information ### Cherry-pick details Applied cleanly with `git cherry-pick -x`. It has the same 2 files, +287/-106, and the same `git patch-id --stable` as the master commit. No prerequisite commits are missing: - #64772 is on this branch; it merged to master before the 2.59 branch cut. - `_raylet.pyx` differs from master at 6077a8a by #66514, #65243 and #65487, which aren't on this branch. None of them touches `task_execution_handler`, the only function #67132 changes. - `test_asyncio.py` differs from master by tests that #66576 and #65243 add. #67132's two tests go after `test_async_actor_finalizes_objects_dropped_on_fiber`, which this branch has from #64772. Not a duplicate: this branch doesn't contain #67132, and no PR against `releases/2.59.2` references it. ### Testing | Command | Result | |---|---| | `pre-commit run --files python/ray/_raylet.pyx python/ray/tests/test_asyncio.py` | Passed, including cython-lint | I didn't run the tests locally. `_raylet.pyx` needs a full Ray build, which wasn't practical on my machine. Both new tests in `test_asyncio.py` skip below CPython 3.14. Premerge CI on this branch runs the core Python tests on 3.10, and postmerge also on 3.12, so it runs the rest of `test_asyncio.py` against the changed `task_execution_handler`, but not these two tests. AI assistance was used to prepare this cherry-pick. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: davik <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: Kunchen (David) Dai <[email protected]>
Description
A
LocalGCRPC can arrive before Python assignsglobal_worker.core_worker. The resultingAttributeErrorescapes the Cython callback and can crash the process inPyTraceBack_Here.Skip the request while the core worker is unavailable, and catch callback exceptions while holding the GIL in both threaded and synchronous GC modes. Add subprocess-isolated regression tests that send real
LocalGCRPCs, exercise missing initialization and injectedRuntimeError/SystemExit, and verify that subsequent GC still collects cyclic objects.Related issues
Fixes #66454.
Validation
8a94f8b467624322b961228a52350678d3d9b9f3,python -m pytest --noconftest --import-mode=importlib python/ray/tests/test_global_gc.py -k local_gc_callback_recovery -x -q --tb=shortreproducesSIGSEGVinPyTraceBack_Hereon the uninitialized case.PYTHONPATH=python RAY_ENABLE_WINDOWS_OR_OSX_CLUSTER=1 python -m pytest python/ray/tests/test_global_gc.py -q --tb=short: 12 passed, including all five new regression cases and the existing single-node, multi-node, object-store-pressure, actor-lifecycle, interval, and background-thread tests.pre-commit run --files python/ray/_raylet.pyx python/ray/tests/test_global_gc.py: passed.git diff --check: passed.Local source build: macOS ARM64, Python 3.12.7, Bazel 7.5.0. Apple Clang required warning overrides for existing upstream code; these are command-line options only and are not included in this PR:
PYTHON3_BIN_PATH="$(command -v python)" bazel build -c fastbuild --jobs=4 \ --local_resources=memory=4096 \ --copt=-Wno-error=deprecated-builtins \ --host_copt=-Wno-error=deprecated-builtins \ --per_file_copt=src/ray/gcs/actor/gcs_actor_manager.cc@-Wno-error=shadow \ --per_file_copt=src/ray/gcs_rpc_client/global_state_accessor.cc@-Wno-error=unused-result \ //:ray_pkgAdditional information
Duplicate-work check: the issue timeline and searches for the issue number,
gc_collect,LocalGC, andtrigger_gcfound no competing fix. The reporter confirmed they had not started a PR and were happy for this work to proceed.AI assistance was used to investigate, implement, and test this change. This PR is a draft pending the human submitter's review before requesting maintainer review.