Skip to content

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

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

wwbmmm wants to merge 4 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

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.

2 participants