Skip to content

Commit

Permalink
Fix minvotes for even number of servers
Browse files Browse the repository at this point in the history
  • Loading branch information
resetius committed Dec 11, 2023
1 parent 88f8cbc commit 81d3505
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/raft.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ TVolatileState& TVolatileState::SetCommitIndex(int index)
TRaft::TRaft(int node, const TNodeDict& nodes)
: Id(node)
, Nodes(nodes)
, MinVotes((nodes.size()+2)/2)
, MinVotes((nodes.size()+2+nodes.size()%2)/2)
, Npeers(nodes.size())
, Nservers(nodes.size()+1)
, State(std::make_unique<TState>())
Expand Down
28 changes: 28 additions & 0 deletions test/test_raft.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,33 @@ void test_initial(void**) {
assert_true(raft->CurrentStateName() == EState::FOLLOWER);
}

void test_numbers(void**) {
auto raft = MakeRaft({}, 3);
assert_int_equal(raft->GetMinVotes(), 2);
assert_int_equal(raft->GetNservers(), 3);
assert_int_equal(raft->GetNpeers(), 2);

raft = MakeRaft({}, 2);
assert_int_equal(raft->GetMinVotes(), 2);
assert_int_equal(raft->GetNservers(), 2);
assert_int_equal(raft->GetNpeers(), 1);

raft = MakeRaft({}, 1);
assert_int_equal(raft->GetMinVotes(), 1);
assert_int_equal(raft->GetNservers(), 1);
assert_int_equal(raft->GetNpeers(), 0);

raft = MakeRaft({}, 5);
assert_int_equal(raft->GetMinVotes(), 3);
assert_int_equal(raft->GetNservers(), 5);
assert_int_equal(raft->GetNpeers(), 4);

raft = MakeRaft({}, 10);
assert_int_equal(raft->GetMinVotes(), 6);
assert_int_equal(raft->GetNservers(), 10);
assert_int_equal(raft->GetNpeers(), 9);
}

void test_become(void**) {
auto raft = MakeRaft();
assert_true(raft->CurrentStateName() == EState::FOLLOWER);
Expand Down Expand Up @@ -597,6 +624,7 @@ int main() {
cmocka_unit_test(test_message_cast),
cmocka_unit_test(test_message_send_recv),
cmocka_unit_test(test_initial),
cmocka_unit_test(test_numbers),
cmocka_unit_test(test_become),
cmocka_unit_test(test_become_same_func),
cmocka_unit_test(test_follower_to_candidate_on_timeout),
Expand Down

0 comments on commit 81d3505

Please sign in to comment.