Skip to content

UCT/MM: Determine ep flush completion without peer memory access - #11682

Closed
bwestheimer wants to merge 15 commits into
openucx:masterfrom
bwestheimer:bwestheimer/mm-ep-flush-peer-check
Closed

bwestheimer wants to merge 15 commits into
openucx:masterfrom
bwestheimer:bwestheimer/mm-ep-flush-peer-check

Conversation

@bwestheimer

@bwestheimer bwestheimer commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

What

Change uct_mm_ep_flush to determine completion from local arbiter state
(ucs_arbiter_group_is_scheduled) rather than reading the peer's FIFO control
structure. Add four regression gtests that mprotect the peer fifo_ctl page
and verify no page fault occurs on any flush or purge path.

Why

Shared-memory sends in the MM transport write directly into the peer's receive
FIFO inside uct_mm_ep_am_common_send and complete synchronously before the
call returns. There is no outstanding send work after that point; the only
locally pending operations are those queued on the endpoint's pending arbiter
group. Remote FIFO occupancy is therefore a resource-availability signal, not
a completion signal, and flush should not depend on it.

The previous uct_mm_ep_flush read fifo_ctl->head and fifo_ctl->tail
from the peer's shared memory page regardless. Whether that read can fault
depends on the mm mapper's remote-mapping lifetime, which differs by backend:
POSIX and SysV segments are kernel-refcounted and remain valid for an
attached consumer even after the owning peer process exits, so this read is
safe for those mappers. XPMEM does not have that property: an XPMEM
attachment's validity is tied to the exporting process's address space and is
invalidated once that process tears down. This was root-caused as the SIGBUS
seen at MPI_Finalize in field runs of the ICON climate model.

Reproducer (no fault injection, forces mm EP wire-up + peer-segment attach to
every rank via an all-to-all one-sided window, frees it, then finalizes
immediately with no barrier, so a fast rank can be inside uct_mm_ep_flush
while a peer has already exited):

#include <mpi.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
    int rank, size, i, peer;
    const size_t win_bytes = 4096;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    for (int iter = 0; iter < 4; iter++) {
        void *base;
        MPI_Win win;
        char *sendbuf = malloc(win_bytes);
        char *recvbuf = malloc(win_bytes);
        memset(sendbuf, rank + iter, win_bytes);

        MPI_Win_allocate(win_bytes, 1, MPI_INFO_NULL, MPI_COMM_WORLD, &base, &win);
        MPI_Win_lock_all(0, win);
        for (i = 0; i < size; i++) {
            peer = (rank + 1 + i) % size;
            if (peer == rank) continue;
            MPI_Put(sendbuf, win_bytes, MPI_BYTE, peer, 0, win_bytes, MPI_BYTE, win);
            MPI_Win_flush(peer, win);
            MPI_Get(recvbuf, win_bytes, MPI_BYTE, peer, 0, win_bytes, MPI_BYTE, win);
            MPI_Win_flush(peer, win);
        }
        MPI_Win_unlock_all(win);
        MPI_Win_free(&win);
        free(sendbuf);
        free(recvbuf);
    }

    /* No barrier here on purpose: maximizes the teardown interleave. */
    MPI_Finalize();
    return 0;
}

Run forced to each mapper, oversubscribed, looped many times (a single run is
not guaranteed to hit the race):

UCX_TLS=xpmem,self mpirun -np 24 --oversubscribe \
  --mca opal_common_ucx_tls any --mca opal_common_ucx_devices any \
  --mca pml ucx --mca osc ucx ./repro

Result on this branch's base (before the fix), looped 200x:

  • xpmem,self: 200/200 SIGBUS in uct_mm_ep_flush
  • posix,self, sysv,self: 0/200

With the fix applied, xpmem,self is clean under the same loop.

There is a secondary correctness issue: when a flush request is dispatched
from the endpoint's own arbiter group, the group is transiently non-empty but
not scheduled. The previous code treated non-empty as "outstanding work" and
rescheduled the flush, deadlocking. Checking is_scheduled (not is_empty)
handles both the normal flush path and this in-flight case correctly. This
part of the fix is independent of mapper: it corrects a real state-modeling
bug in the common mm endpoint code.

How

Replace the uct_mm_ep_update_cached_tail block with a single
ucs_arbiter_group_is_scheduled check. The four gtests cover: (1) empty
arbiter returns UCS_OK without touching the protected page; (2) non-empty
arbiter returns UCS_ERR_NO_RESOURCE without touching the page; (3) pending
purge does not access the page; (4) a flush queued as a pending op eventually
completes and does not deadlock. These tests model "peer memory
inaccessible" generically (via mprotect) rather than reproducing the XPMEM
teardown mechanism specifically, so they protect the common-code correctness
property across all mm mappers, not just the one that can fault.

@bwestheimer
bwestheimer force-pushed the bwestheimer/mm-ep-flush-peer-check branch 2 times, most recently from 5efd64c to 2c7f0b2 Compare July 27, 2026 17:40
@bwestheimer bwestheimer changed the title UCT/MM: Report mm ep flush completion from local state to avoid peer faults UCT/MM: Determine ep flush completion without peer memory access Jul 27, 2026
MM sends write directly into the peer's receive FIFO inside
uct_mm_ep_am_common_send() and complete before it returns, so there is no
outstanding send work to check after that call. The previous flush read
fifo_ctl->head/tail from the peer's shared memory page; if the peer has
exited and the OS has reclaimed the mapping, that access faults with SIGBUS.

Use ucs_arbiter_group_is_scheduled() rather than is_empty(): when a flush
request is dispatched from ep->arb_group, the arbiter replaces the group head
with an unscheduled dummy, so the group is transiently nonempty but not
scheduled. Testing emptiness would reschedule the flush forever; testing
scheduled-ness lets it complete.

Adds regression gtests that mprotect the peer fifo_ctl page PROT_NONE and
assert no page fault on the empty-arbiter, nonempty-arbiter, purge, and
flush-dispatched-as-pending paths.
@bwestheimer
bwestheimer force-pushed the bwestheimer/mm-ep-flush-peer-check branch from 2c7f0b2 to 60470ec Compare July 27, 2026 17:49
@bwestheimer
bwestheimer marked this pull request as ready for review July 27, 2026 22:27
@bwestheimer
bwestheimer marked this pull request as draft July 27, 2026 22:31
@janjust
janjust requested review from gleon99 and yosefe July 29, 2026 14:39
@gleon99
gleon99 requested a review from shasson5 July 30, 2026 06:34
Comment on lines +542 to +543
if (ucs_arbiter_group_is_scheduled(&ep->arb_group)) {
return UCS_ERR_NO_RESOURCE;

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.

what if mm_iface will become async? that solution will cause flush to report a false UCS_OK
(FIFO not empty)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good point.

If MM sends ever became async, there'd need to be a completion counter alongside the arbiter check. The minimal version might look something like:

/* Add one new field to uct_mm_ep_t */
ucs_atomic_t inflight_sends;

/* In am_common_send, bracket the FIFO write */
ucs_atomic_add32(&ep->inflight_sends, 1);
/* ... write to FIFO, store fence ... */
ucs_atomic_add32(&ep->inflight_sends, -1);

/* Extend the flush check in uct_mm_ep_flush */
if (ucs_arbiter_group_is_scheduled(&ep->arb_group) ||
    ucs_atomic_load32(&ep->inflight_sends) != 0) {
    return UCS_ERR_NO_RESOURCE;
}

I haven't added it in here for synchronous sends because it would add two atomic ops to every send with no practical effect. It also locks in one particular tracking shape, and a future async MM design might want to go in a different direction. So I thought it made the most sense to allow any future implementation to design its own completion tracking, rather than inheriting a counter stub that may not end up being an appropriate fit.

I'd be happy to add a comment to uct_mm_ep_flush documenting the synchronous-completion assumption so that the reasoning is clear to future readers. Or I could add the requisite code as commented-out stubs for now if that would be preferable.

@shasson5

shasson5 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

@bwestheimer can you give more details of how you got this crash?
in general, what you describe should not happen on UCX as posix segments are protected by kernel refcount and are not released until both owner and consumer processes exit.

@bwestheimer

Copy link
Copy Markdown
Contributor Author

You're right about POSIX. I conflated two things in the PR body: the
xpmem-specific fault and the general correctness fix. I've updated the
description to separate them.

I also built a small reproducer and forced the mm mapper explicitly to
check: posix and sysv never fault, xpmem faults every time at the same
fifo_ctl->head read as the field trace. I've added it to the PR description
in place of the /dev/shm explanation.

The rest of the patch doesn't depend on which mapper can fault. The flush
predicate change (local arbiter-scheduled state instead of peer FIFO
occupancy) is correct for every mm mapper regardless, and the is_scheduled
vs is_empty fix is a separate self-dispatch deadlock that's also
mapper-independent.

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

need to update Authors file (see CI failure)

Comment thread test/gtest/uct/test_mm.cc Outdated
Comment on lines +276 to +287
UCS_TEST_SKIP_COND_P(test_uct_mm, flush_no_peer_access,
!check_caps(UCT_IFACE_FLAG_AM_SHORT)) {
uint64_t send_data = 0xdeadbeef;
ucs_status_t status;

do {
status = uct_ep_am_short(m_e1->ep(0), 0, 0xbeef, &send_data,
sizeof(send_data));
if (status == UCS_ERR_NO_RESOURCE) {
progress();
}
} while (status == UCS_ERR_NO_RESOURCE);

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.

please check if any existing code can be reused here, to avoid code duplication (in all tests)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good call. Pulled the fifo_ctl mprotect bracket and the FIFO-saturation loop
out into two helpers (mm_test_protect_fifo_ctl/mm_test_unprotect_fifo_ctl and
mm_test_saturate_fifo) and had the tests that needed them call those instead.
Checked the rest of test/gtest/uct for something already covering either
pattern first, nothing fit, so this is a local dedup rather than reuse of
existing infra. Pushed as a new commit.

@svc-ucx

svc-ucx commented Aug 25, 2026

Copy link
Copy Markdown

🤖 CI Triage Agent — UCX PR · commit 42f4da0e

TL;DR: The only failing step is the "AUTHORS file check" — the PR author (Bryce Westheimer) is a first-time contributor and is not listed in the AUTHORS file, so git diff --exit-code after contrib/authors_update.sh returned 1. Fix by running ./contrib/authors_update.sh <base>..HEAD and committing the updated AUTHORS file.

Full analysis

Summary: Azure Pipelines job "AUTHORS file update check" failed at the AUTHORS file check bash step with ##[error]Bash exited with code '1'; no build or test failure occurred.

Root cause: The check runs ./contrib/authors_update.sh 39b34aec..ae6b6d77 and then git diff --exit-code. The script found a commit author not present in AUTHORS and appended Bryce Westheimer <bwestheimer@nvidia.com> (log line ++ Bryce Westheimer <bwestheimer@nvidia.com>), producing a non-empty diff:

+++ b/AUTHORS
@@ -20,6 +20,7 @@
 Brad Benton <bradford.benton@gmail.com>
+Bryce Westheimer <bwestheimer@nvidia.com>

git diff --exit-code exits 1 when the working tree differs, which fails the step. This is the intended policy gate for new contributors, not a code defect — the current AUTHORS (lines 22–23) jumps straight from "Brad Benton" to "Changcheng Liu", confirming the entry is genuinely missing.

Implicated commit: [REDACTED:Hex High Entropy String] (Bryce Westheimer bwestheimer@nvidia.com) — PR #11682, branch bwestheimer/mm-ep-flush-peer-check. Not a regression; the commit simply introduces a new author.

File: AUTHORS:22 (insertion point after Brad Benton); check logic at contrib/authors_update.sh:35-45

Suggested fix: On the PR branch, add the author entry and amend/append a commit:

./contrib/authors_update.sh origin/master..HEAD
git add AUTHORS && git commit -m "AUTHORS: add Bryce Westheimer"
git push

Alternatively add the single line Bryce Westheimer <bwestheimer@nvidia.com> to AUTHORS between Brad Benton <bradford.benton@gmail.com> and Changcheng Liu <jerrliu@nvidia.com> (the file must stay LC_COLLATE=C sorted, as enforced by contrib/authors_update.sh:43). Note the commit email must match the one in AUTHORS, or the grep in line 35 will re-add it. Once this lands, re-run the pipeline; no other stage reported an error, so the rest of the PR is untested by this failure and should be re-validated.

Related: PR #11682 (this PR); check implemented by contrib/authors_update.sh (added 2024)

🛡️ This comment had 1 potential secret(s) redacted (Hex High Entropy String). See request_id 45d5214e-e6a1-45c1-a228-a54d4cfbb197 in the triage console for the audit trail.

Factor the fifo_ctl mprotect bracket and the FIFO-saturation loop shared
by the mm flush/purge regression tests into three helpers
(mm_test_protect_fifo_ctl, mm_test_unprotect_fifo_ctl, mm_test_saturate_fifo)
instead of repeating them in each test.
…heimer/ucx into bwestheimer/mm-ep-flush-peer-check
@bwestheimer

Copy link
Copy Markdown
Contributor Author

Added, thanks.

@svc-nvidia-pr-review

Copy link
Copy Markdown

🤖 Starting review — findings will be posted here when done.

Comment thread test/gtest/uct/test_mm.cc Outdated
EXPECT_TRUE(ctx.done);
EXPECT_TRUE(ucs_arbiter_group_is_empty(&ep->arb_group));

if (!ucs_arbiter_group_is_empty(&ep->arb_group)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor: the if (!ucs_arbiter_group_is_empty(...)) { purge } fallback is unreachable given the immediately preceding EXPECT_TRUE(ucs_arbiter_group_is_empty(...)); it is dead cleanup code and can be dropped.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch on the redundant guard, but the purge itself needs to stay: if the
10s deadline above is hit, ctx (stack-local) still has a pending request
enqueued on the arbiter pointing into that frame, and it needs to be purged
here while ctx is still alive, not left for the destructor. Dropped the if
guard, kept the purge unconditional.

…tant

The trailing purge was guarded by an is_empty() check that made it look
unreachable, but it isn't: if the flush's pending callback never fires
before the deadline, ctx (a stack-local struct) is still enqueued on the
endpoint's arbiter group when the test function returns, and the
destructor's purge at entity teardown would then walk a pointer into
that dead stack frame. Purge unconditionally instead, while ctx is still
alive.

Also use the existing DEFAULT_TIMEOUT_SEC constant instead of a bare 10.0
literal, matching test_dc.cc and test_p2p_am.cc.
@svc-nvidia-pr-review

Copy link
Copy Markdown

🤖 Starting review — findings will be posted here when done.

@@ -539,15 +539,8 @@ ucs_status_t uct_mm_ep_flush(uct_ep_h tl_ep, unsigned flags,
{

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Correctness of the fix: The old uct_mm_ep_flush dereferenced peer shared memory (ep->fifo_ctl->tail via uct_mm_ep_update_cached_tail, and ep->fifo_ctl->head via uct_mm_ep_has_tx_resources). If the peer had exited/detached, these reads could fault. MM sends complete synchronously on write into the remote FIFO, so the only thing flush must wait for is locally-queued pending operations — precisely what the arbiter group tracks. Replacing the peer-memory checks with ucs_arbiter_group_is_scheduled(&ep->arb_group) is the right, minimal fix and removes the peer dependency.

@@ -539,15 +539,8 @@ ucs_status_t uct_mm_ep_flush(uct_ep_h tl_ep, unsigned flags,
{
uct_mm_ep_t *ep = ucs_derived_of(tl_ep, uct_mm_ep_t);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

is_scheduled vs is_empty: For MM, whenever the group is non-empty it is also scheduled (the arb_elem placeholder and pending adds both schedule the group). During dispatch, is_scheduled correctly reads through the dummy head which stays on the arbiter list, so a flush issued from a pending callback keeps returning UCS_ERR_NO_RESOURCE until the queue drains. The choice is sound and matches the actual dispatch state.

@@ -539,15 +539,8 @@ ucs_status_t uct_mm_ep_flush(uct_ep_h tl_ep, unsigned flags,
{
uct_mm_ep_t *ep = ucs_derived_of(tl_ep, uct_mm_ep_t);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Behavior for 'FIFO full but group empty': New code returns UCS_OK here, whereas the old code returned NO_RESOURCE. This is correct — those sends already landed in the FIFO, so nothing is pending locally; the old behavior was overly conservative.

Comment thread test/gtest/uct/test_mm.cc
@@ -270,4 +273,164 @@ UCS_TEST_SKIP_COND_P(test_uct_mm, reg,
ASSERT_UCS_OK(status);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Tests validate the no-peer-access property directly via mprotect(PROT_NONE) on the fifo_ctl page around the flush call, plus the empty/pending/purge/dispatch-reentrancy paths. Ordering of protect/flush/unprotect vs. later drain (which does touch peer memory) is correct. The unconditional purge with the explanatory comment in flush_pending_dispatch_completes correctly guards against a stack-allocated request still being enqueued on deadline.

Comment thread AUTHORS
@@ -20,6 +20,7 @@ BatshevaBlack <bblack@nvidia.com>
Bin Lei <binl@mellanox.com>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

AUTHORS: 'Bryce M. Westheimer' is inserted in correct alphabetical order (after 'Brad Benton', before 'Changcheng Liu').

@svc-nvidia-pr-review

Copy link
Copy Markdown

Residual note (not blocking): the tests exercise the posix/sysv MM transports under gtest; no additional CI wiring is needed since these run in existing UCT gtest jobs.

@bwestheimer
bwestheimer marked this pull request as ready for review September 2, 2026 21:12
@svc-ucx

svc-ucx commented Sep 2, 2026

Copy link
Copy Markdown

🤖 CI Triage Agent — UCX PR (Tests roce on worker 0) · commit 356ca5b0

TL;DR: The roce job wasn't slow — ucx_info -epw -u t hung/spun for ~96 min until the agent was killed; the PR's new uct_mm_ep_flush() returns UCS_ERR_NO_RESOURCE based on "arbiter group is scheduled" while uct_mm_ep_pending_add() still returns UCS_ERR_BUSY based on "FIFO has room", so UCP's flush loop can ping‑pong forever. Make the two conditions consistent (e.g. only return UCS_ERR_BUSY from pending_add when the arb group is empty, or only return NO_RESOURCE from flush when there are no TX resources).

Full analysis

Summary: Azure job "roce on worker 0" (build 134000) was cancelled by the agent after ./src/tools/info/ucx_info -epw -u t (test test_unused_env_var in contrib/test_jenkins.sh) never returned.

Root cause: Evidence of a hang, not a time-limit problem: the last application line is at 2026-09-02T21:40:30.1960428Z (+ ./src/tools/info/ucx_info -epw -u t), and the next line is 2026-09-02T23:17:02 ##[error]The agent has received a shutdown signal — a single ~96‑minute gap with zero output, and the cleanup step had to Terminate orphan process: pid (2342619) (ucx_info). So ucx_info was stuck/spinning while creating + closing the self endpoint (which flushes the shm/mm lane).

This PR changes uct_mm_ep_flush() to decide completion without touching peer memory:

  • src/uct/sm/mm/base/mm_ep.c:537-549 — flush now returns UCS_ERR_NO_RESOURCE iff ucs_arbiter_group_is_scheduled(&ep->arb_group); it no longer refreshes cached_tail / checks uct_mm_ep_has_tx_resources().
  • src/uct/sm/mm/base/mm_ep.c:441-445 — uct_mm_ep_pending_add() still returns UCS_ERR_BUSY when uct_mm_ep_has_tx_resources(ep) is true, and even asserts ucs_arbiter_group_is_empty(&ep->arb_group) there — i.e. it assumes the old invariant "TX resources available ⇒ group empty".

Those two conditions are no longer mutually exclusive. A group can be scheduled (placeholder arb_elem and/or real pending reqs, e.g. after uct_mm_ep_process_pending() refreshed cached_tail and returned RESCHED_GROUP) while the FIFO does have room. In that state UCP's flush loop spins:

src/ucp/rma/flush.c:109-154 — while ((next_lanes = ep_live_lanes & ~started_lanes) != 0): uct_ep_flush() → UCS_ERR_NO_RESOURCE → uct_ep_pending_add() → UCS_ERR_BUSY → the else if (status != UCS_ERR_BUSY) branch is skipped, started_lanes is not updated and there is no break, so the same lane is retried forever. This is a 100%-CPU livelock with no log output — exactly what the log shows (release build, -O3, so the pending_add assert is compiled out and the failure is silent).

Implicated commit: 60470ec7 — "UCT/MM: Determine ep flush completion without peer memory access", Bryce Westheimer (PR #11682, branch head 356ca5b0)

File: src/uct/sm/mm/base/mm_ep.c:537-549 (flush) vs src/uct/sm/mm/base/mm_ep.c:441-445 (pending_add); livelock manifests in src/ucp/rma/flush.c:109-154

Suggested fix: Keep the flush and pending_add conditions in sync so that NO_RESOURCE from flush always implies pending_add will succeed:

/* mm_ep.c: uct_mm_ep_pending_add() */
if (uct_mm_ep_has_tx_resources(ep) &&
    ucs_arbiter_group_is_empty(&ep->arb_group)) {
    return UCS_ER

</details>

<!-- triage-agent request_id: 2d7948cd-0ea2-4e29-936f-7d80567b4048 -->
<!-- triage-agent gha_run_id: azure:134000 -->
<!-- triage-agent-bot -->

@shasson5

shasson5 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

I mean something like:

mm_iface_t {
...
uint32_t num_attached;
};

and then in mm_iface_cleanup():
if (num_attached > 0) {
// wait
}

@bwestheimer

Copy link
Copy Markdown
Contributor Author

It would cover clean shutdown, but the owner isn't told about attaches today, so
num_attached is a new protocol rather than a field.

The bigger problem is where to wait. uct_iface_close() can't report a timeout and
nothing is driving progress by then, so an abort or SIGKILL turns a crash into a
hang in MPI_Finalize. mm_iface.c:225-236 already rules out peer liveness checks
for these mappers for the same reason.

Flush shouldn't be keying off FIFO occupancy either way.

If you want the teardown sync, I'd do it over the iface signal socket rather than
a count in shared memory, one connected socket per consumer so the owner gets a
HUP if one dies. Happy to take that separately.

The struct is only cache line aligned and head and tail sit on separate cache
lines, so it can cross a page boundary and mprotect of a single page can leave
tail accessible. Protect every page it spans.
@svc-nvidia-pr-review

Copy link
Copy Markdown

🤖 Starting review — findings will be posted here when done.

Comment thread src/uct/sm/mm/base/mm_ep.c Outdated
/* check if resources became available */
if (uct_mm_ep_has_tx_resources(ep)) {
ucs_assert(ucs_arbiter_group_is_empty(&ep->arb_group));
/* BUSY only when flush reports completion, otherwise its caller would spin */

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor: pls check the local group state first, so we don't read the remote FIFO head when there is anything queued (the common case after a failed send).

Suggested change
/* BUSY only when flush reports completion, otherwise its caller would spin */
/* Report BUSY only in a state where uct_mm_ep_flush() reports completion,
* otherwise the flush caller would spin between flush() and pending_add() */
if (ucs_arbiter_group_is_empty(&ep->arb_group) &&
uct_mm_ep_has_tx_resources(ep)) {

Comment thread src/uct/sm/mm/base/mm_ep.c Outdated
return UCS_ERR_NO_RESOURCE;
}
}
/* Must not report NO_RESOURCE where uct_mm_ep_pending_add() reports BUSY */

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

pls also document why this is is_scheduled() and not is_empty() - the group is not scheduled while its element is being dispatched, and that is what makes a flush from a pending callback (ucp_ep_flush_progress_pending) complete instead of being rescheduled forever.

Suggested change
/* Must not report NO_RESOURCE where uct_mm_ep_pending_add() reports BUSY */
/* Must not report NO_RESOURCE where uct_mm_ep_pending_add() reports BUSY.
* Note a group is not scheduled while its element is being dispatched, so a
* flush issued from a pending callback reports completion. */

Comment thread test/gtest/uct/test_mm.cc Outdated
ctx.done = 0;
ASSERT_UCS_OK(uct_ep_pending_add(m_e1->ep(0), &ctx.req, 0));

ucs_time_t deadline = ucs_get_time() +

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor: can we use the existing helper instead of an open-coded deadline loop?

Suggested change
ucs_time_t deadline = ucs_get_time() +
wait_for_flag(&ctx.done);

Comment thread test/gtest/uct/test_mm.cc Outdated
ASSERT_TRUE(ucs_arbiter_group_is_scheduled(&ep->arb_group));
ASSERT_EQ(UCS_ERR_NO_RESOURCE, uct_ep_flush(m_e1->ep(0), 0, NULL));

mm_flush_pending_ctx_t ctx;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor: pls define ctx and purged at the top of the func, as in docs/CodeStyle.md ("Variable definition").

@svc-nvidia-pr-review

Copy link
Copy Markdown

Residual coverage note: The three no_peer_access tests detect a regression by faulting on the PROT_NONE page, so with UCX_HANDLE_ERRORS=freeze (test/gtest/Makefile.am) a future regression shows up as a frozen process killed by the gtest watchdog rather than a clean assertion failure. Not blocking, just something to be aware of when triaging.

uct_mm_ep_has_tx_resources() reads the peer FIFO head, so test the local
arbiter group first and skip that read when work is already queued, which is
the common case after a failed send. Both operands are side effect free, so
the result is unchanged.

Also record why the flush predicate uses is_scheduled() rather than is_empty(),
and in the pending dispatch test use wait_for_flag() and define the variables
at the top of the function.
@svc-nvidia-pr-review

Copy link
Copy Markdown

🤖 Starting review — findings will be posted here when done.

/* Must not report NO_RESOURCE where uct_mm_ep_pending_add() reports BUSY.
* A group is not scheduled while its element is being dispatched, so a
* flush issued from a pending callback reports completion. */
if (ucs_arbiter_group_is_scheduled(&ep->arb_group)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

maybe keep an inline fast path here — ucs_arbiter_group_is_scheduled() is an out-of-line libucs call, and uct_ep_flush() is invoked per lane on every UCP flush, where the group is normally empty (same pattern as the ucs_arbiter_group_schedule() inline wrapper):

Suggested change
if (ucs_arbiter_group_is_scheduled(&ep->arb_group)) {
if (!ucs_arbiter_group_is_empty(&ep->arb_group) &&
ucs_arbiter_group_is_scheduled(&ep->arb_group)) {
return UCS_ERR_NO_RESOURCE;
}

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 probably ignore this comment

Comment thread test/gtest/uct/test_mm.cc
* pages. Must be restored before the ep is destroyed. */
static void mm_test_fifo_ctl_prot(uct_mm_ep_t *ep, int prot)
{
size_t pgsz = ucs_get_page_size();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor: can we use the existing alignment helpers (already available via mm_iface.h) instead of the manual masks and the last - start + pgsz expression?

Suggested change
size_t pgsz = ucs_get_page_size();
size_t pgsz = ucs_get_page_size();
uintptr_t start = ucs_align_down_pow2((uintptr_t)ep->fifo_ctl, pgsz);
uintptr_t end = ucs_align_up_pow2((uintptr_t)ep->fifo_ctl +
sizeof(*ep->fifo_ctl), pgsz);
EXPECT_EQ(0, mprotect((void*)start, end - start, prot));

Comment thread test/gtest/uct/test_mm.cc Outdated
uint64_t send_data = 0xdeadbeef;
ucs_status_t status;

do {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor: if this retry path ever runs, m_e2 has no handler for am_id 0, so progress() reaches the stub AM handler whose ucs_warn() fails the test. The FIFO is empty at this point, so a single ASSERT_UCS_OK() send is enough (or install mm_test_am_noop like mm_test_saturate_fifo does).

Comment thread test/gtest/uct/test_mm.cc

uct_mm_ep_t *ep = ucs_derived_of(m_e1->ep(0), uct_mm_ep_t);

mm_test_fifo_ctl_prot(ep, PROT_NONE);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

UCT_INSTANTIATE_MM_TEST_CASE also instantiates this for xpmem, where ep->fifo_ctl points into an xpmem_attach() region rather than a shm file mapping — did you check mprotect() works there? If it can fail, EXPECT_EQ(0, mprotect(...)) will fail the test on hosts with xpmem loaded.

Use ucs_align_down_pow2()/ucs_align_up_pow2() for the protected range instead
of open coded masks.

The FIFO is empty when flush_no_peer_access starts, so the first send always
has room and the retry loop never ran. It would have failed the test if it
did, since m_e2 has no handler for am_id 0 and the stub handler warns.

uct_mm_ep_flush() ignores UCT_FLUSH_FLAG_CANCEL, so pass 0 rather than imply
cancel semantics that do not exist.

Record what flush_pending_dispatch_completes pins, which is the is_scheduled()
rather than is_empty() choice in the flush predicate.
@svc-nvidia-pr-review

Copy link
Copy Markdown

🤖 Starting review — findings will be posted here when done.

Comment thread test/gtest/uct/test_mm.cc Outdated

UCS_TEST_SKIP_COND_P(test_uct_mm, flush_no_peer_access_pending,
!check_caps(UCT_IFACE_FLAG_AM_SHORT)) {
ucs_status_t status;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor: pls put initialized variables first, per docs/CodeStyle.md variable definition rule (same in pending_purge_no_peer_access and flush_pending_add_consistency).

Suggested change
ucs_status_t status;
uct_mm_ep_t *ep = ucs_derived_of(m_e1->ep(0), uct_mm_ep_t);
ucs_status_t status;

Follow the variable definition rule in docs/CodeStyle.md.
@svc-nvidia-pr-review

Copy link
Copy Markdown

🤖 Starting review — findings will be posted here when done.

Comment thread test/gtest/uct/test_mm.cc
ucs_status_t status;

/* the FIFO is empty, so a single send always has room */
ASSERT_UCS_OK(uct_ep_am_short(m_e1->ep(0), 0, 0xbeef, &send_data,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor: pls install an AM handler for id 0 here, otherwise the un-consumed message reaches uct_iface_stub_am_handler() if anything ever progresses m_e2, and its ucs_warn fails the test via the warning counter in TearDownProxy().

Suggested change
ASSERT_UCS_OK(uct_ep_am_short(m_e1->ep(0), 0, 0xbeef, &send_data,
uct_iface_set_am_handler(m_e2->iface(), 0, mm_test_am_noop, NULL, 0);
/* the FIFO is empty, so a single send always has room */
ASSERT_UCS_OK(uct_ep_am_short(m_e1->ep(0), 0, 0xbeef, &send_data,
sizeof(send_data)));

Comment thread test/gtest/uct/test_mm.cc
/* Protect ep's peer fifo_ctl to assert the tested code path never dereferences
* it. head and tail sit on separate cache lines, so the struct may span two
* pages. Must be restored before the ep is destroyed. */
static void mm_test_fifo_ctl_prot(uct_mm_ep_t *ep, int prot)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

did you check these tests with xpmem? UCT_TEST_MM_TLS includes it, and there ep->fifo_ctl points into an xpmem_attach() mapping rather than a plain mmap/shmat one, so mprotect() may not behave the same; if it fails, EXPECT_EQ only records a failure and the guard silently protects nothing.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Checked. Built with --with-xpmem against the hpc/xpmem module and ran
xpmem/test_uct_mm.*: 8/8 pass over 5 runs, so mprotect() on the attachment
works.

It is also not silently protecting nothing. Reverting the uct_mm_ep_flush hunk
makes xpmem/test_uct_mm.flush_no_peer_access dump core at uct_mm_ep_flush+0x8,
the same as sysv, so fifo_ctl really is inside the region being protected.

Comment thread test/gtest/uct/test_mm.cc Outdated
mm_test_fifo_ctl_prot(ep, PROT_READ | PROT_WRITE);
EXPECT_EQ(UCS_ERR_NO_RESOURCE, status);

while (!ucs_arbiter_group_is_empty(&ep->arb_group)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor: this loop has no deadline, so a regression here hangs the test until the watchdog kills it. pls use wait_for_cond() (10s default) and then assert the group is empty.

@svc-nvidia-pr-review

Copy link
Copy Markdown

Residual coverage note: uct_flush_test::test_flush_am_pending (test/gtest/uct/test_flush.cc:445-465) already exercises the same flush/pending_add contract for all TLs, but its UCS_ERR_BUSY → continue retry loop would have spun forever on the old mm code instead of failing cleanly; the new mm-specific test is deterministic, which is the better regression guard.

Install an AM handler before the send in flush_no_peer_access, otherwise the
message is left for uct_iface_stub_am_handler() and its warning fails the test
through the teardown warning count.

Give the pending drain loop a deadline, so a regression reports a failure
rather than running until the watchdog fires.
@svc-nvidia-pr-review

Copy link
Copy Markdown

🤖 Starting review — findings will be posted here when done.

Comment thread test/gtest/uct/test_mm.cc
uct_ep_pending_purge(m_e1->ep(0), mm_test_purge_cb, &purged);
}

UCT_INSTANTIATE_MM_TEST_CASE(test_uct_mm)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

these tests also run for xpmem, where ep->fifo_ctl points into an xpmem_attach() region rather than a plain shm mapping - is mprotect() guaranteed to work there? if it can fail, this EXPECT will fail the 3 no_peer_access tests on hosts with the xpmem module loaded.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Tested, it works. xpmem/test_uct_mm.* passes 8/8 over 5 runs against a real
xpmem build, and reverting the flush change cores at uct_mm_ep_flush+0x8 under
xpmem as well, so the region really is being protected.

@yosefe yosefe left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

the right order in MPI_Finalize should be:

  1. all endpoints doing communication
  2. ucp_ep_flush - optional
  3. ucp_ep_destroy
  4. modex_barrier
  5. ucp_worker_destroy

In particular, all communication operations (including flush) and ep_destroy must be done before modex barrier at finalize. and worker_destroy is after the modex.
this guarantees no access to released shared FIFO .

So, the fix may need to be done in OpenMPI

@shasson5

Copy link
Copy Markdown
Contributor

@bwestheimer please ack and close this PR.

@bwestheimer

Copy link
Copy Markdown
Contributor Author

@yosefe and @shasson5 Thank you for the suggestion. I'll have that fix implemented and pushed to OMPI. I'm leaving this PR as draft for later follow-up because I think the fixes have broader scope that may still be useful.

/* check if resources became available */
if (uct_mm_ep_has_tx_resources(ep)) {
ucs_assert(ucs_arbiter_group_is_empty(&ep->arb_group));
/* BUSY only when flush reports completion, otherwise its caller would spin.

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.

maybe remove BUSY... would spin, as we can mention below (see comment).

maybe also ... send with non-empty arbiter would cause re-ordering ... or something that says that we can only send when ahead of line.

return UCS_ERR_NO_RESOURCE;
}
}
/* Must not report NO_RESOURCE where uct_mm_ep_pending_add() reports BUSY.

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.

maybe more clean to document all three states here, not just the dispatch one (can be on top of function and remove that comment)?

  • empty -> is_empty 1, is_scheduled 0 -> OK
  • flush is head of line -> 0, 0 -> OK
  • queued on arbiter -> 0, 1 -> NO_RESOURCE
Suggested change
/* Must not report NO_RESOURCE where uct_mm_ep_pending_add() reports BUSY.
/* Report completion when nothing is queued ahead of this request:
* group state is_empty is_scheduled flush
* --------------------- -------- ------------ -----------
* empty 1 0 OK
* flush is head of line 0 0 OK
* queued 0 1 NO_RESOURCE
* Like all requests, must not report NO_RESOURCE where
* uct_mm_ep_pending_add() reports BUSY.
*/
if (ucs_arbiter_group_is_scheduled(&ep->arb_group)) {

/* Must not report NO_RESOURCE where uct_mm_ep_pending_add() reports BUSY.
* A group is not scheduled while its element is being dispatched, so a
* flush issued from a pending callback reports completion. */
if (ucs_arbiter_group_is_scheduled(&ep->arb_group)) {

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 probably ignore this comment

* The group is tested first to avoid reading the peer FIFO head when work
* is already queued. */
if (ucs_arbiter_group_is_empty(&ep->arb_group) &&
uct_mm_ep_has_tx_resources(ep)) {

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 comment above has_tx_resources() that a flush called on pending already made sure group is not empty in mm_flush(). maybe something or better:

/* Only reached for non-flush, mm_flush() confirmed non-empty group */

Comment thread test/gtest/uct/test_mm.cc
ASSERT_EQ(UCS_ERR_NO_RESOURCE, status);
}

UCS_TEST_SKIP_COND_P(test_uct_mm, flush_no_peer_access,

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.

Seems this also fixes an out-of-order send case, can we mention it in the description?
Can we try to add test for the order too, description below:

On BUSY the caller retries uct_ep_am_short() directly, which skips the anti-reorder check in uct_mm_ep_am_common_send() since the FIFO has room.

The state needs a queued request that declines during dispatch, e.g. ucp_ep_flush_progress() blocked on another lane or ucp_proto_reconfig_select_progress() - uct_mm_ep_process_pending() already refreshed cached_tail, so the FIFO has room while the group stays non-empty.

flush_pending_add_consistency already builds the state, it only checks the pending_add() return:

  • queue req A whose cb declines once, then sends header 1
  • drain m_e2, progress m_e1 once
  • offer req B via uct_ep_pending_add(), on BUSY send header 2 directly
  • expect the receiver to see 1 then 2

without the fix B goes out first.

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.

UCT repro below but no UCP repro so far.

Requires a queued request whose pending callback returns UCS_ERR_NO_RESOURCE for a reason unrelated to the mm lane's own resources. That is what first.blocked simulates.

For instance UCP multi-lane protocol callback returns NO_RESOURCE when a different lane is exhausted, but it is not something a shm-only UCP gtest produces deterministically.

With the pending_add fix reverted, this fails, meaning the request added second overtook the one already queued.

/* AM id used by the ordering test, distinct from the one saturating the FIFO */
#define MM_TEST_AM_ID_ORDER 1

typedef struct {
    uct_pending_req_t req;
    uct_ep_h          ep;
    uint64_t          seq;
    int               blocked;
} mm_order_ctx_t;

static ucs_status_t mm_test_am_record(void *arg, void *data, size_t length,
                                      unsigned flags)
{
    static_cast<std::vector<uint64_t>*>(arg)->push_back(*(uint64_t*)data);
    return UCS_OK;
}

/* Sends ctx->seq once unblocked. While blocked the request stays queued and
 * keeps the group scheduled, which is the state pending_add must not treat as
 * "resources available". */
static ucs_status_t mm_test_order_pending_cb(uct_pending_req_t *self)
{
    mm_order_ctx_t *ctx = ucs_container_of(self, mm_order_ctx_t, req);

    if (ctx->blocked) {
        return UCS_ERR_NO_RESOURCE;
    }

    return uct_ep_am_short(ctx->ep, MM_TEST_AM_ID_ORDER, ctx->seq, &ctx->seq,
                           sizeof(ctx->seq));
}

/* uct_mm_ep_pending_add() must not report BUSY while the arbiter group already
 * holds requests: BUSY tells the caller to send immediately, so the new message
 * would overtake the queued ones. */
UCS_TEST_SKIP_COND_P(test_uct_mm, pending_add_preserves_order,
                     !check_caps(UCT_IFACE_FLAG_AM_SHORT)) {
    uct_mm_ep_t *ep = ucs_derived_of(m_e1->ep(0), uct_mm_ep_t);
    unsigned purged = 0;
    std::vector<uint64_t> received;
    mm_order_ctx_t first, second;
    ucs_status_t status;

    mm_test_saturate_fifo(m_e1->ep(0), m_e2->iface());
    uct_iface_set_am_handler(m_e2->iface(), MM_TEST_AM_ID_ORDER,
                             mm_test_am_record, &received, 0);

    first.req.func = mm_test_order_pending_cb;
    first.ep       = m_e1->ep(0);
    first.seq      = 1;
    first.blocked  = 1;
    ASSERT_UCS_OK(uct_ep_pending_add(m_e1->ep(0), &first.req, 0));

    /* free the remote FIFO, then dispatch once so the cached tail is refreshed
     * while the first request stays queued and keeps the group scheduled */
    while (m_e2->progress()) {
    }
    m_e1->progress();
    ASSERT_TRUE(ucs_arbiter_group_is_scheduled(&ep->arb_group));

    second.req.func = mm_test_order_pending_cb;
    second.ep       = m_e1->ep(0);
    second.seq      = 2;
    second.blocked  = 0;

    /* a caller told BUSY is expected to send right away, ahead of 'first' */
    status = uct_ep_pending_add(m_e1->ep(0), &second.req, 0);
    if (status == UCS_ERR_BUSY) {
        ASSERT_UCS_OK(uct_ep_am_short(m_e1->ep(0), MM_TEST_AM_ID_ORDER,
                                      second.seq, &second.seq,
                                      sizeof(second.seq)));
    } else {
        ASSERT_UCS_OK(status);
    }

    first.blocked = 0;
    wait_for_cond([&received]() { return received.size() == 2; },
                  [this]() { progress(); });

    /* purge before the contexts go out of scope, in case the wait timed out */
    uct_ep_pending_purge(m_e1->ep(0), mm_test_purge_cb, &purged);

    ASSERT_EQ(2u, received.size());
    EXPECT_EQ(first.seq, received[0]);
    EXPECT_EQ(second.seq, received[1]);
}

@shasson5

Copy link
Copy Markdown
Contributor

@bwestheimer can we close?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants