Skip to content

fix: read and write leader time out of lock #1192

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

fedtye
Copy link

@fedtye fedtye commented Jun 7, 2025

Motivation:

When appendEntry takes time more than electiontimeout, election-timer would block in writer lock and then dectect leader timeout.

Modification:

It's no matter to write and read leader timestamp out of lock

  1. election-timer read leadertimestamp out of lock
  2. appendentry handler write leadertimestamp out of lock

Result:

Summary by CodeRabbit

  • Refactor
    • Improved performance and responsiveness by moving validation checks and early returns outside of critical sections, reducing unnecessary locking during election timeout handling and append entries processing.

Copy link

sofastack-cla bot commented Jun 7, 2025

Hi @fedtye, welcome to SOFAStack community, Please sign Contributor License Agreement!

After you signed CLA, we will automatically sync the status of this pull request in 3 minutes.

Copy link
Contributor

coderabbitai bot commented Jun 7, 2025

Walkthrough

The changes reorganize the control flow in the NodeImpl.java file by moving validation checks and early return logic outside of write locks in the handleElectionTimeout and handleAppendEntriesRequest methods. This adjustment ensures that unnecessary locking is avoided when certain conditions are met, streamlining execution and reducing lock contention.

Changes

File(s) Change Summary
jraft-core/.../NodeImpl.java Moved validation and early return logic outside write locks in handleElectionTimeout and handleAppendEntriesRequest methods; adjusted update of last leader timestamp. No API or signature changes.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant NodeImpl
    participant Lock

    Client->>NodeImpl: handleAppendEntriesRequest(request)
    alt Node inactive or invalid server ID or stale term
        NodeImpl-->>Client: Early error response (no lock)
    else
        NodeImpl->>Lock: Acquire write lock
        NodeImpl->>NodeImpl: Check term/state, step down if needed
        NodeImpl->>NodeImpl: Verify leader identity, handle snapshot/log
        NodeImpl->>Lock: Release write lock
        NodeImpl-->>Client: Response
    end
Loading

Poem

A lock avoided, a check moved ahead,
The code now flows with lighter tread.
Fewer waits for the herd,
More clarity conferred.
In the warren of threads, less dread!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ast-grep (0.38.1)
jraft-core/src/main/java/com/alipay/sofa/jraft/core/NodeImpl.java
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (2)
jraft-core/src/main/java/com/alipay/sofa/jraft/core/NodeImpl.java (2)

177-177: 🛠️ Refactor suggestion

Use AtomicLong for thread-safe timestamp operations

The volatile keyword alone is insufficient for the concurrent read/write pattern introduced by this PR. While it ensures visibility, it doesn't prevent race conditions when handleElectionTimeout reads the timestamp while handleAppendEntriesRequest writes to it.

-private volatile long                                                  lastLeaderTimestamp;
+private final AtomicLong                                              lastLeaderTimestamp = new AtomicLong();

And update the accessor methods:

 private void updateLastLeaderTimestamp(final long lastLeaderTimestamp) {
-    this.lastLeaderTimestamp = lastLeaderTimestamp;
+    this.lastLeaderTimestamp.set(lastLeaderTimestamp);
 }

Also update reads in isCurrentLeaderValid() and checkLeaderLease():

 private boolean isCurrentLeaderValid() {
-    return Utils.monotonicMs() - this.lastLeaderTimestamp < this.options.getElectionTimeoutMs();
+    return Utils.monotonicMs() - this.lastLeaderTimestamp.get() < this.options.getElectionTimeoutMs();
 }

Also applies to: 1784-1786


552-552: 💡 Verification agent

🧩 Analysis chain

Ensure consistent usage of atomic timestamp operations

After converting lastLeaderTimestamp to AtomicLong, ensure all usages are updated:

Also applies to: 1316-1316, 1776-1778, 2293-2293


🏁 Script executed:

#!/bin/bash
# Find all references to lastLeaderTimestamp to ensure complete migration
rg -n "lastLeaderTimestamp" --type java

Length of output: 822


Migrate lastLeaderTimestamp to AtomicLong

It looks like lastLeaderTimestamp is still declared as a volatile long and is being accessed/updated directly. To complete the migration to AtomicLong, update the following in NodeImpl.java:

• Declaration (around line 177):

// before
private volatile long lastLeaderTimestamp;
// after
private final AtomicLong lastLeaderTimestamp = new AtomicLong();

• Constructor (where you call updateLastLeaderTimestamp):

- updateLastLeaderTimestamp(Utils.monotonicMs());
+ this.lastLeaderTimestamp.set(Utils.monotonicMs());

• updateLastLeaderTimestamp method (lines 1784–1785):

- private void updateLastLeaderTimestamp(final long lastLeaderTimestamp) {
-     this.lastLeaderTimestamp = lastLeaderTimestamp;
- }
+ private void updateLastLeaderTimestamp(final long ts) {
+     this.lastLeaderTimestamp.set(ts);
+ }

• All direct reads (lines 1777 and 1781):

- return monotonicNowMs - this.lastLeaderTimestamp < ...
+ return monotonicNowMs - this.lastLeaderTimestamp.get() < ...

Ensuring these changes will guarantee atomic, thread-safe timestamp updates and reads.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eda479b and 0b5011b.

📒 Files selected for processing (1)
  • jraft-core/src/main/java/com/alipay/sofa/jraft/core/NodeImpl.java (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
jraft-core/src/main/java/com/alipay/sofa/jraft/core/NodeImpl.java (3)
jraft-core/src/main/java/com/alipay/sofa/jraft/util/RpcFactoryHelper.java (1)
  • RpcFactoryHelper (25-37)
jraft-core/src/main/java/com/alipay/sofa/jraft/rpc/RpcRequests.java (1)
  • AppendEntriesResponse (10068-10915)
jraft-core/src/main/java/com/alipay/sofa/jraft/util/Utils.java (1)
  • Utils (59-527)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: sca
🔇 Additional comments (1)
jraft-core/src/main/java/com/alipay/sofa/jraft/core/NodeImpl.java (1)

620-625: ⚠️ Potential issue

Critical: Thread safety violation - reading shared state without synchronization

Reading this.state and calling isCurrentLeaderValid() (which reads lastLeaderTimestamp) without holding any lock creates race conditions. The state could change between the check and when the write lock is acquired, and lastLeaderTimestamp could be read while being written by another thread.

Consider using a read lock for these checks:

 private void handleElectionTimeout() {
-    if (this.state != State.STATE_FOLLOWER) {
-        return;
-    }
-    if (isCurrentLeaderValid()) {
-        return;
-    }
+    this.readLock.lock();
+    try {
+        if (this.state != State.STATE_FOLLOWER) {
+            return;
+        }
+        if (isCurrentLeaderValid()) {
+            return;
+        }
+    } finally {
+        this.readLock.unlock();
+    }
     boolean doUnlock = true;
     this.writeLock.lock();

Likely an incorrect or invalid review comment.

Comment on lines +1938 to +1965
if (!this.state.isActive()) {
LOG.warn("Node {} is not in active state, currTerm={}.", getNodeId(), this.currTerm);
return RpcFactoryHelper //
.responseFactory() //
.newResponse(AppendEntriesResponse.getDefaultInstance(), RaftError.EINVAL,
"Node %s is not in active state, state %s.", getNodeId(), this.state.name());
}

final PeerId serverId = new PeerId();
if (!serverId.parse(request.getServerId())) {
LOG.warn("Node {} received AppendEntriesRequest from {} serverId bad format.", getNodeId(),
request.getServerId());
return RpcFactoryHelper //
.responseFactory() //
.newResponse(AppendEntriesResponse.getDefaultInstance(), RaftError.EINVAL,
"Parse serverId failed: %s.", request.getServerId());
}

// Check stale term
if (request.getTerm() < this.currTerm) {
LOG.warn("Node {} ignore stale AppendEntriesRequest from {}, term={}, currTerm={}.", getNodeId(),
request.getServerId(), request.getTerm(), this.currTerm);
return AppendEntriesResponse.newBuilder() //
.setSuccess(false) //
.setTerm(this.currTerm) //
.build();
}
updateLastLeaderTimestamp(Utils.monotonicMs());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Critical: Multiple thread safety violations in lock-free validation

Moving these checks outside the write lock introduces several race conditions:

  1. Reading this.state without synchronization (line 1938)
  2. Reading this.currTerm without synchronization (line 1957)
  3. Writing to lastLeaderTimestamp without synchronization (line 1965)

These fields are modified under write locks elsewhere, creating data races. The state and term could change between validation and lock acquisition, leading to incorrect behavior.

To fix this while still addressing the original timeout issue, consider one of these approaches:

Option 1: Use atomic operations for timestamp

// Declare as AtomicLong
private final AtomicLong lastLeaderTimestamp = new AtomicLong();

// In handleAppendEntriesRequest (before lock)
lastLeaderTimestamp.set(Utils.monotonicMs());

// In isCurrentLeaderValid
return Utils.monotonicMs() - lastLeaderTimestamp.get() < this.options.getElectionTimeoutMs();

Option 2: Use read lock for validation

+    this.readLock.lock();
+    try {
         if (!this.state.isActive()) {
             LOG.warn("Node {} is not in active state, currTerm={}.", getNodeId(), this.currTerm);
             return RpcFactoryHelper //
                 .responseFactory() //
                 .newResponse(AppendEntriesResponse.getDefaultInstance(), RaftError.EINVAL,
                     "Node %s is not in active state, state %s.", getNodeId(), this.state.name());
         }
+    } finally {
+        this.readLock.unlock();
+    }

     final PeerId serverId = new PeerId();
     if (!serverId.parse(request.getServerId())) {
         // ... parsing validation (safe without lock) ...
     }

+    this.readLock.lock();
+    try {
         // Check stale term
         if (request.getTerm() < this.currTerm) {
             // ... stale term handling ...
         }
+    } finally {
+        this.readLock.unlock();
+    }
     updateLastLeaderTimestamp(Utils.monotonicMs());
🤖 Prompt for AI Agents
In jraft-core/src/main/java/com/alipay/sofa/jraft/core/NodeImpl.java around
lines 1938 to 1965, the code reads and writes shared fields this.state,
this.currTerm, and lastLeaderTimestamp without synchronization, causing thread
safety issues and race conditions. To fix this, either convert
lastLeaderTimestamp to an AtomicLong and update it atomically outside the write
lock, or perform all validation reads under a read lock to ensure consistent and
thread-safe access to these fields. Choose one approach and apply it
consistently to prevent data races while maintaining the intended timeout
behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant