Skip to content

Add polling mode and callback registration to EventDispatcher - #3715

Open
yanglimingcn wants to merge 2 commits into
apache:masterfrom
yanglimingcn:feature/tcp_polling_mode
Open

yanglimingcn wants to merge 2 commits into
apache:masterfrom
yanglimingcn:feature/tcp_polling_mode

Conversation

@yanglimingcn

@yanglimingcn yanglimingcn commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Add event_dispatcher_use_polling for non-blocking epoll/kqueue polling while preserving the bthread model and existing urgent/background scheduling switch.

Support per-tag callback registration with dispatcher-local contexts, initialization rollback, and synchronous unregistration. Use atomic stop and task identifiers and safely acknowledge pending callback commands during shutdown.

Add tests for idle polling, tag isolation, callback lifecycle, concurrent shutdown, and TCP urgent/background processing.

Validation: git diff --check passed. Build and unit tests remain blocked by missing Protobuf dependencies and a Google Test download timeout.

What problem does this PR solve?

Issue Number: resolve

Problem Summary:

In latency-sensitive scenarios where advanced hardware features cannot be utilized, employing a polling mode for TCP can significantly reduce latency—especially when there is only one worker per tag—by substantially lowering the overhead associated with bthread scheduling. A similar implementation is also supported in the TCP mode of SPDK.

What is changed and the side effects?

Changed:

Side effects:

  • Performance effects:

  • Breaking backward compatibility:


Check List:

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

The cross-platform polling and callback-shutdown changes introduce complex concurrency and platform-specific behavior, while dependency-blocked builds and tests leave runtime and shutdown-race validation unverified.

No open issues 🎉

What changed in this PR

This pull request adds optional non-blocking epoll/kqueue polling and per-tag callback registration to EventDispatcher, while preserving existing bthread scheduling behavior. It also adds lifecycle, rollback, shutdown, and TCP processing tests.

Changes:

  • Added configurable polling mode for epoll and kqueue backends.
  • Added per-tag callback registration and synchronous unregistration with dispatcher-local contexts.
  • Added rollback, stale-token protection, shutdown acknowledgement, and lifecycle test coverage.
  • Review identified a moderate shutdown race: registration can report success after concurrent shutdown has already released the callback contexts. Registration and shutdown need a synchronization gate or rollback/recheck.

This pull request requires changes.

File Description
test/​brpc_event_dispatcher_unittest.cpp Adds coverage for polling, callback isolation and lifecycle, shutdown races, rollback, and TCP scheduling.
src/​brpc/​event_dispatcher.h Defines polling configuration, callback APIs, registration tokens, dispatcher contexts, and lifecycle state.
src/​brpc/​event_dispatcher.cpp Implements callback registration, command acknowledgement, rollback, shutdown handling, and global dispatcher initialization.
src/​brpc/​event_dispatcher_kqueue.cpp Integrates polling mode and atomic lifecycle handling into the kqueue backend.
src/​brpc/​event_dispatcher_epoll.cpp Integrates polling mode and atomic lifecycle handling into the epoll backend.

Review effort: Lite

@wwbmmm

wwbmmm commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

What's the user case of this feature? The Problem Summary in the description is empty, and the tree already has per-tag polling implementations with dedicated poller bthreads for URMA (urma_use_polling) and UBShm. Please state which component is expected to use this generic facility. If the intent is to replace those implementations, the migration (or at least a concrete plan for it) should be part of this PR; otherwise we add a large public API with no in-tree user and no way to validate the contract.

@yanglimingcn
yanglimingcn force-pushed the feature/tcp_polling_mode branch from feaf099 to 7a73730 Compare November 9, 2026 01:18
@yanglimingcn

Copy link
Copy Markdown
Contributor Author

What's the user case of this feature? The Problem Summary in the description is empty, and the tree already has per-tag polling implementations with dedicated poller bthreads for URMA (urma_use_polling) and UBShm. Please state which component is expected to use this generic facility. If the intent is to replace those implementations, the migration (or at least a concrete plan for it) should be part of this PR; otherwise we add a large public API with no in-tree user and no way to validate the contract.

Updated

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

Cross-thread callback lifetimes and shutdown synchronization in platform-specific event loops cannot be validated because the reported build and tests are blocked by missing Protobuf and Google Test dependencies, requiring human runtime validation.

No open issues 🎉

Review effort: Lite

@yanglimingcn

Copy link
Copy Markdown
Contributor Author

What's the user case of this feature? The Problem Summary in the description is empty, and the tree already has per-tag polling implementations with dedicated poller bthreads for URMA (urma_use_polling) and UBShm. Please state which component is expected to use this generic facility. If the intent is to replace those implementations, the migration (or at least a concrete plan for it) should be part of this PR; otherwise we add a large public API with no in-tree user and no way to validate the contract.

In latency-sensitive scenarios where advanced hardware features cannot be utilized, employing a polling mode for TCP can significantly reduce latency—especially when there is only one worker per tag—by substantially lowering the overhead associated with bthread scheduling. A similar implementation is also supported in the TCP mode of SPDK.
Therefore, they do not conflict.

_polling_command.store(&command, std::memory_order_release);
}
// Only polling dispatchers accept commands, so no wakeup syscall is needed.
CHECK_EQ(0, command.done.wait());

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 the first dispatcher for the same tag starts successfully but the second fails to start because file descriptors are exhausted or bthread creation fails, this still publishes a command to the second dispatcher. Both its _stop and _polling_finished are false, but no thread can call done.signal(). Registration will wait indefinitely while holding the tag lock.

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. A dispatcher that fails to start never reaches FinishPolling(), so checking _stop and _polling_finished alone was not enough.
SetPollingCallbacks() now checks for a valid bthread ID before publishing the command. If the second dispatcher failed to start, registration rolls back the callbacks already installed on the first dispatcher and returns -1 with errno = ESHUTDOWN, without issuing a token. We also made Start() fail if the wakeup pipe cannot be created, so a partially initialized dispatcher cannot accept polling commands.

registration->_tag = tag;
registration->_id = state->id;
group.state = std::move(state);
return 0;

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.

After dispatcher 0 confirms initialization, it can complete Stop(), Join(), and release_fn before dispatcher 1 initializes. The two dispatchers have therefore never been ready at the same time, yet this still publishes a token and returns 0.

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.

This race is still possible. Registration waits for each dispatcher to acknowledge initialization, but an earlier dispatcher can stop and run release_fn while registration is still waiting for a later one. A successful return therefore means every dispatcher acknowledged installation, not that they were all ready at the same time. The token identifies the registration; it is not a liveness guarantee.
The startup-failure fix does not address this race. To guarantee that all dispatchers are still ready when the token is published, we would need to synchronize the final registration commit with Stop() and event-loop exit, and roll back if shutdown wins. Checking Running() one dispatcher at a time would not close the race.

Comment thread src/brpc/event_dispatcher.cpp Outdated
for (int i = 0; i < g_edisp_num; ++i) {
CHECK_EQ(0, dispatchers[i].SetPollingCallbacks(nullptr));
}
group.state.reset();

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.

group.state.reset() destroys the callback's captured objects while holding group.mutex. If the deleter of the last shared_ptr unregisters the same tag again, the calling thread will deadlock before token validation. At this point, all dispatchers have already confirmed removal,

// back all initialized contexts. Duplicate registration fails with EEXIST.
// Callbacks are serial per dispatcher, but concurrent across dispatchers. They
// must not block, throw, or synchronously register/unregister callbacks (EDEADLK).
// poll_fn must be non-null. Returns 0 on success, -1 with errno on failure.

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 clarify the earliest point at which poll_fn can run. Currently, dispatcher 0 can consume events from the external queue before dispatcher 1 fails to initialize and the overall registration returns -1. Callers need to know that events may already have been processed despite this failure so they can arrange enabling and retries correctly.

Add event_dispatcher_use_polling for non-blocking epoll/kqueue polling while preserving the bthread model and existing urgent/background scheduling switch.

Support per-tag callback registration with dispatcher-local contexts, initialization rollback, and synchronous unregistration. Use atomic stop and task identifiers and safely acknowledge pending callback commands during shutdown.

Add tests for idle polling, tag isolation, callback lifecycle, concurrent shutdown, and TCP urgent/background processing.

Validation: git diff --check passed. Build and unit tests remain blocked by missing Protobuf dependencies and a Google Test download timeout.
@yanglimingcn
yanglimingcn force-pushed the feature/tcp_polling_mode branch from 7a73730 to 1d6ec2a Compare November 30, 2026 01:50
Comment thread src/brpc/event_dispatcher.cpp Outdated
CHECK_EQ(0, g_edisp[i * FLAGS_event_dispatcher_num + j].Start(&attr));
attr.tag = (BTHREAD_TAG_DEFAULT + i) % g_edisp_ntags;
g_edisp[i * g_edisp_num + j].set_priority_index(j);
CHECK_EQ(0, g_edisp[i * g_edisp_num + j].Start(&attr));

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.

A pipe() failure now closes the event queues that were already created, but when crash_on_fatal_log=false, the CHECK_EQ here allows global initialization to complete. The fd hash can still select this member afterward, so ordinary TCP AddConsumer() calls will continue to return EINVAL even after the quota recovers.

Comment thread src/brpc/event_dispatcher.cpp Outdated
return -1;
}
std::unique_ptr<EventDispatcherPollingState> state(
new EventDispatcherPollingState(callbacks, ++group.next_id));

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.

EventDispatcherPollingState's callbacks(cb) invokes the user function object's copy constructor while holding group.mutex. If copying unregisters the same tag using an old token, it waits for the lock it already holds before validating the token, even if the token has expired.

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

Approval is blocked by critical deadlock risks when polling registration or unregistration is called from urgent TCP callbacks while the dispatcher is suspended.

2 open issues

Review effort: Lite

Comment on lines +235 to +236
for (int i = 0; i < g_edisp_ntags * g_edisp_num; ++i) {
if (g_edisp[i].IsDispatcherThread()) {
Comment on lines +86 to +92
int RegisterPollingCallbacksWithTag(bthread_tag_t tag,
const PollingCallbacks& callbacks,
PollingRegistration* registration);

// On success, all callbacks have stopped and release_fn has completed. This
// does not stop dispatchers or TCP traffic. Returns 0 or -1 with errno.
int UnregisterPollingCallbacks(PollingRegistration registration);
Fail fast when a global dispatcher cannot start so fd routing never publishes an unusable shard. Copy polling callbacks outside the group lock and recheck registration before installation.

Cover fd exhaustion and callback-copy reentrancy in regression tests.

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

The change spans complex concurrent callback, acknowledgement, and shutdown coordination across platforms, while missing Protobuf/gtest dependencies prevent build and runtime validation.

2 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.

4 participants