Skip to content

fix(ubshm): keep the UBRing poller off a released ring - #3780

Open
wwbmmm wants to merge 5 commits into
apache:masterfrom
wwbmmm:oncall/req-20261121-025731-5
Open

wwbmmm wants to merge 5 commits into
apache:masterfrom
wwbmmm:oncall/req-20261121-025731-5

Conversation

@wwbmmm

@wwbmmm wwbmmm commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Issue Number: N/A

Problem Summary:

The UBRing poller dereferences ep->_ub_ring in PollIn(), but UBShmEndpoint::Reset() destroyed that ring as soon as it had enqueued a fire-and-forget REMOVE op, without waiting for the poller to stop using it. A poller that was inside PollIn() for the same endpoint then read the released UBRing and its shared memory. In addition, PollerRegisterEvent() picked the poller group with bthread_self_tag() on every call, so a MOD/REMOVE issued from a different bthread than the ADD could be delivered to another group, leaving the socket id in the first poller's set forever. IsWritable() also dereferenced _ub_ring unconditionally, so a concurrent reset made it dereference a null (or stale) pointer.

What is changed and the side effects?

Changed:

  • PollerRegisterEvent() records the poller that serves _poller_sid when the event is added and reuses it for every later ADD/MOD/REMOVE, so an endpoint is always added to and removed from the same op queue regardless of the bthread tag.
  • The synthetic poller socket no longer stores the UBShmEndpoint as its SocketUser. It stores a small PollerUser with the id of the owning Socket; the poller resolves the endpoint through Socket::Address() and keeps that Socket referenced while polling, so the endpoint and its transport cannot be released under the poller.
  • The ring is reference counted: AcquireRing()/ReleaseRing() mark it in use (poller, sender, handshake), DeallocateResources() takes it out of the endpoint and marks it closed, and the last user destroys it. The trx is therefore closed only when nobody uses the ring any more; when the poller is the last user, the close (which may wait for the peer to acknowledge) is moved to a helper bthread so polling is never blocked on it. When no user is in flight the ring is closed inline, as before.
  • PollIn()/PollOut() receive the ring that the caller acquired instead of following ep->_ub_ring, and IsWritable()/CutFromIOBufList() borrow the ring the same way, so they never observe a null or replaced pointer and report "not writable"/EPIPE once the endpoint is released.
  • The handshake's UbrMapRemoteShm()/UbrUnlinkLocalShm() calls use the same acquire/release path.

Side effects:

  • Performance effects: the poller takes one additional reference count per poll of an endpoint (a pair of atomics on a cacheline that only the teardown path writes); the number of Socket::Address() calls per poll is the same as before, since PollIn() used to resolve the endpoint's socket itself.
  • Breaking backward compatibility: none. UBShmEndpoint::IsWritable() is no longer const (it now borrows the ring); it is internal to the ubshm transport.

Check List:

  • Please make sure your changes are compilable.
    • cmake -B build -DBUILD_UNIT_TESTS=ON -DDOWNLOAD_GTEST=OFF -DBRPC_SYSTEM_GTEST_SOURCE_DIR=/usr/src/googletest -DWITH_UBRING=ON + make -j6 brpc_ubring_unittest brpc-static : OK
    • default configuration (UBRING off): brpc_ubring_unittest builds and the disabled-path test passes.
  • Tests:
    • make -j6 brpc_ubring_unittest && test/brpc_ubring_unittest: 36/36 pass (also 36/36 with -DWITH_ASAN=ON, no ASAN report; the only leak reported is the pre-existing g_ubring_resource_mutex from GlobalInitialize()).
    • New tests: ring_lifetime_is_bounded_by_its_users (a ring in use is not handed out nor destroyed by Reset(), and its trx is released only after the last user returns it), poller_of_add_serves_later_operations (REMOVE reaches the poller recorded at ADD even when it is not the poller derived from the current bthread tag; Reset() forgets the registration), and poller_survives_endpoint_teardown (a bthread churns create/poll/reset/destroy of endpoints while the UBPolling bthread polls them, waiting for each trx to come back).
    • Not covered by the container: there is no UB hardware/UDK here, so UBRing runs on the built-in IPC shared-memory backend. An end-to-end reproduction with a real ubring session (a client that drops the TCP fd and stops acknowledging the close) still has to be checked manually on UB hardware; the unit tests exercise the same poller/teardown paths with real UBRing/trx objects.

🤖 This PR was automatically created by brpc-oncall

PollIn() dereferences ep->_ub_ring in the polling bthread while Reset()
frees the ring right after enqueueing a fire-and-forget REMOVE op, so the
poller can read the released ring. PollerRegisterEvent() also looks up the
poller group with bthread_self_tag() at REMOVE time, which may be a
different group than the one that saw ADD, leaving a stale socket id in the
first group's set.

- Choose the poller of _poller_sid when the events are added and reuse it
  for MOD/REMOVE.
- Resolve the endpoint from the owning Socket through a SocketUser kept in
  the synthetic poller Socket, and hold that Socket while polling, so the
  endpoint cannot be released under the poller.
- Reference count the ring: DeallocateResources() stops handing it out and
  the last user destroys it. The trx is closed only when nobody uses the
  ring, and the close, which may wait for the peer, does not run in the
  poller when the poller is the last user.
- Pass the acquired ring to PollIn()/PollOut() so they cannot observe a
  replaced _ub_ring, and let IsWritable()/CutFromIOBufList() borrow it the
  same way instead of dereferencing a null or stale pointer.

Tests: ring lifetime across Reset()/release, event routing to the poller
recorded at ADD time, and a stress test that churns endpoints while the
poller polls them.

Copilot AI 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.

🟡 Changes recommended

Several unresolved moderate and critical findings remain, including leak-prone ownership transfer, blocking cleanup on the poller path, unsafe ring retirement and acquisition races, and untracked shutdown helpers that can access torn-down global resources.

5 open issues
What changed in this PR

This PR hardens UBRing endpoint teardown against concurrent polling, sending, and handshake activity while keeping poller operations associated with the poller selected during registration.

Changes:

  • Adds reference-counted ring acquisition and deferred destruction during teardown.
  • Resolves poller endpoints through retained owning sockets and records stable poller ownership.
  • Adds tests covering ring lifetime, poller routing, and endpoint teardown races.
File Description
test/​brpc_ubring_unittest.cpp Adds tests for ring lifetime bounds, poller operation routing, and endpoint teardown under concurrent polling.
src/​brpc/​ubshm/​ub_endpoint.h Declares ring reference-management APIs, poller ownership metadata, and updated polling interfaces.
src/​brpc/​ubshm/​ub_endpoint.cpp Implements ring lifetime coordination, socket-based poller endpoint resolution, stable poller routing, and safer polling and teardown paths.

Review effort: Lite

Comment thread src/brpc/ubshm/ub_endpoint.cpp Resolved
Comment thread src/brpc/ubshm/ub_endpoint.cpp Resolved
Comment thread src/brpc/ubshm/ub_endpoint.cpp Resolved
Comment thread src/brpc/ubshm/ub_endpoint.cpp Resolved
Comment thread src/brpc/ubshm/ub_endpoint.cpp Resolved
Address the review of the previous commit:

- Drop the helper bthread that destroyed the ring: an untracked bthread could
  outlive GlobalRelease() and touch the UBRing/SHM managers while they are
  being torn down, and its inline fallback could still close the ring in the
  poller. DeallocateResources() now waits (on the ring reference count) until
  no poller or sender uses the ring and then closes it itself, which also
  removes the single "retired ring" slot that a new allocation could
  overwrite before the previous ring was reclaimed.
- Make the counter/closed-flag protocol one atomic protocol: every access uses
  sequential consistency, so either the teardown sees a new user or the user
  sees the closed flag.
- Attach the PollerUser with Socket::set_user() after Socket::Create()
  succeeded, so a socket that fails to initialize cannot leak it.

The reference count is created by butex_create() so that the teardown can sleep
on it; its value is initialized explicitly because butex_create() does not
initialize it.

The tests now start their helpers on separate threads so that the poller really
runs concurrently with the endpoint release: the poller only runs on a worker
pthread when it is started from a thread that is not a bthread worker, and the
releasing thread blocks in DeallocateResources() while the user holds the ring.

Copilot AI 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.

🟡 Changes recommended

Active moderate and critical findings remain in teardown and poller coordination, including a potential stale event re-registration and an unbounded drain that can block resource deallocation indefinitely.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Late epoll registration can resurrect a removed socket

src/​brpc/​ubshm/​ub_endpoint.cpp:1175

WaitEpollOut() can still register an ADD/MOD after teardown has enqueued REMOVE: it calls PollerRegisterEpollOut() even when IsWritable() failed because _ring_closed is set, and its failed-socket path returns before PollerUnRegisterEpollOut(). Since registration and teardown can be on different producers, the late op can be processed after REMOVE, re-inserting the old synthetic sid into poller_sids forever (each poll then only fails Socket::Address). Serialize event registration with teardown or add a generation/closed check that the poller enforces when applying queued ops.

5 resolved since last review

Review effort: Lite

Comment thread src/brpc/ubshm/ub_endpoint.cpp Resolved
DeallocateResources() waits for the poller to leave the ring, but PollIn()
drained the ring until it became empty, which a peer that keeps sending can
postpone for a long time. Bail out of PollIn() as soon as the endpoint is
released, both before touching the ring and per processed message, so the
teardown waits for at most one message.

A sender may also register EPOLLOUT after the ring stopped being handed out
(WaitEpollOut() does that when IsWritable() fails, and its failed-socket path
returns before unregistering). Such an ADD/MOD can be applied after the REMOVE
of the teardown, which re-inserts the socket id into the poller set where it is
resolved on every poll. Drop ADD/MOD once the endpoint is closed, and let the
poller forget a sid it cannot resolve any more.

Tests: late EPOLLOUT registration is dropped while REMOVE still goes through,
and PollIn() returns on a released endpoint before it touches the ring.
@wwbmmm

wwbmmm commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

[replied by brpc-oncall robot] Also addressed the late-registration finding (WaitEpollOut() registering ADD/MOD after teardown enqueued REMOVE):

  • PollerRegisterEvent() drops ADD/MOD once the endpoint is closed (the teardown's own REMOVE still goes through). That is the case WaitEpollOut() hits when IsWritable() fails because the ring was already given up.
  • Because registration and teardown are different producers, an ADD/MOD queued before the closed flag can still be applied after REMOVE. The poller now forgets a socket id it cannot resolve any more (failed synthetic socket, released owning socket, or an endpoint that no longer hands out its ring) instead of resolving it on every poll, so such an id cannot stay in the set.

New test late_registration_after_release_is_dropped checks that a late ADD/MOD never reaches the poller while the teardown's REMOVE does.

Copilot AI 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.

🔵 Needs a closer look

Two critical concurrency issues remain in ub_endpoint.cpp: unsynchronized poller access during teardown and a potential use-after-destruction of the ring reference during release.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

High severity Synchronize poller access with teardown and event registration

src/​brpc/​ubshm/​ub_endpoint.cpp:204

_poller is a plain pointer, but PollerRegisterEvent() can run from a sender bthread while Reset() clears it here. The ring reference wait does not protect this access: WaitEpollOut() releases its ring borrow before registering EPOLLOUT. This is a C++ data race and can also make a registration use a cleared or mismatched poller; synchronize _poller/_poller_sid with teardown and event registration.

High severity Keep the ring reference alive through the release wake-up

src/​brpc/​ubshm/​ub_endpoint.cpp:239

ReleaseRing() decrements _ring_ref before it finishes its wake-up epilogue. DeallocateResources() treats the counter reaching zero as permission to return from Reset(), and the endpoint destructor then destroys _ring_ref; the releasing thread can subsequently load _ring_closed and call butex_wake_all(_ring_ref) on that destroyed butex. Please keep the release operation itself alive until the wake-up is complete (for example with a separate lifetime/active-releaser guard) before allowing the endpoint to destroy the butex.

1 resolved since last review

Review effort: Lite

Address the remaining teardown races:

- `_poller` and `_poller_sid` are read by senders (`WaitEpollOut()`), written
  by the handshake and cleared by `Reset()`, so make them atomic and publish
  them in a fixed order. The poller is now chosen where the events are added
  instead of inside `PollerRegisterEvent()`, so a sender can never pick a
  poller with its own bthread tag, and a sender that runs during the teardown
  either sees the pair or finds no poller and drops its op.
- `ReleaseRing()` only decrements the counter now, and the teardown polls the
  counter instead of sleeping on a butex. This way the last release cannot
  touch the endpoint after the counter reached zero, when the ring is closed
  and the endpoint may be destroyed; previously its wake-up epilogue could
  read `_ring_closed` and wake a butex that was already destroyed.

The counter is a plain atomic again, so the endpoint no longer allocates a
butex for it.
@wwbmmm
wwbmmm requested a lite review from Copilot November 27, 2026 14:23
@wwbmmm

wwbmmm commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

[replied by brpc-oncall robot] Addressed the two remaining teardown races:

Poller state vs. registration. _poller and _poller_sid are now atomics, because senders (WaitEpollOut()), the handshake and Reset() touch them from different threads. The poller is chosen where the events are added (in AllocateClientResources()/AllocateServerResources()) instead of inside PollerRegisterEvent(), and the pair is published in a fixed order (poller first, then socket id). A sender that runs during the teardown therefore either reads a complete pair or finds no poller and drops its op, and it can no longer pick a poller from its own bthread tag. A late op that still slips through is dropped by the poller, which now forgets socket ids it cannot resolve any more.

Release vs. destroy. ReleaseRing() is now a single atomic decrement, and DeallocateResources() polls the counter with a short sleep instead of sleeping on a butex. Previously the last releasing thread could be preempted between the decrement and its wake-up epilogue (load _ring_closed, butex_wake_all()), while the teardown already saw the counter at zero, closed the ring and — in the destructor — destroyed the butex, so the release touched freed memory. With the counter-only release, nothing touches the endpoint after the count reaches zero, which is exactly when the teardown is allowed to proceed; the counter is a plain atomic again and the endpoint no longer allocates a butex for it.

Copilot AI 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.

🔵 Needs a closer look

Approval should be deferred because the concurrency-sensitive UBRing teardown and close-handshake changes are tested only through IPC, leaving real UB hardware and delayed peer-acknowledgement behavior unvalidated.

No open issues 🎉

Review effort: Lite

UBShmEndpoint* ep = transport->GetUBShmEp();
UBRing* ring = nullptr;
if (!ep->AcquireRing(&ring)) {
released_sids.push_back(poller_sid.sid);

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.

The _poller_sid for this registration also needs to be checked here. The old poller can pause after acquiring the synthetic socket, while a health check can still reset and restore the owning socket in place. After the handshake, the old PollerUser::owner_id can still resolve successfully, but AcquireRing() returns the new ring. If the new registration lands on another poller, both pollers will read the same ring and read_buf() concurrently. Consider comparing ep->_poller_sid with poller_sid.sid after acquiring the ring reference; if they do not match, release the reference and remove the stale entry.

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.

[replied by brpc-oncall robot] Done. The poller now compares ep->_poller_sid with the sid of the entry after AcquireRing() succeeded, and releases the reference and drops the entry when they differ. That covers the case you describe: the stale entry still resolves the owning socket and gets the ring of the new connection, but it is no longer the endpoint's current registration, so it does not poll. Stale entries are removed from the set after the iteration.

Comment thread test/brpc_ubring_unittest.cpp Outdated
bthread_usleep(1000);
}
_ep->Reset();
EXPECT_TRUE(user.released.load());

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.

ReleaseRing() and released.store(true) are two separate operations. If the holding thread is preempted between them, a correct Reset() may already have returned while this assertion still fails. A fixed sleep also allows the holding thread to release the ring before Reset() starts. Consider having the holding thread wait until _ring_closed is set before releasing the reference, using TrxIsFree() to check the reset result, and reading the thread completion flag after join().

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.

[replied by brpc-oncall robot] Done. The holding thread now waits until _ring_closed is set before returning the ring, so Reset() has really started and its wait covers this user (no fixed sleep any more), and the test checks released, the writable result and TrxIsFree() after join() instead of racing with the release.

Comment thread test/brpc_ubring_unittest.cpp Outdated
continue;
}
// Let the poller poll the endpoint before it is released.
bthread_usleep(100);

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.

Sleeping for 100 microseconds does not guarantee that the poller has seen this endpoint. ADD and REMOVE can both be dequeued in the same iteration, leaving the registration set empty, while the transaction slot is still released normally at the end. Consider making at least one iteration wait for a signal that the poller has successfully borrowed the target ring before tearing it down concurrently, so the test can catch regressions that skip the polling path.

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.

[replied by brpc-oncall robot] Done. The churn now waits until the poller has actually borrowed the ring (WaitForPollerToBorrow() polls _ring_ref) before releasing the endpoint, and counts a failure if that never happens, so an ADD/REMOVE applied in the same iteration can no longer make the test skip the polling path.

Comment thread test/brpc_ubring_unittest.cpp Outdated
brpc::ubring::UBShmEndpoint::Poller other;
_ep->_poller.store(&other);
_ep->PollerRegisterEvent(brpc::ubring::UBShmEndpoint::PollerSidOp::REMOVE);
ASSERT_TRUE(other.op_queue.Dequeue(op));

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.

If this routing assertion fails, the test body returns early and destroys other, but _ep->_poller still points to it. TearDown() then deletes the endpoint and sends REMOVE to the destroyed queue. Please use scope cleanup to restore the original poller even on an early return.

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.

[replied by brpc-oncall robot] Done. The assertions after pointing _poller at the local poller are EXPECT_* now, so Reset() at the end of the test always runs and clears the pointer before the local poller is destroyed.

Comment thread test/brpc_ubring_unittest.cpp Outdated

brpc::ubring::SHM local_trx_shm =
{nullptr, 4 * 1024 * 1024, 0, {0}, (uint32_t)_socket->fd()};
ASSERT_EQ(0, _ep->AllocateClientResources(&local_trx_shm, "UBRING_ut_ring"));

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 name directly determines the actual IPC shared memory object name. When the same test runs in parallel, the second process encounters EEXIST at shm_open(O_CREAT | O_EXCL). Consider using short names with a process ID and sequence number, as in ChurnEndpoints(), for both UBRING_ut_late and UBRING_ut_op.

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.

[replied by brpc-oncall robot] Done. The new tests use UniqueShmName(), which appends the process id and a sequence number, so two test processes can no longer collide on the IPC object name.

Comment thread test/brpc_ubring_unittest.cpp Outdated
1, std::memory_order_relaxed));
if (ep->AllocateClientResources(&local_trx_shm, name.c_str()) != 0) {
++*failures;
continue;

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.

The direct continue here skips the SetFailed() call at the end. Destruction of the local s only releases the reference from Address(); the owning socket still holds the extra reference acquired at creation, and some resources already attached to the endpoint cannot be cleaned up. Please mark the socket as failed in this error branch, or use scope cleanup for all exit paths.

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.

[replied by brpc-oncall robot] Done. ChurnEndpoints() no longer continues out of the loop: every path reaches s->SetFailed(), and the Socket::Address() failure path uses Socket::SetFailed(id) to release the reference taken by Socket::Create().

A poller entry belongs to the connection that registered it. The endpoint can
be reset and registered again on another poller while this one is resolving the
entry, and AcquireRing() then returns the ring of the new connection; polling it
here would make two pollers read the same ring and the same input buffer. Check
that the entry is still the endpoint's current registration after acquiring the
ring and drop it otherwise.

Tests:
- ring_lifetime_is_bounded_by_its_users: the holding thread now waits until the
  endpoint is closing the ring instead of sleeping for a fixed time, so the
  release really waits for it, and the ring/user state is checked after join()
  instead of racing with it.
- poller_survives_endpoint_teardown: wait until the poller has borrowed the ring
  before releasing the endpoint, because a REMOVE can be applied in the same
  iteration as its ADD, and then the teardown of a polled endpoint is never
  exercised. Fail the socket on every path, otherwise the reference taken by
  Socket::Create() leaks.
- Use per-process, per-test shared memory names so that two test processes can
  run in parallel.
- poller_of_add_serves_later_operations: no ASSERT() after pointing the endpoint
  at a local poller, so that Reset() always runs and clears the pointer before
  the local poller goes out of scope.

Copilot AI 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.

🔵 Needs a closer look

Human assessment is needed because a critical concurrency finding indicates a possible use-after-free or partially initialized ring during reset and allocation.

No open issues 🎉

Review effort: Lite

@wwbmmm
wwbmmm requested a review from chenBright December 3, 2026 12:50
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.

3 participants