Skip to content

[core][rdt] nixl: don't remove a remote agent while transfers on it are in flight - #67389

Merged
Sparks0219 merged 5 commits into
ray-project:masterfrom
BatshevaBlack:rdt-nixl-agent-lock
Nov 2, 2026
Merged

Sparks0219 merged 5 commits into
ray-project:masterfrom
BatshevaBlack:rdt-nixl-agent-lock

Conversation

@BatshevaBlack

@BatshevaBlack BatshevaBlack commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #65905

Problem. fetch_and_get_rdt_objects posts every NIXL transfer before waiting on any. If the source deregisters memory between two posts, its metadata version changes. A later fetch then calls remove_remote_agent() while an earlier transfer on the same agent is still in flight, and that transfer fails with NIXL_ERR_REMOTE_DISCONNECT.

Fix. A per-agent lock, plus a set of in-flight transfers per agent. Before removing an agent (on a version change or eviction), the fetch takes that agent's lock and polls its in-flight transfers to a final state. Only the agent whose metadata changed is affected. The poll gives up after RDT_FETCH_FAIL_TIMEOUT_SECONDS, so a stuck transfer fails the fetch instead of hanging it.

@BatshevaBlack
BatshevaBlack requested a review from a team as a code owner October 25, 2026 07:14

@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 introduces thread-safe mechanisms to manage NIXL remote agents and prevent them from being removed while transfers are still in flight. It adds locks per remote agent, tracks in-flight transfers, and implements safe eviction and version-change handling. Additionally, comprehensive unit and integration tests are added to verify these concurrency behaviors. The review feedback highlights several potential race conditions where shared dictionaries like _inflight_xfers and _agent_locks are accessed or mutated concurrently without proper synchronization, suggesting they be protected by _remote_agents_lock.

@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Oct 25, 2026
@Sparks0219

Copy link
Copy Markdown
Contributor

Thanks for reworking this, looks a lot cleaner! 😄

@BatshevaBlack
BatshevaBlack force-pushed the rdt-nixl-agent-lock branch 2 times, most recently from e6e8cea to 506b9c2 Compare October 26, 2026 09:48
@Sparks0219 Sparks0219 added the go add ONLY when ready to merge, run all tests label Nov 1, 2026
spare = torch.ones(8, dtype=torch.uint8)
spare_ref = put(spare)
del spare_ref
gc.collect()

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.

nit: don't need this gc.collect

# A finalizer on this thread may release the handle meanwhile.
while (
xfer_handle in inflight
and nixl_agent.check_xfer_state(xfer_handle) == "PROC"

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.

I was reading up a bit on when python triggers gc and looks like it's whenever you also enter a function. So technically even if you have the guard above, the moment you call check_xfer_state python gc can decide to run and trigger the use after free still. It's like... pretty unlikely though so fine leaving it up as a follow up.

# LRU cache of remote agent names. When full, the least
# recently used remote agent is evicted and remove_remote_agent is called.
self._remote_agents: OrderedDict = OrderedDict()
# Guards _remote_agents only, held briefly and never while waiting for an agent lock.

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.

This ordering might break since gc can run whenever, for example during _evict_if_full once we grab the cache lock python gc could run and grab the agent lock. Might need some form of check in the finalizer there regarding whether we currently hold some lock, or something along those lines. Fine leaving as a TODO

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

LGTM, couple of nits which I'm fine leaving as follow ups

…re in flight

Each remote agent gets a lock and a set of its in-flight transfers. Before
removing an agent (metadata version change or cache eviction), the remover
polls those transfers until they finish, so a batched get no longer fails
earlier transfers with NIXL_ERR_REMOTE_DISCONNECT.

Signed-off-by: BatshevaBlack <[email protected]>
…rsion changes

Five receivers sharing one GPU batch-get from a single driver whose objects
each carry a different metadata version. A fetch that sees a new version removes
the remote agent, which must not break the earlier transfers still in flight on
it. Without the fix this fails with NIXL_ERR_REMOTE_DISCONNECT.

Signed-off-by: BatshevaBlack <[email protected]>
… or add fails

Drop the cache entry before removing an agent, so a failed removal does not block eviction and a failed add does not leave a stale version. Make wait_fetch_complete skip a poll while the agent lock is busy, so its timeout and abort checks still run.

Signed-off-by: BatshevaBlack <[email protected]>
The helper also polls in-flight transfers, removes a stale agent and updates the cache, not just adds the agent.

Signed-off-by: BatshevaBlack <[email protected]>
…polling

Rename _remote_agents_lock to _remote_agent_cache_lock and _agent_locks to _remote_agent_locks. Skip a transfer in _finish_transfers if a finalizer on the same thread already released it.

Signed-off-by: BatshevaBlack <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 93b3b24. Configure here.

@Sparks0219
Sparks0219 merged commit 541bd56 into ray-project:master Nov 2, 2026
6 checks passed
Sparks0219 pushed a commit that referenced this pull request Nov 3, 2026
Changes

- Test nit. Remove an unneeded gc.collect() in
test_nixl_concurrent_batched_get_with_agent_version_change.
wait_tensor_freed already waits for the free.
- Handles released while polling. _finish_transfers polled handles that
a garbage-collection finalizer on the same thread could release, leading
to a use after free. While an agent's transfers are being polled,
_cleanup_transfer now defers releasing handles and _finish_transfers
releases them when polling ends. This replaces the xfer_handle in
inflight check, which narrowed the window but didn't close it.
- Finalizer under the cache lock. Garbage collection could run
_cleanup_transfer on a thread holding _remote_agent_cache_lock, where
waiting for an agent lock can deadlock with a thread that holds that
agent lock and wants the cache lock. Cache-lock sections now go through
_cache_guard(). While a thread holds the lock, _cleanup_transfer defers
its work and the guard replays it after releasing the lock.

---------

Signed-off-by: BatshevaBlack <[email protected]>
edoakes pushed a commit that referenced this pull request Nov 17, 2026
…ory (#68009)

## Why

`test_usage_stats.py::test_worker_crash_increment_stats` triggered an
OOM kill by allocating memory (~8 GB per loop) until the raylet's memory
monitor hit the 95% threshold. The CI job runs 3 test containers per
host (`--parallelism-per-worker 3`) with no container memory limit, so
the monitor in **every** container sees host-wide memory crossing 95% at
once and OOM-kills workers of whatever test happens to be running next
to it.

Since #67389 added a test target (2026-11-02), sharding places
`test_actor_retry_2` alongside `test_usage_stats`, and it has flaked in
22 of 24 postmerge runs of `:ray: core: python tests` (worker 0) since
then. It was 0 of 25 before. Every failure is the same: the raylet in
the `test_actor_retry_2` container kills its non-restartable `Counter`
actor during the `oomer` spike, with host memory at ~29.5 GB / 30.8 GB
while that container's processes use ~1.4 GB (e.g. postmerge builds
20851, 20854, 20859, 20873).

## Change

Split the test into two, both still in `test_usage_stats.py`:
- `test_worker_crash_increment_stats`: `crasher` only, asserts
`worker_crash_system_error == "2"` (unchanged).
- `test_worker_oom_increment_stats`: starts Ray with
`memory_usage_threshold=0`, so the memory monitor OOM-kills the running
`oomer` task without exhausting host memory, and asserts
`worker_crash_oom == "1"`.

The counter path under test is unchanged: memory monitor → kill with
`NODE_OUT_OF_MEMORY` → `GcsWorkerManager` increments `WORKER_CRASH_OOM`
→ caller gets `OutOfMemoryError`. Only how the threshold is crossed
differs. The two checks use separate clusters because with a 0
threshold, `crasher` could itself be OOM-killed before `exit(1)`. Only
the `oomer` worker is eligible for killing: the by-time policy only
considers workers that have held a lease, or idle workers using ≥1 GB.


AI assistance (Claude Code) was used for the investigation and the
change.

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

Signed-off-by: Kartica Modi <[email protected]>
Sparks0219 added a commit to Sparks0219/ray that referenced this pull request Nov 18, 2026
Resolves the conflict in NixlTensorTransport._cleanup_transfer with
ray-project#67389, which made it defer while the thread holds the cache lock and
serialized handle releases with the remote agent locks. The receive
pool blocks are carried through the deferred cleanup and freed after
the rest of it, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Joshua Lee <[email protected]>
Sparks0219 added a commit to Sparks0219/ray that referenced this pull request Nov 18, 2026
Two follow-ups to merging ray-project#67389 into the receive pool:

- When garbage collection cleans up a fetch request while
  _finish_transfers still polls its handle, the handle's release waits
  for the polling to end. Its pool blocks now wait with it, so the next
  receive can't take a block that the transfer may still write into.
- The pool's lock is not reentrant, and garbage collection can run a
  fetch request's cleanup on a thread that holds it, which would then
  wait for the pool's lock itself, or for the cache lock or an agent
  lock whose holder waits for the pool's lock. Every pool call now runs
  with those cleanups deferred, as the cache lock already did.

Also adds a test that a receive failing after it took its buffers from
the pool returns them without deregistering anything, and that the
pool still receives afterwards.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Joshua Lee <[email protected]>
Sparks0219 added a commit that referenced this pull request Nov 20, 2026
Follows up on #61573 with the receive side of the NIXL memory pool.

When the receiver has registered a pool with `register_nixl_memory_pool`
and passes no target buffers, `ray.get` reads the incoming tensors into
regions of the pool, which is registered with NIXL once, instead of
registering new buffers for every transfer. Once the transfer lands, the
tensors are copied out into ordinary tensors on the source's device
type, and the regions go straight back to the pool. The tensors you get
are independent of the pool, so the pool size bounds how much data can
be in flight at once, not how much received data you can hold. An
earlier version of this PR tied blocks to the returned tensors with
`weakref`, which broke when a view outlived the tensor, so it copies out
instead.

- `MemoryPoolManager.allocate_regions`, `copy_out_and_free` and
`free_blocks` make up the receive-side allocator. Regions start on
`_MAX_ALIGNMENT`, so the sender's packed layout decodes in place. The
pool now has a lock, since sends and receives use it from both the main
and `_ray_system` threads.
- A failed or abandoned receive gives its regions back only after its
transfer handle is released, including when that release waits for
`_finish_transfers` (#67389) to stop polling the handle.
- Every pool call runs with the cleanups that garbage collection
triggers deferred, as the cache lock already does, so a fetch request's
`__del__` can't deadlock on the pool's lock.
- An object with an empty tensor skips the receive pool: NIXL can't find
a zero-length descriptor inside a registered region
(`NIXL_ERR_NOT_FOUND`).
- With user target buffers the pool is bypassed, as before.

**Not a duplicate:** this is the receive-side follow-up to #61573.
Searching open PRs for the NIXL memory pool turns up #68142 (pool
statistics, which touches the same files but not the receive path) and
nothing else on the receive side.

**Tests** (4x T4, UCX with `UCX_TLS=^gdr_copy`, Ray nightly 2b3daa8
with this branch's `python/ray/experimental` and `python/ray/tests`
linked in):
- `pytest python/ray/tests/rdt/test_rdt_nixl.py
python/ray/tests/rdt/test_nixl_agent_lock.py
python/ray/tests/rdt/test_nixl_memory_pool.py`: 95 passed, 1 skipped
(`test_nixl_borrow_after_abort`, skipped on master).
- `pytest python/ray/tests/rdt/test_nixl_backend_selection.py
python/ray/tests/rdt/test_rdt_custom.py
python/ray/tests/rdt/test_rdt_gloo.py` (with the two unit files above):
101 passed, 1 skipped.
- Each new test fails with its fix reverted.

AI assistance (Claude Code) was used for this PR.

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

---------

Signed-off-by: Joshua Lee <[email protected]>
Co-authored-by: Claude Opus 5.5 <[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.

[RDT]: In-flight transfers race condition

2 participants