Skip to content

[cherry-pick][2.60.1][Core] Reanchor stack protection boundary to current stack before py calls (#67132) - #67996

Merged
sai-miduthuri merged 1 commit into
releases/2.60.1from
sai-miduthuri/cherry-pick-67132-2.60.1
Nov 10, 2026
Merged

sai-miduthuri merged 1 commit into
releases/2.60.1from
sai-miduthuri/cherry-pick-67132-2.60.1

Conversation

@sai-miduthuri

Copy link
Copy Markdown
Contributor

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:

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

…calls (#67132)

## Description
In #64772, we began reanchoring
the python's stack boundaries each time ray swapped between async actor
task contexts in order to provide a ballpark estimate of the new fiber
stack location to python to make sure python doesn't leak memory in
3.14.

However, as issue #66399 has
reported, this act of reanchoring has the potential to trigger recursive
depth failure if any python calls is invoked on the new fiber stack
location before the reanchoring occurs.

We have reproduced both failure behaviors reported in the issue locally
via the repro script below:

```py
import asyncio
import os
import random
import time

import ray

DURATION_S = 600

@ray.remote
class Backend:
    async def handle(self, payload: bytes, delay: float) -> bytes:
        await asyncio.sleep(delay)
        return payload[: random.randint(0, len(payload))]

@ray.remote(max_concurrency=1000)
class RouterManager:
    def __init__(self, backends):
        self.backends = backends

    async def route(self, payload: bytes, delay: float, resp_size: int) -> bytes:
        # Forwarding some calls downstream matters: without it, the crash
        # did not reproduce in 20 minutes of the same load.
        if random.random() < 0.3:
            await random.choice(self.backends).handle.remote(payload, delay / 2)
        await asyncio.sleep(delay)
        return b"r" * resp_size

def submit(actor):
    # Args < 100 KiB are inlined and deserialized on the fiber thread; returns
    # are serialized there too. Varying both fragments that thread's heap.
    return actor.route.remote(
        random.choice(PAYLOADS), random.uniform(0, 0.005), random.randint(0, 90 * 1024)
    )

ray.init()
PAYLOADS = [os.urandom(random.randint(0, 90 * 1024)) for _ in range(256)]
backends = [Backend.remote() for _ in range(2)]
actors = [RouterManager.remote(backends) for _ in range(4)]
inflight = {submit(a): a for a in actors for _ in range(2000)}

start, done = time.time(), 0
while time.time() - start < DURATION_S:
    ready, _ = ray.wait(list(inflight), num_returns=min(500, len(inflight)), timeout=1)
    for ref in ready:
        actor = inflight.pop(ref)
        ray.get(ref)  # Raises ActorDiedError once a worker crashes.
        inflight[submit(actor)] = actor
        done += 1
    print(f"[{time.time() - start:5.0f}s] {done} tasks", end="\r")

print(f"\nNo crash after {DURATION_S}s ({done} tasks).")
```

And on master we were able to observe the reported failure from the
issue locally:
```bash
(RouterManager pid=3044853) [2026-10-16 23:45:04,766 C 3044853 3046700] task_receiver.cc:136:  An unexpected system state has occurred. You have likely discovered a bug in Ray. Please report this issue at https://github.com/ray-project/ray/issues and we'll work with you to fix it. Check failed: objects_valid 1 return objects expected, 1 returned. Object at idx 0 was not stored.
(RouterManager pid=3044853) *** StackTrace Information ***
(RouterManager pid=3044853) /home/ubuntu/ray/python/ray/_raylet.so(+0x19335d8) [0x7f5269d925d8] ray::operator<<()
(RouterManager pid=3044853) /home/ubuntu/ray/python/ray/_raylet.so(_ZN3ray6RayLogD1Ev+0x67) [0x7f5269d95ba7] ray::RayLog::~RayLog()
(RouterManager pid=3044853) /home/ubuntu/ray/python/ray/_raylet.so(_ZN3ray4core12TaskReceiver25HandleTaskExecutionResultENS_6StatusERKNS_17TaskSpecificationERKNS0_19TaskExecutionResultERKSt8functionIFvS2_S9_IFvvEESB_EEPNS_3rpc13PushTaskReplyE+0x1845) [0x7f5269125f05] ray::core::TaskReceiver::HandleTaskExecutionResult()
(RouterManager pid=3044853) /home/ubuntu/ray/python/ray/_raylet.so(+0xcc9e7d) [0x7f5269128e7d] ray::core::TaskReceiver::ExecuteTask()
(RouterManager pid=3044853) /home/ubuntu/ray/python/ray/_raylet.so(_ZN3ray4core32UnorderedActorTaskExecutionQueue31AcceptRequestOrRejectIfCanceledENS_6TaskIDERNS0_13TaskToExecuteE+0x17a) [0x7f5269137cca] ray::core::UnorderedActorTaskExecutionQueue::AcceptRequestOrRejectIfCanceled()
(RouterManager pid=3044853) /home/ubuntu/ray/python/ray/_raylet.so(+0xcda2ce) [0x7f52691392ce] std::_Function_handler<>::_M_invoke()
(RouterManager pid=3044853) /home/ubuntu/ray/python/ray/_raylet.so(+0xcd9aed) [0x7f5269138aed] std::__invoke_impl<>()
(RouterManager pid=3044853) /home/ubuntu/ray/python/ray/_raylet.so(+0xce024c) [0x7f526913f24c] boost::fibers::worker_context<>::run_()
(RouterManager pid=3044853) /home/ubuntu/ray/python/ray/_raylet.so(+0xce042f) [0x7f526913f42f] boost::context::detail::fiber_record<>::run()
(RouterManager pid=3044853) /home/ubuntu/ray/python/ray/_raylet.so(+0xce03bc) [0x7f526913f3bc] boost::context::detail::fiber_entry<>()
(RouterManager pid=3044853) /home/ubuntu/ray/python/ray/_raylet.so(+0xce43af) [0x7f52691433af] make_fcontext
(RouterManager pid=3044853)
```

Additionally, we have also verified that the issue was indeed caused by
the actor failing at the `disable_client_hook` call before reanchor due
too recursion depth exceeded by attaching gdb to the run and logging out
the stack information at the time of failure:
```bash
  recorded bounds : top=0x7f48d4269108 base=0x7f48d4229108 size=256 KiB soft=0x7f48d4231108 hard=0x7f48d422d108
  stack pointer   : sp=0x7f48d422ec28  used(top-sp)=233 kB  sp-base=22.8 KiB  -> RecursionError (soft..hard)
  python callee   : <unavailable: value has been optimized out>
  current fiber   : [0x7f48d41f0ac0, 0x7f48d4230ac0) entry-to-check depth=7.6 KiB; this_top - recorded_base = +30.4 KiB
  own malloc chunk: user=0x7f48d41f0ac0 size=0x40010 flags=0x5 (heap)
  chunk above     : user=0x7f48d4230ad0 size=0x3d930 in_use=False
  C backtrace:
    _Py_CheckRecursiveCall @ 0x5634c5be5710
    _Py_EnterRecursiveCallTstate @ 0x5634c5a5e5b7
    _PyEval_EvalFrameDefault @ 0x5634c5a5e5b7
    _PyEval_EvalFrame @ 0x5634c5a82a45
    _PyEval_Vector @ 0x5634c5a82a45
    _PyFunction_Vectorcall @ 0x5634c5a82a45
    __pyx_f_3ray_7_raylet_task_execution_handler(ray::rpc::Address const&, ray::rpc::TaskType, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocat @ 0x7f5268e52c02
    ray::Status std::__invoke_impl<ray::Status, ray::Status (*&)(ray::rpc::Address const&, ray::rpc::TaskType, std::__cxx11::basic_string<char, std::char_traits<cha @ 0x7f5268e996c9
    std::_Function_handler<ray::Status (ray::rpc::Address const&, ray::rpc::TaskType, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>  @ 0x7f5268e992c0
    ray::core::CoreWorker::ExecuteTask(ray::TaskSpecification const&, std::optional<std::unordered_map<std::__cxx11::basic_string<char, std::char_traits<char>, std: @ 0x7f5268f665b5
    ray::Status std::__invoke_impl<ray::Status, ray::Status (ray::core::CoreWorker::*&)(ray::TaskSpecification const&, std::optional<std::unordered_map<std::__cxx11 @ 0x7f5268fb1446
    std::_Function_handler<ray::Status (ray::TaskSpecification const&, std::optional<std::unordered_map<std::__cxx11::basic_string<char, std::char_traits<char>, std @ 0x7f5268fb1296
    ray::core::TaskReceiver::ExecuteTask(ray::core::TaskToExecute&) @ 0x7f5269128d69
    ray::core::UnorderedActorTaskExecutionQueue::AcceptRequestOrRejectIfCanceled(ray::TaskID, ray::core::TaskToExecute&) @ 0x7f5269137cca
    std::_Function_handler<void (), ray::core::UnorderedActorTaskExecutionQueue::RunRequestWithResolvedDependencies(ray::core::TaskToExecute)::$_1>::_M_invoke(std:: @ 0x7f52691392ce
    void std::__invoke_impl<void, ray::core::FiberState::EnqueueFiber(std::function<void ()>&&)::{lambda()#1}&>(std::__invoke_other, ray::core::FiberState::EnqueueF @ 0x7f5269138aed
    boost::fibers::worker_context<ray::core::FiberState::FiberState(int, std::function<std::function<void ()> ()>)::{lambda()#1}::operator()() const::{lambda()#1}>: @ 0x7f526913f24c
    boost::context::detail::fiber_record<boost::context::fiber, boost::context::basic_fixedsize_stack<boost::context::stack_traits>&, std::_Bind<boost::context::fib @ 0x7f526913f42f
    void boost::context::detail::fiber_entry<boost::context::detail::fiber_record<boost::context::fiber, boost::context::basic_fixedsize_stack<boost::context::stack @ 0x7f526913f3bc
    make_fcontext @ 0x7f52691433af
```

From these logs, we confirm that the issue is indeed caused by calls
into python triggering `Py_CheckRecursiveCall`, leading to the worker
crash, causing no valid objects to be returned.

### What this PR changes
This PR takes the proposed suggestion of the issue and reanchors the
stack before any python calls are made (i.e. `disable_client_hook`).

The only other call site for reanchor within the code is when we resume
execution after yielding the fiber in
`run_async_func_or_coro_in_event_loop`. In this case, no python calls
occurs before resuming execution and reanchor. Thus no reordering is
needed here.

## Related issues
Fixes #66399

---------

Signed-off-by: davik <[email protected]>
(cherry picked from commit 6077a8a)
Signed-off-by: Sai Miduthuri <[email protected]>
@sai-miduthuri
sai-miduthuri requested a review from a team as a code owner November 9, 2026 23:36

@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 modifies task_execution_handler in python/ray/_raylet.pyx to ensure that CPython's stack protection is re-anchored to the fiber stack before any Python call is executed on that fiber. This is done by splitting the with gil, disable_client_hook(): block so that RayReanchorStackProtectionToCurrentFiberStack runs immediately after acquiring the GIL, preventing potential stack depth check failures in Python 3.14+. Additionally, two unit tests are added in python/ray/tests/test_asyncio.py to verify this behavior and prevent memory leaks on idle async actors. There are no review comments to address, and I have no further feedback to provide.

@ray-gardener ray-gardener Bot added the core Issues that should be addressed in Ray Core label Nov 10, 2026
@sai-miduthuri sai-miduthuri added the go add ONLY when ready to merge, run all tests label Nov 10, 2026
@sai-miduthuri
sai-miduthuri merged commit fc71415 into releases/2.60.1 Nov 10, 2026
6 of 7 checks passed
@sai-miduthuri
sai-miduthuri deleted the sai-miduthuri/cherry-pick-67132-2.60.1 branch November 10, 2026 23:16
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

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.

2 participants