You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@rocketmq.apache.org by "unbridled-41 (via GitHub)" <gi...@apache.org> on 2026/09/05 16:02:26 UTC

[PR] [ISSUE #11045] Rebind broker channel on heartbeat so stale channel close cannot evict a live broker [rocketmq]

unbridled-41 opened a new pull request, #11046:
URL: https://github.com/apache/rocketmq/pull/11046

   Closes #11045
   
   ### Problem / Evidence
   
   `DefaultBrokerHeartbeatManager#onBrokerHeartbeat` never rebinds the channel of an existing `BrokerLiveInfo` — the `prev != null` branch only refreshes the timestamp, timeout, election priority and epoch (`DefaultBrokerHeartbeatManager.java:133-142`), so the live entry stays pinned to the broker's **first-ever** channel.
   
   When the broker-to-controller connection dies half-open (or the controller-side close event for the old channel arrives late), the broker client reconnects first and keeps heartbeating on a new channel. When the old channel eventually fires `channelInactive`/`onChannelException`/`onChannelIdle`, `BrokerHousekeepingService` (wired as the controller `ChannelEventListener` in `ControllerManager`, passed to `DLedgerServer`) calls `onBrokerChannelClose(oldChannel)`, which matches the stale stored channel, **removes the live entry of a broker that is healthy on the new channel** and fires `notifyBrokerInActive`. `ControllerManager#onBrokerInactive` then checks `getReplicaInfo` and, because the evicted broker is the current master, calls `triggerElectMaster` — a spurious failover (epoch bump, possible master change, sync-state reset) for a healthy broker-set.
   
   Deterministic regression test `DefaultBrokerHeartbeatManagerTest#testStaleChannelCloseDoesNotEvictReRegisteredBroker` fails on unmodified `develop`:
   
   ```
   DefaultBrokerHeartbeatManagerTest.testStaleChannelCloseDoesNotEvictReRegisteredBroker:74
   A stale channel close must not evict a broker alive on a new channel
   Tests run: 2, Failures: 1, Errors: 0, Skipped: 1  (develop @ ff8f6f74c, 2026-09-05)
   ```
   
   ### Root cause / Fix
   
   The heartbeat path keeps the stale channel reference forever. This is inconsistent with the NameServer implementation, where the broker's channel is refreshed on every registration heartbeat.
   
   Fix: rebind the live entry to the current channel in `onBrokerHeartbeat` when a non-null channel arrives, so `onBrokerChannelClose` only removes entries whose stored channel is the one that actually closed:
   
   ```java
   // Rebind the live entry to the current channel, otherwise a close event of a stale
   // channel would evict a broker that is already alive on a new channel
   if (channel != null && channel != prev.getChannel()) {
       prev.setChannel(channel);
   }
   ```
   
   ### Priority
   
   PRIORITY = 76(影响 30 + 波及范围 14 + 可复现 18 + 维护价值 14),FIX_CONFIDENCE = 88。
   
   - 影响 30/40: spurious master election / epoch bump fencing a healthy master — an availability and correctness event for every controller-mode deployment (the default dLedger controller uses this heartbeat manager).
   - 波及范围 14/20: all controller-mode deployments; the mechanism (heartbeat + channel lifecycle) runs continuously.
   - 可复现 18/20: deterministic two-channel unit test; the reconnect-before-close ordering is a routine network scenario.
   - 维护价值 14/20: same bug family as the nameserver stale-channel issues; small, well-bounded fix aligning controller with nameserver behavior.
   
   ### Tests
   
   - Regression test added: `DefaultBrokerHeartbeatManagerTest#testStaleChannelCloseDoesNotEvictReRegisteredBroker` (fails before the fix as shown above).
   - After the fix (`develop @ ff8f6f74c` + this change, 2026-09-05):
   
   ```
   mvn -pl controller test -Dtest=DefaultBrokerHeartbeatManagerTest
   Tests run: 2, Failures: 0, Errors: 0, Skipped: 0  — BUILD SUCCESS
   ```
   
   - Full controller module: `mvn -pl controller test` — all tests pass except the pre-existing baseline failure `ReplicasInfoManagerTest#testSerialize` (JDK-21 `InaccessibleObjectException: Unable to make field ... AtomicLong.value accessible`), which reproduces identically on unmodified `develop @ ff8f6f74c` and is unrelated to this change.
   
   ### Risk
   
   Very low. The added branch only updates a mutable field that was previously never refreshed after creation; heartbeats without a channel (the existing test passes `null`) keep the old behavior. The close-detection semantics (`getChannel() == channel` identity match) are unchanged — they simply now compare against the current channel. The jRaft heartbeat manager keeps its own raft-routed close handling and is untouched.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@rocketmq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [ISSUE #11045] Rebind broker channel on heartbeat so stale channel close cannot evict a live broker [rocketmq]

Posted by "unbridled-41 (via GitHub)" <gi...@apache.org>.
unbridled-41 closed pull request #11046: [ISSUE #11045] Rebind broker channel on heartbeat so stale channel close cannot evict a live broker
URL: https://github.com/apache/rocketmq/pull/11046


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@rocketmq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [ISSUE #11045] Rebind broker channel on heartbeat so stale channel close cannot evict a live broker [rocketmq]

Posted by "unbridled-41 (via GitHub)" <gi...@apache.org>.
unbridled-41 commented on PR #11046:
URL: https://github.com/apache/rocketmq/pull/11046#issuecomment-5970066740

   Made atomic in 4f46a0708, following the shape you suggested:
   
   - `onBrokerHeartbeat` now performs the whole create/update/rebind through `brokerLiveTable.compute(...)`, so an entry is never observed half-updated.
   - `onBrokerChannelClose` walks the identities and calls `computeIfPresent(...)`, returning `null` only while the live entry still carries the closing channel; a heartbeat that rebound the identity first makes the stale close a no-op. The inactive notification is submitted with the values captured at removal (`closed.getBrokerName()`, `closed.getBrokerId()`), not by closing over the mutable entry.
   
   **Coordinated concurrency test.** `testConcurrentHeartbeatDuringStaleChannelCloseKeepsBrokerAlive` runs 500 rounds: each round starts with the broker live on the old channel, releases the stale close and the rebinding heartbeat from a common latch, then requires the entry to still exist and carry the new channel. Before the change it fails on the very first round:
   
   ```
   round 1: the live entry must survive the stale close
   ```
   
   After: `mvn -pl controller -Dtest=DefaultBrokerHeartbeatManagerTest test` → `Tests run: 3, Failures: 0, Errors: 0, Skipped: 0`.
   
   One note: pausing the close deterministically after its match would need a test-only hook in production code, so I used the coordinated race instead — happy to add the hook if you would rather have the deterministic interleaving.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@rocketmq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [ISSUE #11045] Rebind broker channel on heartbeat so stale channel close cannot evict a live broker [rocketmq]

Posted by "RongtongJin (via GitHub)" <gi...@apache.org>.
RongtongJin commented on code in PR #11046:
URL: https://github.com/apache/rocketmq/pull/11046#discussion_r4227688656


##########
controller/src/main/java/org/apache/rocketmq/controller/impl/heartbeat/DefaultBrokerHeartbeatManager.java:
##########
@@ -111,53 +112,70 @@ public void onBrokerHeartbeat(String clusterName, String brokerName, String brok
         Long timeoutMillis, Channel channel, Integer epoch, Long maxOffset, Long confirmOffset,
         Integer electionPriority) {
         BrokerIdentityInfo brokerIdentityInfo = new BrokerIdentityInfo(clusterName, brokerName, brokerId);
-        BrokerLiveInfo prev = this.brokerLiveTable.get(brokerIdentityInfo);
         int realEpoch = Optional.ofNullable(epoch).orElse(-1);
         long realBrokerId = Optional.ofNullable(brokerId).orElse(-1L);
         long realMaxOffset = Optional.ofNullable(maxOffset).orElse(-1L);
         long realConfirmOffset = Optional.ofNullable(confirmOffset).orElse(-1L);
         long realTimeoutMillis = Optional.ofNullable(timeoutMillis).orElse(DEFAULT_BROKER_CHANNEL_EXPIRED_TIME);
         int realElectionPriority = Optional.ofNullable(electionPriority).orElse(Integer.MAX_VALUE);
-        if (null == prev) {
-            this.brokerLiveTable.put(brokerIdentityInfo,
-                new BrokerLiveInfo(brokerName,
+        // compute() keeps the create-or-update decision and the channel rebinding atomic per
+        // broker identity, so onBrokerChannelClose can never observe a half-updated entry: a
+        // heartbeat that rebinds the entry and a close of the previous channel serialize on the
+        // same key instead of racing between the match and the removal.
+        this.brokerLiveTable.compute(brokerIdentityInfo, (key, prev) -> {
+            if (prev == null) {
+                log.info("new broker registered, {}, brokerId:{}", brokerIdentityInfo, realBrokerId);
+                return new BrokerLiveInfo(brokerName,
                     brokerAddr,
                     realBrokerId,
                     System.currentTimeMillis(),
                     realTimeoutMillis,
                     channel,
                     realEpoch,
                     realMaxOffset,
-                    realElectionPriority));
-            log.info("new broker registered, {}, brokerId:{}", brokerIdentityInfo, realBrokerId);
-        } else {
+                    realElectionPriority);
+            }
             prev.setLastUpdateTimestamp(System.currentTimeMillis());

Review Comment:
   [P1] Make expiry revalidation/removal atomic with heartbeat rebinding
   
   The per-key compute protects this update against onBrokerChannelClose, but scanNotActiveBroker still reads the timestamp, checks expiry, reads the channel, and removes the entry outside that atomic operation. A concrete interleaving is:
   
   1. The scanner reads the old lastUpdateTimestamp and pauses.
   2. A heartbeat on newChannel refreshes the timestamp and rebinds this same BrokerLiveInfo.
   3. The scanner resumes, decides it is expired using the old timestamp, reads newChannel from the updated object, removes the live entry, and closes the healthy new connection.
   
   I reproduced this with JDK 8 by pausing getLastUpdateTimestamp after capturing its old value, completing the replacement heartbeat, then resuming the scan. The assertion that newChannel remains active passes with the base manager and fails at this head. The expiry/removal race predates this PR, but closing the newly rebound connection is an additional consequence of this change.
   
   Please have the scan recheck the current timestamp/timeout and remove the entry within computeIfPresent for the same identity, capture the channel of the entry actually removed, and close that captured channel outside the operation. Add a coordinated regression test for this order; remove(key, value) alone is insufficient while heartbeats mutate the same value object.



##########
controller/src/main/java/org/apache/rocketmq/controller/impl/heartbeat/DefaultBrokerHeartbeatManager.java:
##########
@@ -111,53 +112,70 @@ public void onBrokerHeartbeat(String clusterName, String brokerName, String brok
         Long timeoutMillis, Channel channel, Integer epoch, Long maxOffset, Long confirmOffset,
         Integer electionPriority) {
         BrokerIdentityInfo brokerIdentityInfo = new BrokerIdentityInfo(clusterName, brokerName, brokerId);
-        BrokerLiveInfo prev = this.brokerLiveTable.get(brokerIdentityInfo);
         int realEpoch = Optional.ofNullable(epoch).orElse(-1);
         long realBrokerId = Optional.ofNullable(brokerId).orElse(-1L);
         long realMaxOffset = Optional.ofNullable(maxOffset).orElse(-1L);
         long realConfirmOffset = Optional.ofNullable(confirmOffset).orElse(-1L);
         long realTimeoutMillis = Optional.ofNullable(timeoutMillis).orElse(DEFAULT_BROKER_CHANNEL_EXPIRED_TIME);
         int realElectionPriority = Optional.ofNullable(electionPriority).orElse(Integer.MAX_VALUE);
-        if (null == prev) {
-            this.brokerLiveTable.put(brokerIdentityInfo,
-                new BrokerLiveInfo(brokerName,
+        // compute() keeps the create-or-update decision and the channel rebinding atomic per
+        // broker identity, so onBrokerChannelClose can never observe a half-updated entry: a
+        // heartbeat that rebinds the entry and a close of the previous channel serialize on the
+        // same key instead of racing between the match and the removal.
+        this.brokerLiveTable.compute(brokerIdentityInfo, (key, prev) -> {
+            if (prev == null) {
+                log.info("new broker registered, {}, brokerId:{}", brokerIdentityInfo, realBrokerId);
+                return new BrokerLiveInfo(brokerName,
                     brokerAddr,
                     realBrokerId,
                     System.currentTimeMillis(),
                     realTimeoutMillis,
                     channel,
                     realEpoch,
                     realMaxOffset,
-                    realElectionPriority));
-            log.info("new broker registered, {}, brokerId:{}", brokerIdentityInfo, realBrokerId);
-        } else {
+                    realElectionPriority);
+            }
             prev.setLastUpdateTimestamp(System.currentTimeMillis());
             prev.setHeartbeatTimeoutMillis(realTimeoutMillis);
             prev.setElectionPriority(realElectionPriority);
+            // Rebind the live entry to the current channel, otherwise a close event of a stale
+            // channel would evict a broker that is already alive on a new channel
+            if (channel != null && channel != prev.getChannel()) {
+                prev.setChannel(channel);

Review Comment:
   [P1] Do not let a late heartbeat restore an already closed channel
   
   This condition also accepts a heartbeat whose channel has already closed. A heartbeat request from oldChannel can be dispatched before disconnection but finish after a heartbeat on newChannel: controller requests use the shared request executor, RequestTask.run does not check channel liveness, and close events run on a separate NettyEventExecutor.
   
   The resulting order is: an old heartbeat is queued; oldChannel closes; newChannel's heartbeat updates the live entry; the queued old heartbeat runs and this assignment changes the channel back to oldChannel; the delayed old close callback then removes the broker even though newChannel is still active. I reproduced that order with an actual RequestTask and EmbeddedChannels on this head: the new connection remains active, but the live-table entry disappears.
   
   This is a remaining instance of the original failure, rather than a separate newly introduced bug. compute serializes the map operations but cannot establish which connection is current. Please reject heartbeats from closed channels inside the per-identity atomic update, covering creation and timestamp refresh as well as rebinding, and add a deterministic test where the old request executes after the new heartbeat. If two active connections may overlap, their ordering also needs an explicit policy; the broker epoch alone is not a connection generation.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@rocketmq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [ISSUE #11045] Rebind broker channel on heartbeat so stale channel close cannot evict a live broker [rocketmq]

Posted by "unbridled-41 (via GitHub)" <gi...@apache.org>.
unbridled-41 commented on PR #11046:
URL: https://github.com/apache/rocketmq/pull/11046#issuecomment-5556022599

   **Evidence-chain audit (2026-09-06)** — every technical assertion in the PR body re-verified against source; tests re-run at the branch tip.
   
   Code-level anchors (personally re-read at the fix branch):
   
   - `DefaultBrokerHeartbeatManager#onBrokerHeartbeat` `prev != null` branch (main `:133-142` pre-fix) refreshes only timestamp/timeout/priority/epoch; `BrokerLiveInfo#setChannel` exists but is called **nowhere** in the file (grep `setChannel` → only the definition `BrokerLiveInfo.java:151-153`).
   - `onBrokerChannelClose` (`:147-161` pre-fix) evicts by channel **identity** match and fires `notifyBrokerInActive` on the stale match.
   - Wiring confirmed end-to-end: `BrokerHousekeepingService.onChannelClose/onChannelException/onChannelIdle` → `onBrokerChannelClose` (`BrokerHousekeepingService.java:38-50`); it is registered as the controller `ChannelEventListener` (`ControllerManager.java:82`, passed at `:123`) and handed to `DLedgerServer` (`DLedgerController.java:117→136`). `ControllerManager#onBrokerInactive` triggers `triggerElectMaster` when the evicted broker is the current master.
   - Nameserver-consistency claim in the body now verified directly: `RouteInfoManager.registerBroker` **replaces** the whole `BrokerLiveInfo` (carrying `ctx.channel()`) on every registration heartbeat (`namesrv/.../RouteInfoManager.java:373-380`), so the NameServer refreshes the channel every heartbeat — the controller did not.
   
   Fresh re-run at this PR's tip `a7accbf9b` (2026-09-06, JDK 21):
   
   ```
   mvn -pl controller test -Dtest=DefaultBrokerHeartbeatManagerTest
   Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 — BUILD SUCCESS
   ```
   
   The jRaft heartbeat manager (`RaftBrokerHeartBeatManager`) routes live info through raft consensus with `channel = null` in its `BrokerLiveInfo`, so it has a different close-detection mechanism and is intentionally untouched by this fix.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@rocketmq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [ISSUE #11045] Rebind broker channel on heartbeat so stale channel close cannot evict a live broker [rocketmq]

Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #11046:
URL: https://github.com/apache/rocketmq/pull/11046#issuecomment-5553204295

   ## [Codecov](https://app.codecov.io/gh/apache/rocketmq/pull/11046?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `50.00000%` with `1 line` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 48.75%. Comparing base ([`ff8f6f7`](https://app.codecov.io/gh/apache/rocketmq/commit/ff8f6f74c560e391261ccd716707c6d20422e253?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`a7accbf`](https://app.codecov.io/gh/apache/rocketmq/commit/a7accbf9ba47a5d9f4ecd044010c6af132f9885b?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/rocketmq/pull/11046?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [.../impl/heartbeat/DefaultBrokerHeartbeatManager.java](https://app.codecov.io/gh/apache/rocketmq/pull/11046?src=pr&el=tree&filepath=controller%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Frocketmq%2Fcontroller%2Fimpl%2Fheartbeat%2FDefaultBrokerHeartbeatManager.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29udHJvbGxlci9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcm9ja2V0bXEvY29udHJvbGxlci9pbXBsL2hlYXJ0YmVhdC9EZWZhdWx0QnJva2VySGVhcnRiZWF0TWFuYWdlci5qYXZh) | 50.00% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/rocketmq/pull/11046?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@              Coverage Diff              @@
   ##             develop   #11046      +/-   ##
   =============================================
   - Coverage      48.86%   48.75%   -0.12%     
   + Complexity     13797    13761      -36     
   =============================================
     Files           1381     1381              
     Lines         101574   101576       +2     
     Branches       13213    13214       +1     
   =============================================
   - Hits           49638    49522     -116     
   - Misses         45924    46021      +97     
   - Partials        6012     6033      +21     
   ```
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/rocketmq/pull/11046?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@rocketmq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org