DistributedApplications: deterministic replicated KV core with quorum commits, quorum reads and crash/partition histories (P-DISTRIBUTED-04 foundation)
This commit is contained in:
1 parent
9ba4738415
commit
cfa860f944
4 files changed
+736
No files matched your search
@@ -11,6 +11,7 @@ find_package(Void CONFIG REQUIRED COMPONENTS Functional Net)
|
|||||||
|
|
||||||
add_library(distributed_host_graph STATIC
|
add_library(distributed_host_graph STATIC
|
||||||
src/host_graph.cpp
|
src/host_graph.cpp
|
||||||
|
src/replicated_kv.cpp
|
||||||
src/single_node.cpp)
|
src/single_node.cpp)
|
||||||
target_include_directories(distributed_host_graph PUBLIC include)
|
target_include_directories(distributed_host_graph PUBLIC include)
|
||||||
target_link_libraries(distributed_host_graph PUBLIC Void::Functional Void::Net)
|
target_link_libraries(distributed_host_graph PUBLIC Void::Functional Void::Net)
|
||||||
@@ -21,6 +22,10 @@ target_link_libraries(distributed_host_graph_test PRIVATE distributed_host_graph
|
|||||||
add_executable(distributed_single_node_test tests/single_node_test.cpp)
|
add_executable(distributed_single_node_test tests/single_node_test.cpp)
|
||||||
target_link_libraries(distributed_single_node_test PRIVATE distributed_host_graph)
|
target_link_libraries(distributed_single_node_test PRIVATE distributed_host_graph)
|
||||||
|
|
||||||
|
add_executable(distributed_replicated_kv_test tests/replicated_kv_test.cpp)
|
||||||
|
target_link_libraries(distributed_replicated_kv_test PRIVATE distributed_host_graph)
|
||||||
|
|
||||||
enable_testing()
|
enable_testing()
|
||||||
add_test(NAME distributed_host_graph COMMAND distributed_host_graph_test)
|
add_test(NAME distributed_host_graph COMMAND distributed_host_graph_test)
|
||||||
add_test(NAME distributed_single_node COMMAND distributed_single_node_test)
|
add_test(NAME distributed_single_node COMMAND distributed_single_node_test)
|
||||||
|
add_test(NAME distributed_replicated_kv COMMAND distributed_replicated_kv_test)
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "distributed_host/host_graph.hpp"
|
||||||
|
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace DistributedHost
|
||||||
|
{
|
||||||
|
/// One replicated log entry. A missing value is an erase.
|
||||||
|
struct KvLogEntry {
|
||||||
|
std::uint64_t term{0};
|
||||||
|
std::uint64_t index{0};
|
||||||
|
std::string key;
|
||||||
|
std::optional<std::string> value;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class KvWriteOutcome : std::uint8_t {
|
||||||
|
/// Majority-committed and applied: the only durable reply.
|
||||||
|
Applied,
|
||||||
|
/// The entry may exist locally but no majority acknowledged it. It is
|
||||||
|
/// not durable and a later leader may overwrite it.
|
||||||
|
NoQuorum,
|
||||||
|
NotLeader,
|
||||||
|
NodeDown
|
||||||
|
};
|
||||||
|
|
||||||
|
struct KvWriteReply {
|
||||||
|
KvWriteOutcome outcome{KvWriteOutcome::NoQuorum};
|
||||||
|
std::uint64_t index{0};
|
||||||
|
std::uint64_t term{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Immutable inspection copy of one voter.
|
||||||
|
struct KvNodeSnapshot {
|
||||||
|
std::string id;
|
||||||
|
bool alive{true};
|
||||||
|
Role role{Role::Follower};
|
||||||
|
std::uint64_t term{0};
|
||||||
|
std::uint64_t commit_index{0};
|
||||||
|
std::uint64_t applied_index{0};
|
||||||
|
std::size_t log_size{0};
|
||||||
|
std::optional<std::string> leader;
|
||||||
|
std::map<std::string, std::string, std::less<>> kv;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Deterministic single-group replicated key-value cluster.
|
||||||
|
///
|
||||||
|
/// Models the safety rules the reference distributed KV depends on
|
||||||
|
/// without sockets, threads or clocks:
|
||||||
|
/// * a write is replied Applied only after a majority of matching acks
|
||||||
|
/// (durable reply), never on local append alone;
|
||||||
|
/// * a leader in a minority cannot commit and is stepped down when it
|
||||||
|
/// observes a higher term;
|
||||||
|
/// * a consistent read is served only by a leader that confirms a
|
||||||
|
/// majority in its term and has applied every committed entry;
|
||||||
|
/// * committed entries survive crash/restart and are never overwritten.
|
||||||
|
///
|
||||||
|
/// The simulator is single-threaded; tests drive elections, proposals,
|
||||||
|
/// partitions and crashes explicitly.
|
||||||
|
class ReplicatedKvCluster
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
explicit ReplicatedKvCluster(std::vector<std::string> voters);
|
||||||
|
|
||||||
|
[[nodiscard]] const std::vector<std::string>& voters() const noexcept
|
||||||
|
{
|
||||||
|
return m_voters;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request a majority election for `candidate` in a new term.
|
||||||
|
/// Fails without changing the cluster when no majority is
|
||||||
|
/// reachable.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
elect(std::string_view candidate);
|
||||||
|
|
||||||
|
/// Append and replicate one command through `leader`. The reply is
|
||||||
|
/// Applied only when a majority acknowledged the matching entry.
|
||||||
|
[[nodiscard]] KvWriteReply propose(std::string_view leader,
|
||||||
|
std::string key,
|
||||||
|
std::optional<std::string> value);
|
||||||
|
|
||||||
|
/// Replicate the leader's log and commit index without appending a
|
||||||
|
/// new command (the AppendEntries heartbeat). Followers in a newer
|
||||||
|
/// term step the leader down.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
heartbeat(std::string_view leader);
|
||||||
|
|
||||||
|
/// Linearizable read: leader-only, majority-confirmed in the
|
||||||
|
/// leader's term, after applying every committed entry.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
|
||||||
|
quorum_read(std::string_view node, std::string_view key);
|
||||||
|
|
||||||
|
/// Crash/restart keep the durable log, term and vote.
|
||||||
|
void crash(std::string_view node);
|
||||||
|
void restart(std::string_view node);
|
||||||
|
|
||||||
|
/// Move a node to a partition id. Nodes only communicate within
|
||||||
|
/// the same partition id.
|
||||||
|
void set_partition(std::string_view node, int partition);
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<KvNodeSnapshot>
|
||||||
|
snapshot(std::string_view node) const;
|
||||||
|
|
||||||
|
/// Highest commit index across live nodes.
|
||||||
|
[[nodiscard]] std::uint64_t committed_index() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Node {
|
||||||
|
std::string id;
|
||||||
|
bool alive{true};
|
||||||
|
int partition{0};
|
||||||
|
Role role{Role::Follower};
|
||||||
|
std::uint64_t term{0};
|
||||||
|
std::optional<std::string> voted_for;
|
||||||
|
std::optional<std::string> leader;
|
||||||
|
std::vector<KvLogEntry> log;
|
||||||
|
std::uint64_t commit_index{0};
|
||||||
|
std::uint64_t applied_index{0};
|
||||||
|
std::map<std::string, std::string, std::less<>> kv;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] Node* find(std::string_view id);
|
||||||
|
[[nodiscard]] const Node* find(std::string_view id) const;
|
||||||
|
[[nodiscard]] bool reachable(const Node& a, const Node& b) const;
|
||||||
|
[[nodiscard]] bool majority(std::size_t acks) const;
|
||||||
|
/// True when `candidate` has a log at least as up to date as `voter`.
|
||||||
|
[[nodiscard]] static bool log_up_to_date(const Node& candidate,
|
||||||
|
const Node& voter);
|
||||||
|
void apply_committed(Node& node);
|
||||||
|
/// Copy the leader's log to one reachable follower. False when the
|
||||||
|
/// follower cannot be brought in line (e.g. it is in a newer term).
|
||||||
|
[[nodiscard]] bool replicate_to(Node& leader, Node& follower);
|
||||||
|
|
||||||
|
std::vector<std::string> m_voters;
|
||||||
|
std::vector<Node> m_nodes;
|
||||||
|
};
|
||||||
|
} // namespace DistributedHost
|
||||||
@@ -0,0 +1,392 @@
|
|||||||
|
#include "distributed_host/replicated_kv.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace DistributedHost
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
[[nodiscard]] Void::Result::Error invalid(std::string message)
|
||||||
|
{
|
||||||
|
return Void::Result::Error{
|
||||||
|
Void::Result::ErrorKind::invalid_argument, std::move(message)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Error no_quorum(std::string message)
|
||||||
|
{
|
||||||
|
return Void::Result::Error{Void::Result::ErrorKind::overloaded,
|
||||||
|
std::move(message)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Error not_found(std::string message)
|
||||||
|
{
|
||||||
|
return Void::Result::Error{Void::Result::ErrorKind::not_found,
|
||||||
|
std::move(message)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Error not_leader(std::string message)
|
||||||
|
{
|
||||||
|
return Void::Result::Error{Void::Result::ErrorKind::conflict,
|
||||||
|
std::move(message)};
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
ReplicatedKvCluster::ReplicatedKvCluster(std::vector<std::string> voters)
|
||||||
|
: m_voters(std::move(voters))
|
||||||
|
{
|
||||||
|
m_nodes.reserve(m_voters.size());
|
||||||
|
for (const auto& id : m_voters) {
|
||||||
|
Node node;
|
||||||
|
node.id = id;
|
||||||
|
// Sentinel entry keeps log indices 1-based and match the entry
|
||||||
|
// index directly.
|
||||||
|
node.log.push_back(KvLogEntry{.term = 0, .index = 0});
|
||||||
|
m_nodes.push_back(std::move(node));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ReplicatedKvCluster::Node* ReplicatedKvCluster::find(std::string_view id)
|
||||||
|
{
|
||||||
|
for (auto& node : m_nodes) {
|
||||||
|
if (node.id == id) {
|
||||||
|
return &node;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ReplicatedKvCluster::Node*
|
||||||
|
ReplicatedKvCluster::find(std::string_view id) const
|
||||||
|
{
|
||||||
|
for (const auto& node : m_nodes) {
|
||||||
|
if (node.id == id) {
|
||||||
|
return &node;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ReplicatedKvCluster::reachable(const Node& a, const Node& b) const
|
||||||
|
{
|
||||||
|
return a.alive && b.alive && a.partition == b.partition;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ReplicatedKvCluster::majority(std::size_t acks) const
|
||||||
|
{
|
||||||
|
return acks > m_voters.size() / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ReplicatedKvCluster::log_up_to_date(const Node& candidate,
|
||||||
|
const Node& voter)
|
||||||
|
{
|
||||||
|
const auto& last_candidate = candidate.log.back();
|
||||||
|
const auto& last_voter = voter.log.back();
|
||||||
|
if (last_candidate.term != last_voter.term) {
|
||||||
|
return last_candidate.term > last_voter.term;
|
||||||
|
}
|
||||||
|
return last_candidate.index >= last_voter.index;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ReplicatedKvCluster::apply_committed(Node& node)
|
||||||
|
{
|
||||||
|
while (node.applied_index < node.commit_index &&
|
||||||
|
node.applied_index + 1 < node.log.size()) {
|
||||||
|
const KvLogEntry& entry = node.log[node.applied_index + 1];
|
||||||
|
if (entry.value.has_value()) {
|
||||||
|
node.kv.insert_or_assign(entry.key, *entry.value);
|
||||||
|
} else {
|
||||||
|
node.kv.erase(entry.key);
|
||||||
|
}
|
||||||
|
node.applied_index = entry.index;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
ReplicatedKvCluster::elect(std::string_view candidate)
|
||||||
|
{
|
||||||
|
Node* self = find(candidate);
|
||||||
|
if (self == nullptr) {
|
||||||
|
return std::unexpected{
|
||||||
|
not_found("ReplicatedKv: unknown voter")};
|
||||||
|
}
|
||||||
|
if (!self->alive) {
|
||||||
|
return std::unexpected{
|
||||||
|
no_quorum("ReplicatedKv: candidate is down")};
|
||||||
|
}
|
||||||
|
|
||||||
|
self->term += 1;
|
||||||
|
self->role = Role::Candidate;
|
||||||
|
self->voted_for = self->id;
|
||||||
|
self->leader.reset();
|
||||||
|
|
||||||
|
std::size_t votes = 1;
|
||||||
|
for (auto& voter : m_nodes) {
|
||||||
|
if (voter.id == self->id || !reachable(*self, voter)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (voter.term < self->term) {
|
||||||
|
voter.term = self->term;
|
||||||
|
voter.voted_for.reset();
|
||||||
|
voter.role = Role::Follower;
|
||||||
|
voter.leader.reset();
|
||||||
|
}
|
||||||
|
const bool can_vote =
|
||||||
|
voter.term == self->term && !voter.voted_for.has_value();
|
||||||
|
if (can_vote && log_up_to_date(*self, voter)) {
|
||||||
|
voter.voted_for = self->id;
|
||||||
|
++votes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!majority(votes)) {
|
||||||
|
self->role = Role::Follower;
|
||||||
|
return std::unexpected{no_quorum(
|
||||||
|
"ReplicatedKv: election did not reach a majority")};
|
||||||
|
}
|
||||||
|
self->role = Role::Leader;
|
||||||
|
self->leader = self->id;
|
||||||
|
for (auto& node : m_nodes) {
|
||||||
|
if (node.id != self->id && reachable(*self, node) &&
|
||||||
|
node.term <= self->term) {
|
||||||
|
node.leader = self->id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ReplicatedKvCluster::replicate_to(Node& leader, Node& follower)
|
||||||
|
{
|
||||||
|
if (!reachable(leader, follower)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (follower.term > leader.term) {
|
||||||
|
leader.role = Role::Follower;
|
||||||
|
leader.leader.reset();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (follower.term < leader.term) {
|
||||||
|
follower.term = leader.term;
|
||||||
|
follower.voted_for.reset();
|
||||||
|
follower.role = Role::Follower;
|
||||||
|
}
|
||||||
|
follower.leader = leader.id;
|
||||||
|
|
||||||
|
// Highest index where both logs agree, then overwrite the suffix.
|
||||||
|
std::size_t match = 0;
|
||||||
|
const std::size_t shared =
|
||||||
|
std::min(follower.log.size(), leader.log.size()) - 1;
|
||||||
|
for (std::size_t i = shared + 1; i-- > 0;) {
|
||||||
|
if (follower.log[i].term == leader.log[i].term) {
|
||||||
|
match = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
follower.log.resize(match + 1);
|
||||||
|
for (std::size_t i = match + 1; i < leader.log.size(); ++i) {
|
||||||
|
follower.log.push_back(leader.log[i]);
|
||||||
|
}
|
||||||
|
// AppendEntries carries the leader commit index: a follower that was
|
||||||
|
// behind applies everything now proven committed.
|
||||||
|
if (leader.commit_index > follower.commit_index) {
|
||||||
|
follower.commit_index = std::min(
|
||||||
|
leader.commit_index,
|
||||||
|
static_cast<std::uint64_t>(follower.log.size() - 1));
|
||||||
|
apply_committed(follower);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
KvWriteReply ReplicatedKvCluster::propose(std::string_view leader_id,
|
||||||
|
std::string key,
|
||||||
|
std::optional<std::string> value)
|
||||||
|
{
|
||||||
|
Node* leader = find(leader_id);
|
||||||
|
if (leader == nullptr || !leader->alive) {
|
||||||
|
return KvWriteReply{.outcome = KvWriteOutcome::NodeDown,
|
||||||
|
.index = 0,
|
||||||
|
.term = leader ? leader->term : 0};
|
||||||
|
}
|
||||||
|
if (leader->role != Role::Leader) {
|
||||||
|
return KvWriteReply{.outcome = KvWriteOutcome::NotLeader,
|
||||||
|
.index = 0,
|
||||||
|
.term = leader->term};
|
||||||
|
}
|
||||||
|
|
||||||
|
KvLogEntry entry;
|
||||||
|
entry.term = leader->term;
|
||||||
|
entry.index = static_cast<std::uint64_t>(leader->log.size());
|
||||||
|
entry.key = std::move(key);
|
||||||
|
entry.value = std::move(value);
|
||||||
|
leader->log.push_back(entry);
|
||||||
|
|
||||||
|
std::size_t acks = 1;
|
||||||
|
for (auto& follower : m_nodes) {
|
||||||
|
if (follower.id == leader->id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (replicate_to(*leader, follower)) {
|
||||||
|
++acks;
|
||||||
|
}
|
||||||
|
if (leader->role != Role::Leader) {
|
||||||
|
// A higher term was observed: the local append is not durable.
|
||||||
|
return KvWriteReply{.outcome = KvWriteOutcome::NotLeader,
|
||||||
|
.index = entry.index,
|
||||||
|
.term = leader->term};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!majority(acks)) {
|
||||||
|
// Uncommitted: a later leader may truncate it. Never applied.
|
||||||
|
return KvWriteReply{.outcome = KvWriteOutcome::NoQuorum,
|
||||||
|
.index = entry.index,
|
||||||
|
.term = leader->term};
|
||||||
|
}
|
||||||
|
|
||||||
|
leader->commit_index = entry.index;
|
||||||
|
apply_committed(*leader);
|
||||||
|
for (auto& node : m_nodes) {
|
||||||
|
if (node.id == leader->id || !reachable(*leader, node)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Only nodes whose log matches the committed entry may apply it.
|
||||||
|
if (node.log.size() > entry.index &&
|
||||||
|
node.log[entry.index].term == entry.term) {
|
||||||
|
node.commit_index =
|
||||||
|
std::max(node.commit_index, entry.index);
|
||||||
|
apply_committed(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return KvWriteReply{
|
||||||
|
.outcome = KvWriteOutcome::Applied,
|
||||||
|
.index = entry.index,
|
||||||
|
.term = leader->term};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
ReplicatedKvCluster::heartbeat(std::string_view leader_id)
|
||||||
|
{
|
||||||
|
Node* leader = find(leader_id);
|
||||||
|
if (leader == nullptr) {
|
||||||
|
return std::unexpected{not_found("ReplicatedKv: unknown voter")};
|
||||||
|
}
|
||||||
|
if (!leader->alive || leader->role != Role::Leader) {
|
||||||
|
return std::unexpected{
|
||||||
|
not_leader("ReplicatedKv: heartbeat requires a leader")};
|
||||||
|
}
|
||||||
|
for (auto& follower : m_nodes) {
|
||||||
|
if (follower.id != leader->id) {
|
||||||
|
(void)replicate_to(*leader, follower);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (leader->role != Role::Leader) {
|
||||||
|
return std::unexpected{not_leader(
|
||||||
|
"ReplicatedKv: stepped down after a higher term")};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<std::string>>
|
||||||
|
ReplicatedKvCluster::quorum_read(std::string_view node_id,
|
||||||
|
std::string_view key)
|
||||||
|
{
|
||||||
|
Node* node = find(node_id);
|
||||||
|
if (node == nullptr) {
|
||||||
|
return std::unexpected{not_found("ReplicatedKv: unknown voter")};
|
||||||
|
}
|
||||||
|
if (!node->alive) {
|
||||||
|
return std::unexpected{
|
||||||
|
no_quorum("ReplicatedKv: node is down")};
|
||||||
|
}
|
||||||
|
if (node->role != Role::Leader) {
|
||||||
|
return std::unexpected{not_leader(
|
||||||
|
"ReplicatedKv: consistent reads require a leader")};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Confirm leadership in this term with a majority heartbeat.
|
||||||
|
std::size_t acks = 1;
|
||||||
|
for (auto& peer : m_nodes) {
|
||||||
|
if (peer.id == node->id || !reachable(*node, peer)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (peer.term > node->term) {
|
||||||
|
node->role = Role::Follower;
|
||||||
|
node->leader.reset();
|
||||||
|
return std::unexpected{not_leader(
|
||||||
|
"ReplicatedKv: stepped down after a higher term")};
|
||||||
|
}
|
||||||
|
++acks;
|
||||||
|
}
|
||||||
|
if (!majority(acks)) {
|
||||||
|
return std::unexpected{no_quorum(
|
||||||
|
"ReplicatedKv: no majority to confirm the read")};
|
||||||
|
}
|
||||||
|
|
||||||
|
// A quorum-confirmed leader has every committed entry; apply them.
|
||||||
|
apply_committed(*node);
|
||||||
|
const auto found = node->kv.find(key);
|
||||||
|
if (found == node->kv.end()) {
|
||||||
|
return std::optional<std::string>{};
|
||||||
|
}
|
||||||
|
return std::optional<std::string>{found->second};
|
||||||
|
}
|
||||||
|
|
||||||
|
void ReplicatedKvCluster::crash(std::string_view node_id)
|
||||||
|
{
|
||||||
|
if (Node* node = find(node_id); node != nullptr) {
|
||||||
|
node->alive = false;
|
||||||
|
node->role = Role::Follower;
|
||||||
|
node->leader.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ReplicatedKvCluster::restart(std::string_view node_id)
|
||||||
|
{
|
||||||
|
if (Node* node = find(node_id); node != nullptr) {
|
||||||
|
// Log, term, vote and applied state are durable.
|
||||||
|
node->alive = true;
|
||||||
|
node->role = Role::Follower;
|
||||||
|
node->leader.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ReplicatedKvCluster::set_partition(std::string_view node_id,
|
||||||
|
int partition)
|
||||||
|
{
|
||||||
|
if (Node* node = find(node_id); node != nullptr) {
|
||||||
|
node->partition = partition;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<KvNodeSnapshot>
|
||||||
|
ReplicatedKvCluster::snapshot(std::string_view node_id) const
|
||||||
|
{
|
||||||
|
const Node* node = find(node_id);
|
||||||
|
if (node == nullptr) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
KvNodeSnapshot out;
|
||||||
|
out.id = node->id;
|
||||||
|
out.alive = node->alive;
|
||||||
|
out.role = node->role;
|
||||||
|
out.term = node->term;
|
||||||
|
out.commit_index = node->commit_index;
|
||||||
|
out.applied_index = node->applied_index;
|
||||||
|
out.log_size = node->log.size();
|
||||||
|
out.leader = node->leader;
|
||||||
|
out.kv = node->kv;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::uint64_t ReplicatedKvCluster::committed_index() const
|
||||||
|
{
|
||||||
|
std::uint64_t highest = 0;
|
||||||
|
for (const auto& node : m_nodes) {
|
||||||
|
if (node.alive) {
|
||||||
|
highest = std::max(highest, node.commit_index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return highest;
|
||||||
|
}
|
||||||
|
} // namespace DistributedHost
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
#include "distributed_host/replicated_kv.hpp"
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
using namespace DistributedHost;
|
||||||
|
|
||||||
|
ReplicatedKvCluster cluster()
|
||||||
|
{
|
||||||
|
return ReplicatedKvCluster{{"a", "b", "c"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
void leader_commits_with_a_majority()
|
||||||
|
{
|
||||||
|
auto kv = cluster();
|
||||||
|
assert(kv.elect("a").has_value());
|
||||||
|
const auto reply = kv.propose("a", "key", std::string{"value"});
|
||||||
|
assert(reply.outcome == KvWriteOutcome::Applied);
|
||||||
|
assert(reply.index == 1);
|
||||||
|
assert(kv.committed_index() == 1);
|
||||||
|
|
||||||
|
auto read = kv.quorum_read("a", "key");
|
||||||
|
assert(read.has_value());
|
||||||
|
assert(read->has_value());
|
||||||
|
assert(**read == "value");
|
||||||
|
|
||||||
|
// Followers applied the committed entry too.
|
||||||
|
assert(kv.snapshot("b")->kv.at("key") == "value");
|
||||||
|
assert(kv.snapshot("c")->kv.at("key") == "value");
|
||||||
|
assert(kv.snapshot("b")->applied_index ==
|
||||||
|
kv.snapshot("b")->commit_index);
|
||||||
|
}
|
||||||
|
|
||||||
|
void minority_leader_cannot_commit_or_read()
|
||||||
|
{
|
||||||
|
auto kv = cluster();
|
||||||
|
assert(kv.elect("a").has_value());
|
||||||
|
kv.set_partition("b", 1);
|
||||||
|
kv.set_partition("c", 1);
|
||||||
|
|
||||||
|
const auto reply = kv.propose("a", "key", std::string{"lost"});
|
||||||
|
assert(reply.outcome == KvWriteOutcome::NoQuorum);
|
||||||
|
// Never applied without a majority.
|
||||||
|
assert(kv.snapshot("a")->kv.empty());
|
||||||
|
|
||||||
|
auto read = kv.quorum_read("a", "key");
|
||||||
|
assert(!read.has_value());
|
||||||
|
assert(read.error().kind() == Void::Result::ErrorKind::overloaded);
|
||||||
|
}
|
||||||
|
|
||||||
|
void new_majority_elects_and_preserves_committed_history()
|
||||||
|
{
|
||||||
|
auto kv = cluster();
|
||||||
|
assert(kv.elect("a").has_value());
|
||||||
|
assert(kv.propose("a", "key", std::string{"one"}).outcome ==
|
||||||
|
KvWriteOutcome::Applied);
|
||||||
|
|
||||||
|
// Isolate the old leader; the other two form a majority.
|
||||||
|
kv.set_partition("a", 1);
|
||||||
|
assert(kv.elect("b").has_value());
|
||||||
|
assert(kv.propose("b", "key", std::string{"two"}).outcome ==
|
||||||
|
KvWriteOutcome::Applied);
|
||||||
|
|
||||||
|
// Heal: the next heartbeat from the new leader delivers the committed
|
||||||
|
// entry and term to the stale node, which steps down.
|
||||||
|
kv.set_partition("a", 0);
|
||||||
|
assert(kv.heartbeat("b").has_value());
|
||||||
|
assert(kv.snapshot("a")->role == Role::Follower);
|
||||||
|
assert(kv.snapshot("a")->kv.at("key") == "two");
|
||||||
|
|
||||||
|
const auto stale = kv.propose("a", "key", std::string{"stale"});
|
||||||
|
assert(stale.outcome == KvWriteOutcome::NotLeader);
|
||||||
|
|
||||||
|
auto read = kv.quorum_read("b", "key");
|
||||||
|
assert(read.has_value() && read->has_value());
|
||||||
|
assert(**read == "two");
|
||||||
|
// Committed history was never lost on the old leader either.
|
||||||
|
assert(kv.snapshot("a")->kv.at("key") == "two");
|
||||||
|
}
|
||||||
|
|
||||||
|
void uncommitted_entry_is_overwritten_and_never_applied()
|
||||||
|
{
|
||||||
|
auto kv = cluster();
|
||||||
|
assert(kv.elect("a").has_value());
|
||||||
|
kv.set_partition("b", 1);
|
||||||
|
kv.set_partition("c", 1);
|
||||||
|
|
||||||
|
const auto ghost = kv.propose("a", "key", std::string{"ghost"});
|
||||||
|
assert(ghost.outcome == KvWriteOutcome::NoQuorum);
|
||||||
|
assert(!kv.snapshot("a")->kv.contains("key"));
|
||||||
|
const std::size_t ghost_log = kv.snapshot("a")->log_size;
|
||||||
|
|
||||||
|
kv.set_partition("b", 0);
|
||||||
|
kv.set_partition("c", 0);
|
||||||
|
assert(kv.elect("b").has_value());
|
||||||
|
assert(kv.propose("b", "key", std::string{"real"}).outcome ==
|
||||||
|
KvWriteOutcome::Applied);
|
||||||
|
|
||||||
|
// The stale suffix was truncated and replaced, never applied.
|
||||||
|
const auto old = kv.snapshot("a");
|
||||||
|
assert(old->log_size <= ghost_log);
|
||||||
|
assert(old->kv.at("key") == "real");
|
||||||
|
auto read = kv.quorum_read("b", "key");
|
||||||
|
assert(read.has_value() && read->has_value() && **read == "real");
|
||||||
|
}
|
||||||
|
|
||||||
|
void crash_and_restart_preserve_committed_state()
|
||||||
|
{
|
||||||
|
auto kv = cluster();
|
||||||
|
assert(kv.elect("a").has_value());
|
||||||
|
assert(kv.propose("a", "x", std::string{"1"}).outcome ==
|
||||||
|
KvWriteOutcome::Applied);
|
||||||
|
assert(kv.propose("a", "y", std::string{"2"}).outcome ==
|
||||||
|
KvWriteOutcome::Applied);
|
||||||
|
|
||||||
|
for (const auto& id : kv.voters()) {
|
||||||
|
kv.crash(id);
|
||||||
|
}
|
||||||
|
for (const auto& id : kv.voters()) {
|
||||||
|
kv.restart(id);
|
||||||
|
}
|
||||||
|
assert(kv.elect("c").has_value());
|
||||||
|
auto x = kv.quorum_read("c", "x");
|
||||||
|
auto y = kv.quorum_read("c", "y");
|
||||||
|
assert(x.has_value() && x->has_value() && **x == "1");
|
||||||
|
assert(y.has_value() && y->has_value() && **y == "2");
|
||||||
|
}
|
||||||
|
|
||||||
|
void follower_cannot_serve_consistent_read()
|
||||||
|
{
|
||||||
|
auto kv = cluster();
|
||||||
|
assert(kv.elect("a").has_value());
|
||||||
|
auto read = kv.quorum_read("b", "key");
|
||||||
|
assert(!read.has_value());
|
||||||
|
assert(read.error().kind() == Void::Result::ErrorKind::conflict);
|
||||||
|
}
|
||||||
|
|
||||||
|
void election_without_majority_or_voter_fails()
|
||||||
|
{
|
||||||
|
auto kv = cluster();
|
||||||
|
kv.set_partition("b", 1);
|
||||||
|
kv.set_partition("c", 1);
|
||||||
|
assert(!kv.elect("a").has_value());
|
||||||
|
|
||||||
|
auto unknown = kv.elect("nope");
|
||||||
|
assert(!unknown.has_value());
|
||||||
|
assert(unknown.error().kind() == Void::Result::ErrorKind::not_found);
|
||||||
|
}
|
||||||
|
|
||||||
|
void write_requires_a_leader() {
|
||||||
|
auto kv = cluster();
|
||||||
|
assert(kv.elect("a").has_value());
|
||||||
|
assert(kv.propose("b", "key", std::string{"v"}).outcome ==
|
||||||
|
KvWriteOutcome::NotLeader);
|
||||||
|
assert(kv.propose("missing", "key", std::string{"v"}).outcome ==
|
||||||
|
KvWriteOutcome::NodeDown);
|
||||||
|
}
|
||||||
|
|
||||||
|
void deletes_replicate_as_tombstones()
|
||||||
|
{
|
||||||
|
auto kv = cluster();
|
||||||
|
assert(kv.elect("a").has_value());
|
||||||
|
assert(kv.propose("a", "key", std::string{"value"}).outcome ==
|
||||||
|
KvWriteOutcome::Applied);
|
||||||
|
assert(kv.propose("a", "key", std::nullopt).outcome ==
|
||||||
|
KvWriteOutcome::Applied);
|
||||||
|
|
||||||
|
auto read = kv.quorum_read("a", "key");
|
||||||
|
assert(read.has_value());
|
||||||
|
assert(!read->has_value());
|
||||||
|
assert(!kv.snapshot("b")->kv.contains("key"));
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
leader_commits_with_a_majority();
|
||||||
|
minority_leader_cannot_commit_or_read();
|
||||||
|
new_majority_elects_and_preserves_committed_history();
|
||||||
|
uncommitted_entry_is_overwritten_and_never_applied();
|
||||||
|
crash_and_restart_preserve_committed_state();
|
||||||
|
follower_cannot_serve_consistent_read();
|
||||||
|
election_without_majority_or_voter_fails();
|
||||||
|
write_requires_a_leader();
|
||||||
|
deletes_replicate_as_tombstones();
|
||||||
|
std::puts("distributed replicated kv ok");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user