Skip to content

[Core] Guard local GC during core worker startup - #66514

Merged
elliot-barn merged 2 commits into
ray-project:masterfrom
bhushanasati25:fix-local-gc-startup-66454
Oct 20, 2026
Merged

elliot-barn merged 2 commits into
ray-project:masterfrom
bhushanasati25:fix-local-gc-startup-66454

Conversation

@bhushanasati25

Copy link
Copy Markdown
Contributor

Description

A LocalGC RPC can arrive before Python assigns global_worker.core_worker. The resulting AttributeError escapes the Cython callback and can crash the process in PyTraceBack_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 LocalGC RPCs, exercise missing initialization and injected RuntimeError/SystemExit, and verify that subsequent GC still collects cyclic objects.

Related issues

Fixes #66454.

Validation

  • On the unmodified nightly wheel at 8a94f8b467624322b961228a52350678d3d9b9f3, python -m pytest --noconftest --import-mode=importlib python/ray/tests/test_global_gc.py -k local_gc_callback_recovery -x -q --tb=short reproduces SIGSEGV in PyTraceBack_Here on the uninitialized case.
  • With the patched native extension built from source, 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_pkg

Additional information

Duplicate-work check: the issue timeline and searches for the issue number, gc_collect, LocalGC, and trigger_gc found 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.

@bhushanasati25
bhushanasati25 marked this pull request as ready for review September 27, 2026 04:12
@bhushanasati25
bhushanasati25 requested a review from a team as a code owner September 27, 2026 04:12

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

Comment thread python/ray/_raylet.pyx
Comment on lines +2879 to +2882
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")

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

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

@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Sep 27, 2026
@karticam karticam self-assigned this Sep 29, 2026
@karticam karticam added the go add ONLY when ready to merge, run all tests label Oct 9, 2026

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

Added a few comments. Please take a look

Comment thread python/ray/_raylet.pyx
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:

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.

can you please add here in the comments why is it safe to skip the GC here?

Comment thread python/ray/_raylet.pyx
logger.debug(
"gc.collect() freed {} refs in {} seconds".format(
num_freed, end - start))
except BaseException:

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.

is this currently hit in practice or just a defensive measure?

logger = logging.getLogger(__name__)


@pytest.mark.parametrize(

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.

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?

@karticam

Copy link
Copy Markdown
Contributor

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.

@karticam
karticam force-pushed the fix-local-gc-startup-66454 branch from d245ceb to 77d8f94 Compare October 19, 2026 20:27
@rueian
rueian enabled auto-merge (squash) October 20, 2026 17:10
@elliot-barn
elliot-barn disabled auto-merge October 20, 2026 20:41
@elliot-barn
elliot-barn merged commit fcda0b2 into ray-project:master Oct 20, 2026
6 of 7 checks passed
sai-miduthuri added a commit that referenced this pull request Nov 10, 2026
…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]>
sai-miduthuri added a commit that referenced this pull request Nov 10, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community core Issues that should be addressed in Ray Core go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Core] Worker SIGSEGV in PyTraceBack_Here when LocalGC arrives before worker.core_worker is assigned

4 participants