From cfa860f9440c19fdf97893eb986a0d83d2459aae Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Fri, 4 Dec 2026 10:32:28 +0300 Subject: [PATCH] DistributedApplications: deterministic replicated KV core with quorum commits, quorum reads and crash/partition histories (P-DISTRIBUTED-04 foundation) --- .../distributed/host-graph/CMakeLists.txt | 5 + .../distributed_host/replicated_kv.hpp | 147 +++++++ .../host-graph/src/replicated_kv.cpp | 392 ++++++++++++++++++ .../host-graph/tests/replicated_kv_test.cpp | 192 +++++++++ 4 files changed, 736 insertions(+) create mode 100644 examples/distributed/host-graph/include/distributed_host/replicated_kv.hpp create mode 100644 examples/distributed/host-graph/src/replicated_kv.cpp create mode 100644 examples/distributed/host-graph/tests/replicated_kv_test.cpp diff --git a/examples/distributed/host-graph/CMakeLists.txt b/examples/distributed/host-graph/CMakeLists.txt index bf6130b..75efb3d 100644 --- a/examples/distributed/host-graph/CMakeLists.txt +++ b/examples/distributed/host-graph/CMakeLists.txt @@ -11,6 +11,7 @@ find_package(Void CONFIG REQUIRED COMPONENTS Functional Net) add_library(distributed_host_graph STATIC src/host_graph.cpp + src/replicated_kv.cpp src/single_node.cpp) target_include_directories(distributed_host_graph PUBLIC include) 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) 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() 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_replicated_kv COMMAND distributed_replicated_kv_test) diff --git a/examples/distributed/host-graph/include/distributed_host/replicated_kv.hpp b/examples/distributed/host-graph/include/distributed_host/replicated_kv.hpp new file mode 100644 index 0000000..a6c6be1 --- /dev/null +++ b/examples/distributed/host-graph/include/distributed_host/replicated_kv.hpp @@ -0,0 +1,147 @@ +#pragma once + +#include "distributed_host/host_graph.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +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 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 leader; + std::map> 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 voters); + + [[nodiscard]] const std::vector& 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 + 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 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 + 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> + 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 + 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 voted_for; + std::optional leader; + std::vector log; + std::uint64_t commit_index{0}; + std::uint64_t applied_index{0}; + std::map> 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 m_voters; + std::vector m_nodes; + }; +} // namespace DistributedHost diff --git a/examples/distributed/host-graph/src/replicated_kv.cpp b/examples/distributed/host-graph/src/replicated_kv.cpp new file mode 100644 index 0000000..2f18556 --- /dev/null +++ b/examples/distributed/host-graph/src/replicated_kv.cpp @@ -0,0 +1,392 @@ +#include "distributed_host/replicated_kv.hpp" + +#include +#include +#include + +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 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 + 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(follower.log.size() - 1)); + apply_committed(follower); + } + return true; + } + + KvWriteReply ReplicatedKvCluster::propose(std::string_view leader_id, + std::string key, + std::optional 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(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 + 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> + 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{}; + } + return std::optional{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 + 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 diff --git a/examples/distributed/host-graph/tests/replicated_kv_test.cpp b/examples/distributed/host-graph/tests/replicated_kv_test.cpp new file mode 100644 index 0000000..b76ec28 --- /dev/null +++ b/examples/distributed/host-graph/tests/replicated_kv_test.cpp @@ -0,0 +1,192 @@ +#include "distributed_host/replicated_kv.hpp" + +#include +#include +#include +#include + +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; +}