Skip to content

fix: [#4696] HA/Raft auto-reset a follower's wedged replication chann… - #5020

Merged
lvca merged 3 commits into
mainfrom
worktree-fix-4696-grpc-channel-recovery
Jul 6, 2026
Merged

lvca merged 3 commits into
mainfrom
worktree-fix-4696-grpc-channel-recovery

Conversation

@lvca

@lvca lvca commented Jul 6, 2026

Copy link
Copy Markdown
Member

…el (Gap 1)

Closes the remaining Gap 1 from issue #4696: after a follower restarts with a new address (e.g. a Kubernetes pod-IP change), the leader's outbound Ratis gRPC appender channel could stay wedged on a stale/negative DNS result indefinitely, stranding the follower until a manual transferLeadership. Ratis's own error path only calls GrpcServerProtocolClient.resetConnectBackoff(), which never recreates the ManagedChannel or re-resolves DNS, so the earlier fix (proactive allowlist refresh + JVM DNS TTL) was not enough on its own.

Now the leader, once a follower has stayed continuously unreachable (no successful RPC) for arcadedb.ha.peerChannelResetDuration (default 60s), closes that one follower's outbound gRPC proxy via PeerProxyMap.resetProxy(). The appender's next send rebuilds a fresh ManagedChannel against the same peer DNS name, which re-resolves to the follower's current IP and reconnects. Only the unreachable peer's channel is touched and leadership is unchanged, so there is no flapping risk - a less-disruptive automatic alternative to the manual leadership-transfer lever. Set the duration to 0 to disable.

Uses the public Ratis PeerProxyMap.resetProxy API (no reflection); the detection reuses the leader's existing per-follower unreachability signal in ClusterMonitor, fires once per unreachable streak, and re-arms on reconnect.

Tests: ClusterMonitorTest (trigger fires once after the reset duration, re-arms after reconnect, disabled when duration=0, handler required when enabled) and RaftPeerChannelResetTest (the resetProxy coupling seam, plus graceful no-op when the RPC layer is not proxy-based).

What does this PR do?

A brief description of the change being made with this pull request.

Motivation

What inspired you to submit this pull request?

Related issues

A list of issues either fixed, containing architectural discussions, otherwise relevant
for this Pull Request.

Additional Notes

Anything else we should know when reviewing?

Checklist

  • I have run the build using mvn clean package command
  • My unit tests cover both failure and success scenarios

…el (Gap 1)

Closes the remaining Gap 1 from issue #4696: after a follower restarts with a new
address (e.g. a Kubernetes pod-IP change), the leader's outbound Ratis gRPC appender
channel could stay wedged on a stale/negative DNS result indefinitely, stranding the
follower until a manual transferLeadership. Ratis's own error path only calls
GrpcServerProtocolClient.resetConnectBackoff(), which never recreates the ManagedChannel
or re-resolves DNS, so the earlier fix (proactive allowlist refresh + JVM DNS TTL) was
not enough on its own.

Now the leader, once a follower has stayed continuously unreachable (no successful RPC)
for arcadedb.ha.peerChannelResetDuration (default 60s), closes that one follower's
outbound gRPC proxy via PeerProxyMap.resetProxy(). The appender's next send rebuilds a
fresh ManagedChannel against the same peer DNS name, which re-resolves to the follower's
current IP and reconnects. Only the unreachable peer's channel is touched and leadership
is unchanged, so there is no flapping risk - a less-disruptive automatic alternative to
the manual leadership-transfer lever. Set the duration to 0 to disable.

Uses the public Ratis PeerProxyMap.resetProxy API (no reflection); the detection reuses
the leader's existing per-follower unreachability signal in ClusterMonitor, fires once per
unreachable streak, and re-arms on reconnect.

Tests: ClusterMonitorTest (trigger fires once after the reset duration, re-arms after
reconnect, disabled when duration=0, handler required when enabled) and
RaftPeerChannelResetTest (the resetProxy coupling seam, plus graceful no-op when the RPC
layer is not proxy-based).
@lvca lvca self-assigned this Jul 6, 2026
@lvca lvca added this to the 26.7.2 milestone Jul 6, 2026
@mergify

mergify Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 31 complexity

Metric Results
Complexity 31

View in Codacy

🟢 Coverage 80.00% diff coverage · -7.21% coverage variation

Metric Results
Coverage variation ✅ -7.21% coverage variation
Diff coverage ✅ 80.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (593f621) 134803 100334 74.43%
Head commit (a9961a4) 166670 (+31867) 112041 (+11707) 67.22% (-7.21%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#5020) 65 52 80.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces an automatic channel-reset recovery mechanism to handle cases where a follower's replication channel becomes wedged on stale DNS after a pod-IP change in Kubernetes. It adds a new configuration parameter arcadedb.ha.peerChannelResetDuration and updates ClusterMonitor and RaftHAServer to reset the Ratis gRPC proxy channel for continuously unreachable peers. The changes are well-tested with new unit tests. The reviewer suggested adding a defensive null check on withProxy.getProxies() in RaftHAServer.resetPeerAppenderChannel to prevent a potential NullPointerException.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +432 to +438
static boolean resetPeerAppenderChannel(final RaftServerRpc rpc, final RaftPeerId peerId) {
if (rpc instanceof RaftServerRpcWithProxy<?, ?> withProxy) {
withProxy.getProxies().resetProxy(peerId);
return true;
}
return false;
}

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.

medium

To prevent a potential NullPointerException, it is safer to perform a defensive null check on withProxy.getProxies() before invoking resetProxy(peerId). While getProxies() is typically non-null in standard Ratis implementations, adding a null check aligns with defensive programming best practices and ensures robustness.

  static boolean resetPeerAppenderChannel(final RaftServerRpc rpc, final RaftPeerId peerId) {
    if (rpc instanceof RaftServerRpcWithProxy<?, ?> withProxy) {
      final var proxies = withProxy.getProxies();
      if (proxies != null) {
        proxies.resetProxy(peerId);
        return true;
      }
    }
    return false;
  }

@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: HA/Raft auto-reset of a wedged replication channel (#4696)

Overall this is a well-scoped, well-documented fix. It reuses the existing per-follower unreachability signal in ClusterMonitor, is fully config-gated (disable with 0), uses the public Ratis PeerProxyMap.resetProxy API (no reflection), and only touches the one unreachable peer's channel, so the "no flapping" claim holds. The Javadoc on both ClusterMonitor.trackUnreachableForChannelReset and RaftHAServer.resetPeerReplicationChannel is excellent, and the testable static seam (resetPeerAppenderChannel) is a nice compromise for something that's otherwise hard to exercise without a live cluster. Nice work.

A few points worth considering:

1. Single-fire-per-streak may not be robust enough (medium)

trackUnreachableForChannelReset fires the handler at most once per unreachable streak (channelResetTriggered = true), and only re-arms after the follower becomes reachable again. If that single resetProxy doesn't heal the channel - e.g. the reset lands before the JVM's DNS cache has actually re-resolved, or the freshly-built channel also wedges - the leader never retries and the operator is back to the manual transferLeadership lever this PR was meant to replace. Since the retry would still be bounded to the one unreachable peer, there is no flapping downside to re-firing.

Consider re-arming periodically while the streak continues, e.g. re-fire every peerChannelResetDurationMs instead of once. Turning channelResetTriggered into a lastChannelResetAtMs timestamp and gating on now - lastChannelResetAtMs >= peerChannelResetDurationMs would give defense-in-depth at essentially no risk. This is the main functional concern.

2. Silent coupling to HA_PEER_UNREACHABLE_THRESHOLD (low)

trackUnreachableForChannelReset early-returns when peerUnreachableThresholdMs <= 0, but the constructor only validates the handler against peerChannelResetDurationMs. So a config with peerChannelResetDurationMs > 0 and HA_PEER_UNREACHABLE_THRESHOLD = 0 silently disables the channel-reset recovery even though the operator explicitly enabled it. Worth either documenting this dependency in the HA_PEER_CHANNEL_RESET_DURATION config description, or logging a one-time WARNING at startup when the reset is enabled but the threshold that feeds it is disabled.

3. resetProxy runs synchronously on the lag-monitor thread (low)

resetPeerReplicationChannel -> resetProxy closes a gRPC ManagedChannel inline on the single lag-monitor thread that services every follower. Channel close is normally quick, but if it ever blocks it stalls lag monitoring for all peers for that tick. Probably negligible in practice; flagging for awareness. The try/catch in ClusterMonitor around the handler correctly prevents a throw from breaking the loop.

Test coverage

Good. ClusterMonitorTest covers the fire-once, re-arm-after-reconnect, disabled-when-0, and handler-required-when-enabled cases; RaftPeerChannelResetTest covers both the proxy-based and non-proxy (graceful no-op) branches of the seam. If you adopt the periodic re-fire from point 1, add a test asserting a second fire within the same unreachable streak. An end-to-end test simulating a pod-IP change would be ideal but is understandably out of scope here.

Nits

  • The timing semantics are effectively HA_PEER_UNREACHABLE_THRESHOLD (to detect) + HA_PEER_CHANNEL_RESET_DURATION (to persist) before the reset fires (~70s with defaults), since the streak clock starts at the first unreachable tick. That matches the docs closely enough, just noting it for anyone tuning the values.

…derChannel

Address Gemini review on PR #5020: guard against a null PeerProxyMap before calling
resetProxy() so a proxy-based RPC whose proxy map is not yet available is a safe no-op
instead of a potential NPE. Add a regression test for the null-proxies path.
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: HA/Raft auto-reset of a follower wedged replication channel (issue 4696)

Overall this is a well-scoped, well-documented fix. The single-peer channel reset (vs. a full transferLeadership) is the right lever, the public PeerProxyMap.resetProxy API avoids reflection, the disable switch (=0) is a good safety valve, and the tests cover the streak fire-once / re-arm / disabled / handler-required cases plus the Ratis seam. The Javadoc and release note are excellent.

A few points worth considering:

1. The reset is single-shot per streak - a failed reset can leave the follower stranded (the exact failure mode being fixed).
In trackUnreachableForChannelReset, channelResetTriggered is set true on the first fire and only re-armed when the follower becomes reachable again. If that one resetProxy does NOT heal the channel (e.g. the appender rebuilds against a JVM-level InetAddress still inside its positive-cache TTL, or the new channel again resolves stale), the follower stays continuously unreachable, the streak never ends, and no further reset is ever attempted. That reproduces the stranded-until-manual-transferLeadership symptom this PR set out to eliminate. Consider a bounded periodic re-reset while still unreachable instead of a strict one-shot - e.g. after firing, re-arm the timer (state.channelUnreachableSinceMs = now) so it retries every peerChannelResetDurationMs, optionally with a cap on attempts. Small change, and it makes the recovery robust to a first attempt that does not stick.

2. Implicit coupling to HA_PEER_UNREACHABLE_THRESHOLD.
trackUnreachableForChannelReset early-returns when peerUnreachableThresholdMs is 0 or less. So setting arcadedb.ha.peerUnreachableThreshold=0 (a knob primarily for the narrative) silently disables the channel-reset recovery even when peerChannelResetDuration is greater than 0. This is documented indirectly in the config description, but it is a non-obvious dependency. A one-line WARNING at construction when peerChannelResetDurationMs > 0 and peerUnreachableThresholdMs is 0 or less would make the misconfiguration visible.

3. ClusterMonitor logs the reset at WARNING even when the handler is a no-op.
ClusterMonitor logs resetting its replication channel at WARNING BEFORE invoking the handler. When resetPeerAppenderChannel returns false (RPC not proxy-based), RaftHAServer logs the actual outcome at FINE. So in that case the operator sees a WARNING claiming a reset happened while it was actually a no-op. Minor, but the announcement slightly over-promises relative to what occurred. Also note the two WARNING lines per successful reset (one from the monitor, one from the server) are somewhat redundant.

4. Minor: raftServer read from the lag-monitor thread.
resetPeerReplicationChannel reads the non-volatile raftServer field from the ClusterMonitor thread (it is reassigned during recovery on another thread). The local capture plus null-check is fine and consistent with existing patterns in this class, so this is low-risk, just noting it.

Nits.
resetPeerReplicationChannel guards with isLeader()/shutdownRequested but that instance path is not unit-tested (understandably, it needs a live cluster). The static seam coverage is good; consider a follow-up integration test that exercises an actual pod-IP change end-to-end if feasible.

Nothing here is blocking - point 1 is the one I would most encourage addressing, since a single failed reset re-introduces the stranding this PR aims to prevent.

… + log clarity

Address review feedback on PR #5020:

1. Single-shot reset could re-strand the follower. If the first resetProxy did not heal
   the channel (e.g. the rebuilt channel re-resolves stale DNS while the JVM positive-cache
   TTL has not expired), the streak never ended and no further reset was attempted -
   reproducing the stranded-until-manual-transferLeadership symptom this fix targets. The
   reset is now retried once per peerChannelResetDuration while the follower stays
   unreachable, bounded by CHANNEL_RESET_MAX_ATTEMPTS (5); after the cap the monitor gives
   up and logs once (SEVERE) for operator intervention. The counter re-arms on reconnect.
   An in-progress reconnection is not disrupted: a follower that returns within an interval
   clears the streak and is never reset.

2. Implicit coupling to peerUnreachableThreshold was silent. Setting
   arcadedb.ha.peerUnreachableThreshold=0 disabled the channel reset even with
   peerChannelResetDuration > 0. ClusterMonitor now logs a WARNING at construction when the
   reset is enabled but its unreachable signal is disabled.

3. Over-promising WARNING. ClusterMonitor logged "resetting" at WARNING before invoking the
   handler, so a no-op (non-proxy RPC) still announced a reset, and a success logged two
   WARNINGs (monitor + server). The monitor now announces intent ("triggering ... attempt
   N/M"), RaftHAServer confirms a success at FINE, and surfaces the rare no-op at WARNING -
   one operator-facing WARNING per reset.

Tests: rewrote the sustained-unreachability test for periodic retry, added the give-up cap
test and the misconfiguration-warning tests.
@codecov

codecov Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 78.46154% with 14 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.46%. Comparing base (593f621) to head (a9961a4).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
...java/com/arcadedb/server/ha/raft/RaftHAServer.java 41.17% 10 Missing ⚠️
...va/com/arcadedb/server/ha/raft/ClusterMonitor.java 91.30% 3 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #5020      +/-   ##
============================================
+ Coverage     65.44%   65.46%   +0.01%     
- Complexity      821      839      +18     
============================================
  Files          1687     1687              
  Lines        134803   134867      +64     
  Branches      28824    28836      +12     
============================================
+ Hits          88226    88291      +65     
  Misses        34506    34506              
+ Partials      12071    12070       -1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@lvca
lvca merged commit cd0a3cc into main Jul 6, 2026
14 of 15 checks passed
@lvca
lvca deleted the worktree-fix-4696-grpc-channel-recovery branch July 6, 2026 18:11
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…derChannel

Address Gemini review on PR #5020: guard against a null PeerProxyMap before calling
resetProxy() so a proxy-based RPC whose proxy map is not yet available is a safe no-op
instead of a potential NPE. Add a regression test for the null-proxies path.

(cherry picked from commit d3e68de)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
… + log clarity

Address review feedback on PR #5020:

1. Single-shot reset could re-strand the follower. If the first resetProxy did not heal
   the channel (e.g. the rebuilt channel re-resolves stale DNS while the JVM positive-cache
   TTL has not expired), the streak never ended and no further reset was attempted -
   reproducing the stranded-until-manual-transferLeadership symptom this fix targets. The
   reset is now retried once per peerChannelResetDuration while the follower stays
   unreachable, bounded by CHANNEL_RESET_MAX_ATTEMPTS (5); after the cap the monitor gives
   up and logs once (SEVERE) for operator intervention. The counter re-arms on reconnect.
   An in-progress reconnection is not disrupted: a follower that returns within an interval
   clears the streak and is never reset.

2. Implicit coupling to peerUnreachableThreshold was silent. Setting
   arcadedb.ha.peerUnreachableThreshold=0 disabled the channel reset even with
   peerChannelResetDuration > 0. ClusterMonitor now logs a WARNING at construction when the
   reset is enabled but its unreachable signal is disabled.

3. Over-promising WARNING. ClusterMonitor logged "resetting" at WARNING before invoking the
   handler, so a no-op (non-proxy RPC) still announced a reset, and a success logged two
   WARNINGs (monitor + server). The monitor now announces intent ("triggering ... attempt
   N/M"), RaftHAServer confirms a success at FINE, and surfaces the rare no-op at WARNING -
   one operator-facing WARNING per reset.

Tests: rewrote the sustained-unreachability test for periodic retry, added the give-up cap
test and the misconfiguration-warning tests.

(cherry picked from commit a9961a4)
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.

1 participant