Skip to content

Commit

Permalink
RAFT node responds to VoteRequest with outdated Term (#5021)
Browse files Browse the repository at this point in the history
A node's Term may be increased during handling of a VoteRequest. When
that was the case, the node was responding with a stale Term.

Example trace:

```
[DBG] RAFT [S1Nunr6R - S-R3F-5xgoWjQW] Received a voteRequest &{term:27 lastTerm:26 lastIndex:46 candidate:yrzKKRBu reply:$NRG.R.OHF7VRUO}
[DBG] RAFT [S1Nunr6R - S-R3F-5xgoWjQW] Stepping down from leader, detected higher term: 27 vs 26
[DBG] RAFT [S1Nunr6R - S-R3F-5xgoWjQW] Stepping down
[DBG] RAFT [S1Nunr6R - S-R3F-5xgoWjQW] Switching to follower
[DBG] RAFT [S1Nunr6R - S-R3F-5xgoWjQW] Sending a voteResponse &{term:26 peer:S1Nunr6R granted:true} -> "$NRG.R.OHF7VRUO"
```
This is handled correctly except VoteResponse in the last log line
should be sending back Term 27, not 26.

Signed-off-by: Your Name <marco@nats.io>
  • Loading branch information
derekcollison committed Feb 1, 2024
2 parents 65d4f14 + 34d70e4 commit ba14d03
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
4 changes: 4 additions & 0 deletions server/raft.go
Original file line number Diff line number Diff line change
Expand Up @@ -3953,6 +3953,10 @@ func (n *raft) processVoteRequest(vr *voteRequest) error {
n.resetElect(randCampaignTimeout())
}
}

// Term might have changed, make sure response has the most current
vresp.term = n.term

n.Unlock()

n.sendReply(vr.reply, vresp.encode())
Expand Down
12 changes: 5 additions & 7 deletions server/raft_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,15 +273,13 @@ func TestNRGSimpleElection(t *testing.T) {
re := decodeVoteResponse(msg.Data)
require_True(t, re != nil)

// The new term hasn't started yet, so the vote responses
// should contain the term from before the election. It is
// possible that candidates are listening to this to work
// out if they are in previous terms.
require_Equal(t, re.term, vr.lastTerm)
require_Equal(t, re.term, startTerm)

// The vote should have been granted.
require_Equal(t, re.granted, true)

// The node granted the vote, therefore the term in the vote
// response should have advanced as well.
require_Equal(t, re.term, vr.term)
require_Equal(t, re.term, startTerm+1)
}

// Everyone in the group should have voted for our candidate
Expand Down

0 comments on commit ba14d03

Please sign in to comment.