Skip to content

[CoreWorker] Optimize CoreWorker internal structures using absl::InlinedVector - #1

Closed
crazizorba wants to merge 2 commits into
400Ping:masterfrom
crazizorba:fix-400ping-error
Closed

crazizorba wants to merge 2 commits into
400Ping:masterfrom
crazizorba:fix-400ping-error

Conversation

@crazizorba

Copy link
Copy Markdown

Refactor: optimize internal structures within CoreWorker (ReferenceCounter and TaskManager) using absl::InlinedVector. Local tests passed (core_worker_test PASSED).

@crazizorba

Copy link
Copy Markdown
Author

Hi @400Ping ,

I have fixed the vector issue and verified it locally (core_worker_test passed successfully). Could you please approve or trigger the CI runs for this PR? Thank you!

@github-actions

github-actions Bot commented Jun 6, 2026

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale label Jun 6, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

Again, you can always ask for help on our discussion forum or Ray's public slack channel.

Thanks again for your contribution!

@github-actions github-actions Bot closed this Jun 20, 2026
400Ping pushed a commit that referenced this pull request Jul 6, 2026
…uctural PRs (ray-project#64414)

## Description

Two related fixes that get the incremental Read the Docs build
(DOC-1047, ray-project#64277) actually working.

### 1. Repair the cache producer (`ci/ray_ci/doc/`)

The postmerge `doc: build` step has crashed on every run since the
Sphinx 8.2.3 upgrade (ray-project#64070), so **no doc build cache has been uploaded
since Jun 23**. `make html` builds the docs with the docbuild image's
Python (Sphinx 8.2.3) and writes `environment.pickle`, but
`_massage_cache` then unpickled it in-process under Bazel's pinned
Sphinx (6.2.1):

```
File ".../ci/ray_ci/doc/build_cache.py", line 50, in _massage_cache
    environment_cache = pickle.load(f)
ModuleNotFoundError: No module named 'sphinx.util._files'
```

(`sphinx.util._files` is new in Sphinx 8.x, so 6.2.1 can't load the
pickle.) → upload crashes → no cache. Without a fresh cache, RtD only
finds the last pre-upgrade (7.x) cache, rejects it as `build environment
version not current`, and rebuilds cold every time — so the incremental
path never engages.

**Fix:** run the pickle massage under the doc-build environment's Python
(`PYTHONPATH` unset), mirroring how `_build()` runs `make html`, so the
pickle is read by the same Sphinx that wrote it. Extracted into
`ci/ray_ci/doc/massage_cache.py` (stdlib-only) per review.

### 2. Skip the incremental build for structural PRs
(`.readthedocs.yaml`)

Incremental Sphinx doesn't delete output for sources removed/renamed in
a PR, and the restored cache carries generated stubs — so a structural
PR can leave stale pages in the preview. The fail-fast fallback only
catches cases that emit a `-W` warning; a clean rename/delete
(references updated) is silent. So if `git diff --diff-filter=D` finds
any removed/moved source under `doc/source/`, route straight to the
clean build (`rtd-fallback`). The proper prune-on-restore fix (so these
PRs can *use* the cache) is tracked in **DOC-1314**.

## Related issues

Related to
**[DOC-1047](https://anyscale1.atlassian.net/browse/DOC-1047)** (epic
[DOC-1046](https://anyscale1.atlassian.net/browse/DOC-1046)); unblocks
the incremental RtD builds added in ray-project#64277. Follow-up:
**[DOC-1314](https://anyscale1.atlassian.net/browse/DOC-1314)**.

## Additional information

- `ci/ray_ci/doc:test_build_cache` passes (3/3); `test_massage_cache`
exercises the real subprocess massage.
- The cache-upload path runs postmerge + master only, so change #1 is
fully verifiable only after merge — expected: the next postmerge
produces a Sphinx-8.2.3 cache that RtD then accepts.
- `.readthedocs.yaml` structural-detection uses `if ! git diff --quiet
--no-renames --diff-filter=D … 2>/dev/null` — the same shape as the
existing `post_checkout` step. An earlier `| grep` + `can't` version was
silently dropped by RTD's job-script preprocessor (the build step logged
`exit-code: None` and never ran), so the script now uses only constructs
already proven in `post_checkout`, with no in-script apostrophes or
pipes. Validated via YAML parse + `bash -n`.
- This bundles a `.readthedocs.yaml` (consumer) change with the `ci/`
(producer) fix at the author's request; happy to split if a reviewer
prefers.

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

---------

Signed-off-by: Ronny Roland <[email protected]>
Signed-off-by: Ronny <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
400Ping pushed a commit that referenced this pull request Jul 17, 2026
…nd (ray-project#64759)

## Why are these changes needed?

After ray-project#63657 merged, the C++ ThreadSanitizer (TSAN) build started
reporting data races in the embedded RocksDB GCS backend tests:

- `//src/ray/gcs/store_client/tests:rocksdb_store_client_test`
- `//src/ray/gcs/store_client/tests:rocksdb_concurrency_test`
- `//src/ray/gcs/store_client/tests:rocksdb_parity_test`

The reported races are **inside RocksDB itself**, e.g.:

```
WARNING: ThreadSanitizer: data race
  Write of size 2 by thread T180:
    #1 rocksdb::MemTable::Add(...)                       // memcpy of key bytes
  Previous read of size 2 by thread T182:
    #1 rocksdb::BytewiseComparatorImpl::Compare(...)     // memcmp during a Get
```

### Root cause

RocksDB is built as a static library by an **out-of-band CMake action**
(`bazel/rocksdb.BUILD` via `rules_foreign_cc`). Bazel's `--copt
-fsanitize=thread` and `--per_file_copt` from the `tsan` config only
apply to Bazel-compiled `cc_library` targets — they never reach the
CMake build. As a result, a TSAN-instrumented GCS test links an
**un-instrumented** `librocksdb.a`.

TSAN can intercept the plain `memcpy`/`memcmp` on the key/value bytes
inside RocksDB's lock-free memtable skiplist, but it **cannot see the
acquire/release atomics** RocksDB uses to publish and observe those
bytes (that synchronizing code is uninstrumented). Missing those
happens-before edges, TSAN reports false races.

Concurrent `Put`/`Get` across the store client's I/O offload pool is a
fully supported RocksDB operation, so these are false positives, not
real races. `report_atomic_races=0` (already set in the `tsan` config)
does not suppress them because the racing accesses are byte-wise
`memcpy`/`memcmp`, not atomic operations.

### Fix

Build RocksDB with its native `WITH_TSAN` CMake option under the `tsan`
config. RocksDB's `CMakeLists.txt` handles `WITH_TSAN` by adding
`-fsanitize=thread` to its own compile/link flags — the RocksDB-blessed
way to run it under TSAN. With RocksDB instrumented, ThreadSanitizer
understands its synchronization and the false positives disappear.

- `.bazelrc`: `--config=tsan` now sets `--define=ray_rocksdb_tsan=true`.
- `bazel/rocksdb.BUILD`: a `config_setting` reads that define and a
`cache_entries` `select()` flips `WITH_TSAN=ON` only for TSAN builds.

Non-TSAN builds are unaffected: the define is only set by
`--config=tsan`, and `WITH_TSAN` stays off in the default `select()`
branch. `--config=tsan-clang` inherits the define via `--config=tsan`.

### Verification

Reproduced and verified with the same toolchain CI uses
(`--config=tsan-clang`, clang 14, libc++). All three previously-failing
tests were built under TSAN and run (ASLR disabled via `setarch -R`,
`TSAN_OPTIONS=report_atomic_races=0`, matching CI):

| RocksDB build (clang-14 TSAN, identical otherwise) | Data races |
Result |
| --- | --- | --- |
| **Without this fix** (uninstrumented `librocksdb.a`) | **10** |
**FAILED** (TSAN exits 66) |
| **With this fix** (`WITH_TSAN=ON`) | **0** | **PASSED** |

The negative-control run (fix disabled via
`--define=ray_rocksdb_tsan=false`) reproduces the exact races from the
report — `rocksdb::MemTable::Add` (memcpy) racing
`rocksdb::BytewiseComparatorImpl::Compare` (memcmp) in the memtable
skiplist:

```
SUMMARY: ThreadSanitizer: data race in __interceptor_memcmp
  #1 rocksdb::(anonymous namespace)::BytewiseComparatorImpl::Compare(...) comparator.cc
  #1 rocksdb::MemTable::Add(...)
```

With the fix, the same runs are clean:

```
rocksdb_store_client_test   : 0 data races, [  PASSED  ] 12 tests
rocksdb_concurrency_test    : 0 data races, [  PASSED  ]  4 tests
rocksdb_parity_test         : 0 data races, [  PASSED  ]  2 tests
```

This confirms the fix both eliminates the reported races and that
removing it reproduces them — i.e. the instrumentation is the cause of
the change.

## Related issue number

Follow-up to ray-project#63657.

## Checks

- [x] I've signed off every commit (by using the -s flag, i.e., `git
commit -s`) in this PR.
- [x] I've made sure the tests are passing. Note that there might be a
few flaky tests, see the recent failures at https://flakey-tests.ray.io/
- Testing Strategy
   - [x] Unit tests
   - [ ] Release tests
   - [ ] This PR is not tested :(

---------

Signed-off-by: Santosh Jha <[email protected]>
Co-authored-by: Copilot <[email protected]>
400Ping pushed a commit that referenced this pull request Aug 18, 2026
…uctural PRs (ray-project#64414)

## Description

Two related fixes that get the incremental Read the Docs build
(DOC-1047, ray-project#64277) actually working.

### 1. Repair the cache producer (`ci/ray_ci/doc/`)

The postmerge `doc: build` step has crashed on every run since the
Sphinx 8.2.3 upgrade (ray-project#64070), so **no doc build cache has been uploaded
since Jun 23**. `make html` builds the docs with the docbuild image's
Python (Sphinx 8.2.3) and writes `environment.pickle`, but
`_massage_cache` then unpickled it in-process under Bazel's pinned
Sphinx (6.2.1):

```
File ".../ci/ray_ci/doc/build_cache.py", line 50, in _massage_cache
    environment_cache = pickle.load(f)
ModuleNotFoundError: No module named 'sphinx.util._files'
```

(`sphinx.util._files` is new in Sphinx 8.x, so 6.2.1 can't load the
pickle.) → upload crashes → no cache. Without a fresh cache, RtD only
finds the last pre-upgrade (7.x) cache, rejects it as `build environment
version not current`, and rebuilds cold every time — so the incremental
path never engages.

**Fix:** run the pickle massage under the doc-build environment's Python
(`PYTHONPATH` unset), mirroring how `_build()` runs `make html`, so the
pickle is read by the same Sphinx that wrote it. Extracted into
`ci/ray_ci/doc/massage_cache.py` (stdlib-only) per review.

### 2. Skip the incremental build for structural PRs
(`.readthedocs.yaml`)

Incremental Sphinx doesn't delete output for sources removed/renamed in
a PR, and the restored cache carries generated stubs — so a structural
PR can leave stale pages in the preview. The fail-fast fallback only
catches cases that emit a `-W` warning; a clean rename/delete
(references updated) is silent. So if `git diff --diff-filter=D` finds
any removed/moved source under `doc/source/`, route straight to the
clean build (`rtd-fallback`). The proper prune-on-restore fix (so these
PRs can *use* the cache) is tracked in **DOC-1314**.

## Related issues

Related to
**[DOC-1047](https://anyscale1.atlassian.net/browse/DOC-1047)** (epic
[DOC-1046](https://anyscale1.atlassian.net/browse/DOC-1046)); unblocks
the incremental RtD builds added in ray-project#64277. Follow-up:
**[DOC-1314](https://anyscale1.atlassian.net/browse/DOC-1314)**.

## Additional information

- `ci/ray_ci/doc:test_build_cache` passes (3/3); `test_massage_cache`
exercises the real subprocess massage.
- The cache-upload path runs postmerge + master only, so change #1 is
fully verifiable only after merge — expected: the next postmerge
produces a Sphinx-8.2.3 cache that RtD then accepts.
- `.readthedocs.yaml` structural-detection uses `if ! git diff --quiet
--no-renames --diff-filter=D … 2>/dev/null` — the same shape as the
existing `post_checkout` step. An earlier `| grep` + `can't` version was
silently dropped by RTD's job-script preprocessor (the build step logged
`exit-code: None` and never ran), so the script now uses only constructs
already proven in `post_checkout`, with no in-script apostrophes or
pipes. Validated via YAML parse + `bash -n`.
- This bundles a `.readthedocs.yaml` (consumer) change with the `ci/`
(producer) fix at the author's request; happy to split if a reviewer
prefers.

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

---------

Signed-off-by: Ronny Roland <[email protected]>
Signed-off-by: Ronny <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: 400Ping <[email protected]>
400Ping pushed a commit that referenced this pull request Aug 18, 2026
…nd (ray-project#64759)

## Why are these changes needed?

After ray-project#63657 merged, the C++ ThreadSanitizer (TSAN) build started
reporting data races in the embedded RocksDB GCS backend tests:

- `//src/ray/gcs/store_client/tests:rocksdb_store_client_test`
- `//src/ray/gcs/store_client/tests:rocksdb_concurrency_test`
- `//src/ray/gcs/store_client/tests:rocksdb_parity_test`

The reported races are **inside RocksDB itself**, e.g.:

```
WARNING: ThreadSanitizer: data race
  Write of size 2 by thread T180:
    #1 rocksdb::MemTable::Add(...)                       // memcpy of key bytes
  Previous read of size 2 by thread T182:
    #1 rocksdb::BytewiseComparatorImpl::Compare(...)     // memcmp during a Get
```

### Root cause

RocksDB is built as a static library by an **out-of-band CMake action**
(`bazel/rocksdb.BUILD` via `rules_foreign_cc`). Bazel's `--copt
-fsanitize=thread` and `--per_file_copt` from the `tsan` config only
apply to Bazel-compiled `cc_library` targets — they never reach the
CMake build. As a result, a TSAN-instrumented GCS test links an
**un-instrumented** `librocksdb.a`.

TSAN can intercept the plain `memcpy`/`memcmp` on the key/value bytes
inside RocksDB's lock-free memtable skiplist, but it **cannot see the
acquire/release atomics** RocksDB uses to publish and observe those
bytes (that synchronizing code is uninstrumented). Missing those
happens-before edges, TSAN reports false races.

Concurrent `Put`/`Get` across the store client's I/O offload pool is a
fully supported RocksDB operation, so these are false positives, not
real races. `report_atomic_races=0` (already set in the `tsan` config)
does not suppress them because the racing accesses are byte-wise
`memcpy`/`memcmp`, not atomic operations.

### Fix

Build RocksDB with its native `WITH_TSAN` CMake option under the `tsan`
config. RocksDB's `CMakeLists.txt` handles `WITH_TSAN` by adding
`-fsanitize=thread` to its own compile/link flags — the RocksDB-blessed
way to run it under TSAN. With RocksDB instrumented, ThreadSanitizer
understands its synchronization and the false positives disappear.

- `.bazelrc`: `--config=tsan` now sets `--define=ray_rocksdb_tsan=true`.
- `bazel/rocksdb.BUILD`: a `config_setting` reads that define and a
`cache_entries` `select()` flips `WITH_TSAN=ON` only for TSAN builds.

Non-TSAN builds are unaffected: the define is only set by
`--config=tsan`, and `WITH_TSAN` stays off in the default `select()`
branch. `--config=tsan-clang` inherits the define via `--config=tsan`.

### Verification

Reproduced and verified with the same toolchain CI uses
(`--config=tsan-clang`, clang 14, libc++). All three previously-failing
tests were built under TSAN and run (ASLR disabled via `setarch -R`,
`TSAN_OPTIONS=report_atomic_races=0`, matching CI):

| RocksDB build (clang-14 TSAN, identical otherwise) | Data races |
Result |
| --- | --- | --- |
| **Without this fix** (uninstrumented `librocksdb.a`) | **10** |
**FAILED** (TSAN exits 66) |
| **With this fix** (`WITH_TSAN=ON`) | **0** | **PASSED** |

The negative-control run (fix disabled via
`--define=ray_rocksdb_tsan=false`) reproduces the exact races from the
report — `rocksdb::MemTable::Add` (memcpy) racing
`rocksdb::BytewiseComparatorImpl::Compare` (memcmp) in the memtable
skiplist:

```
SUMMARY: ThreadSanitizer: data race in __interceptor_memcmp
  #1 rocksdb::(anonymous namespace)::BytewiseComparatorImpl::Compare(...) comparator.cc
  #1 rocksdb::MemTable::Add(...)
```

With the fix, the same runs are clean:

```
rocksdb_store_client_test   : 0 data races, [  PASSED  ] 12 tests
rocksdb_concurrency_test    : 0 data races, [  PASSED  ]  4 tests
rocksdb_parity_test         : 0 data races, [  PASSED  ]  2 tests
```

This confirms the fix both eliminates the reported races and that
removing it reproduces them — i.e. the instrumentation is the cause of
the change.

## Related issue number

Follow-up to ray-project#63657.

## Checks

- [x] I've signed off every commit (by using the -s flag, i.e., `git
commit -s`) in this PR.
- [x] I've made sure the tests are passing. Note that there might be a
few flaky tests, see the recent failures at https://flakey-tests.ray.io/
- Testing Strategy
   - [x] Unit tests
   - [ ] Release tests
   - [ ] This PR is not tested :(

---------

Signed-off-by: Santosh Jha <[email protected]>
Co-authored-by: Copilot <[email protected]>
Signed-off-by: 400Ping <[email protected]>
owenowenisme pushed a commit that referenced this pull request Oct 26, 2026
…-project#67254)

## Why

`upload_wheels_to_pypi()` shells out to `twine upload` **once per
file**, in `sorted()` order, with `check=True`. A single rejected file
therefore aborts the loop and strands every wheel after it — and because
a retry starts over at file #1, which it already uploaded successfully,
the retry fails immediately too. The step cannot recover on its own.

This bit the 2.58.1 release. The TestPyPI upload was rejected partway
through (the project had hit its size limit), leaving **9 of 24 wheels
unpublished**: all four `cp314` wheels, `cp313-win_amd64`, and all four
`ray_cpp` wheels (`ray_cpp` sorts after `ray-`, so none of them were
attempted). Every retry of the job 400'd on the first file, and the
missing wheels had to be uploaded manually.

## What

Adds `--skip-existing` to the twine invocation, making the step
idempotent: files already on the index are skipped rather than failing
the run, so a partial upload is repaired by simply re-running the job.

This only affects *duplicate file* rejections — twine still fails the
step on other errors (bad auth, size limits, malformed metadata), which
is the behavior we want.

## Tests

`ci/ray_ci/automation/test_pypi_lib.py` asserts the exact twine argv;
updated accordingly. All 9 tests pass locally.

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

Signed-off-by: elliot-barn <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
owenowenisme pushed a commit that referenced this pull request Oct 26, 2026
…calls (ray-project#67132)

## Description
In ray-project#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 ray-project#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 ray-project#66399

---------

Signed-off-by: davik <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants