diff --git a/examples/distributed/host-graph/CMakeLists.txt b/examples/distributed/host-graph/CMakeLists.txt index 7670cbb..4399a5e 100644 --- a/examples/distributed/host-graph/CMakeLists.txt +++ b/examples/distributed/host-graph/CMakeLists.txt @@ -7,7 +7,7 @@ set(CMAKE_CXX_STANDARD 26) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) -find_package(Void CONFIG REQUIRED COMPONENTS Functional Net) +find_package(Void CONFIG REQUIRED COMPONENTS Functional Net System) add_library(distributed_host_graph STATIC src/cluster_fixture.cpp @@ -46,6 +46,14 @@ target_link_libraries(distributed_cluster_queue_test PRIVATE distributed_host_gr add_executable(distributed_host_graph_bench benchmarks/host_graph_bench.cpp) target_link_libraries(distributed_host_graph_bench PRIVATE distributed_host_graph) +# Out-of-process voter agent and the multi-process acceptance harness that +# spawns three of them. +add_executable(distributed_voter_agent agents/voter_agent.cpp) +target_link_libraries(distributed_voter_agent PRIVATE Void::Net) + +add_executable(distributed_multi_process_test tests/multi_process_test.cpp) +target_link_libraries(distributed_multi_process_test PRIVATE Void::Net Void::System) + enable_testing() add_test(NAME distributed_host_graph COMMAND distributed_host_graph_test) add_test(NAME distributed_single_node COMMAND distributed_single_node_test) @@ -59,3 +67,5 @@ add_test(NAME distributed_cluster_queue COMMAND distributed_cluster_queue_test) # latency thresholds. add_test(NAME distributed_host_graph_bench_smoke COMMAND distributed_host_graph_bench --quick) +add_test(NAME distributed_multi_process + COMMAND distributed_multi_process_test $) diff --git a/examples/distributed/host-graph/agents/voter_agent.cpp b/examples/distributed/host-graph/agents/voter_agent.cpp new file mode 100644 index 0000000..aca7f3d --- /dev/null +++ b/examples/distributed/host-graph/agents/voter_agent.cpp @@ -0,0 +1,611 @@ +// Out-of-process voter agent for the multi-process acceptance harness. +// +// Each agent owns one directory and durably persists its Raft-style state +// (current term, vote, log, commit index) before replying to any RPC. The +// parent harness drives elections and replication over authenticated HTTP; +// killing an agent loses nothing acknowledged, and a restarted agent +// recovers from disk. +// +// distributed_voter_agent --dir --port --token +// +// The bound port is written to `/port` once the listener is up. +// Keys and values are restricted to [A-Za-z0-9_.-] so the durable text format +// stays unambiguous. + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using Entry = std::pair; // term, index + + struct LogEntry { + std::uint64_t term{0}; + std::uint64_t index{0}; + std::string key; + std::string value; + + [[nodiscard]] bool operator==(const LogEntry&) const noexcept = + default; + }; + + [[nodiscard]] bool safe_token(std::string_view text) + { + return !text.empty() && + std::ranges::all_of(text, [](char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '_' || c == '.' || + c == '-'; + }); + } + + void sync_directory(const std::filesystem::path& directory) + { + const int fd = ::open(directory.c_str(), O_RDONLY | O_DIRECTORY); + if (fd >= 0) { + (void)::fsync(fd); + (void)::close(fd); + } + } + + /// Durable voter state. Every mutation is persisted (write, fsync, rename, + /// directory fsync) before the RPC returns success. + class VoterStore + { + public: + + explicit VoterStore(std::filesystem::path directory) + : m_directory(std::move(directory)) + , m_path(m_directory / "voter.state") + { + } + + [[nodiscard]] bool load() + { + std::lock_guard lock{m_mutex}; + if (!std::filesystem::exists(m_path)) { + return std::filesystem::create_directories(m_directory) || + std::filesystem::exists(m_directory); + } + std::ifstream in{m_path}; + if (!in.is_open()) { + return false; + } + std::string line; + while (std::getline(in, line)) { + std::istringstream fields{line}; + std::string tag; + fields >> tag; + if (tag == "term") { + std::uint64_t term = 0; + std::string voted; + if (!(fields >> term >> voted)) { + return false; + } + m_term = term; + m_voted_for = voted == "-" + ? std::nullopt + : std::optional{voted}; + } else if (tag == "entry") { + LogEntry entry; + if (!(fields >> entry.term >> entry.index >> entry.key >> + entry.value)) { + return false; + } + m_log.push_back(std::move(entry)); + } else if (tag == "commit") { + if (!(fields >> m_commit)) { + return false; + } + } else { + return false; + } + } + reapply(); + return true; + } + + [[nodiscard]] std::uint64_t term() const + { + std::lock_guard lock{m_mutex}; + return m_term; + } + + [[nodiscard]] std::uint64_t last_index() const + { + std::lock_guard lock{m_mutex}; + return m_log.empty() ? 0 : m_log.back().index; + } + + [[nodiscard]] std::uint64_t last_term() const + { + std::lock_guard lock{m_mutex}; + return m_log.empty() ? 0 : m_log.back().term; + } + + [[nodiscard]] std::uint64_t commit() const + { + std::lock_guard lock{m_mutex}; + return m_commit; + } + + [[nodiscard]] std::size_t log_size() const + { + std::lock_guard lock{m_mutex}; + return m_log.size(); + } + + [[nodiscard]] std::string voted_for() const + { + std::lock_guard lock{m_mutex}; + return m_voted_for.value_or("-"); + } + + /// Grant a vote when the term allows it and the candidate's log is + /// at least as up to date. + [[nodiscard]] bool vote(std::uint64_t term, std::string_view candidate, + std::uint64_t candidate_last_index, + std::uint64_t candidate_last_term) + { + std::lock_guard lock{m_mutex}; + if (term < m_term) { + return false; + } + if (term > m_term) { + m_term = term; + m_voted_for.reset(); + if (!persist()) { + return false; + } + } + if (m_voted_for.has_value() && *m_voted_for != candidate) { + return false; + } + const std::uint64_t self_index = + m_log.empty() ? 0 : m_log.back().index; + const std::uint64_t self_term = + m_log.empty() ? 0 : m_log.back().term; + const bool up_to_date = + candidate_last_term > self_term || + (candidate_last_term == self_term && + candidate_last_index >= self_index); + if (!up_to_date) { + return false; + } + m_voted_for = std::string{candidate}; + return persist(); + } + + /// AppendEntries: returns the matched index on success. + [[nodiscard]] std::optional append( + std::uint64_t term, std::uint64_t prev_index, + std::uint64_t prev_term, std::uint64_t leader_commit, + const std::vector& entries) + { + std::lock_guard lock{m_mutex}; + if (term < m_term) { + return std::nullopt; + } + if (term > m_term) { + m_term = term; + m_voted_for.reset(); + } + const std::uint64_t local_last = + m_log.empty() ? 0 : m_log.back().index; + if (prev_index > local_last) { + return std::nullopt; + } + const std::uint64_t local_term = + prev_index == 0 ? 0 : m_log[prev_index - 1].term; + if (local_term != prev_term) { + return std::nullopt; + } + std::size_t position = static_cast(prev_index); + for (const auto& entry : entries) { + if (position < m_log.size() && + m_log[position] == entry) { + ++position; + continue; + } + m_log.resize(position); + m_log.push_back(entry); + ++position; + } + if (leader_commit > m_commit) { + m_commit = std::min(leader_commit, + m_log.empty() ? 0 : m_log.back().index); + } + reapply(); + if (!persist()) { + return std::nullopt; + } + return m_log.empty() ? 0 : m_log.back().index; + } + + [[nodiscard]] std::vector entries_from( + std::uint64_t index) const + { + std::lock_guard lock{m_mutex}; + std::vector out; + for (const auto& entry : m_log) { + if (entry.index >= index) { + out.push_back(entry); + } + } + return out; + } + + [[nodiscard]] std::optional value( + std::string_view key) const + { + std::lock_guard lock{m_mutex}; + const auto found = m_kv.find(key); + if (found == m_kv.end()) { + return std::nullopt; + } + return found->second; + } + + private: + + void reapply() + { + m_kv.clear(); + for (const auto& entry : m_log) { + if (entry.index > m_commit) { + break; + } + if (entry.value == "-") { + m_kv.erase(entry.key); + } else { + m_kv.insert_or_assign(entry.key, entry.value); + } + } + } + + [[nodiscard]] bool persist() + { + std::string text; + text += "term " + std::to_string(m_term) + " " + + m_voted_for.value_or("-") + "\n"; + for (const auto& entry : m_log) { + text += "entry " + std::to_string(entry.term) + " " + + std::to_string(entry.index) + " " + entry.key + " " + + entry.value + "\n"; + } + text += "commit " + std::to_string(m_commit) + "\n"; + + const auto temporary = m_path.string() + ".tmp"; + { + std::ofstream out{temporary, std::ios::trunc}; + if (!out.is_open()) { + return false; + } + out << text; + out.flush(); + if (!out.good()) { + return false; + } + } + const int fd = ::open(temporary.c_str(), O_RDONLY); + if (fd < 0) { + return false; + } + (void)::fsync(fd); + (void)::close(fd); + if (std::rename(temporary.c_str(), m_path.c_str()) != 0) { + return false; + } + sync_directory(m_directory); + return true; + } + + mutable std::mutex m_mutex; + std::filesystem::path m_directory; + std::filesystem::path m_path; + std::uint64_t m_term{0}; + std::optional m_voted_for; + std::vector m_log; + std::uint64_t m_commit{0}; + std::map> m_kv; + }; + + [[nodiscard]] std::optional + query(std::string_view text, std::string_view name) + { + std::size_t pos = 0; + while (pos <= text.size()) { + const std::size_t amp = text.find('&', pos); + const std::string_view pair = + text.substr(pos, amp == std::string_view::npos + ? std::string_view::npos + : amp - pos); + const std::size_t eq = pair.find('='); + if (pair.substr(0, eq) == name) { + return eq == std::string_view::npos ? std::string_view{} + : pair.substr(eq + 1); + } + if (amp == std::string_view::npos) { + break; + } + pos = amp + 1; + } + return std::nullopt; + } + + [[nodiscard]] std::optional number(std::string_view text) + { + if (text.empty()) { + return std::nullopt; + } + std::uint64_t value = 0; + const auto parsed = + std::from_chars(text.data(), text.data() + text.size(), value); + if (parsed.ec != std::errc{}) { + return std::nullopt; + } + return value; + } + + [[nodiscard]] Void::Net::ServerResponse text_response(int status, + std::string body) + { + Void::Net::ServerResponse response; + response.status = static_cast(status); + response.headers.push_back( + Void::Net::Header{"content-type", "text/plain; charset=utf-8"}); + response.body = std::move(body); + return response; + } +} // namespace + +int main(int argc, char** argv) +{ + std::filesystem::path directory; + std::uint16_t port = 0; + std::string token; + long long parent{0}; + + for (int i = 1; i < argc; ++i) { + const std::string_view arg{argv[i]}; + if (arg == "--dir" && i + 1 < argc) { + directory = argv[++i]; + } else if (arg == "--parent" && i + 1 < argc) { + parent = std::strtoll(argv[++i], nullptr, 10); + } else if (arg == "--port" && i + 1 < argc) { + unsigned int value = 0; + const auto parsed = std::from_chars(argv[i + 1], + argv[i + 1] + std::strlen(argv[i + 1]), + value); + if (parsed.ec != std::errc{} || value > 65535U) { + std::fprintf(stderr, "invalid --port\n"); + return 2; + } + port = static_cast(value); + ++i; + } else if (arg == "--token" && i + 1 < argc) { + token = argv[++i]; + } + } + if (directory.empty() || token.empty()) { + std::fprintf(stderr, + "usage: distributed_voter_agent --dir " + "--port --token \n"); + return 2; + } + + VoterStore store{directory}; + if (!store.load()) { + std::fprintf(stderr, "voter agent: failed to load durable state\n"); + return 3; + } + + Void::Net::HttpServerOptions options; + options.bind_host = "127.0.0.1"; + options.port = port; + options.max_concurrent_connections = 8; + options.max_body_bytes = 64ULL * 1024ULL; + Void::Net::HttpServer server{options}; + + auto guarded = [token](const Void::Net::ServerRequest& request) + -> std::optional { + const auto header = request.header("authorization"); + const std::string expected = "Bearer " + token; + if (!header || *header != expected) { + return text_response(401, "unauthorized"); + } + return std::nullopt; + }; + + auto add = [&](Void::Net::Method method, const char* pattern, auto fn) { + return server.add_route( + method, pattern, + [guarded, fn](const Void::Net::ServerRequest& request) + -> Void::Net::RouteResult { + if (auto denied = guarded(request)) { + return Void::Result::ok(std::move(*denied)); + } + return Void::Result::ok(fn(request)); + }); + }; + + auto registered = add( + Void::Net::Method::Get, "/voter/state", + [&store](const Void::Net::ServerRequest&) { + return text_response( + 200, "term=" + std::to_string(store.term()) + + " voted=" + store.voted_for() + + " last_index=" + std::to_string(store.last_index()) + + " last_term=" + std::to_string(store.last_term()) + + " commit=" + std::to_string(store.commit()) + + " entries=" + std::to_string(store.log_size())); + }); + if (!registered) { + return 4; + } + + registered = add( + Void::Net::Method::Post, "/voter/vote", + [&store](const Void::Net::ServerRequest& request) { + const auto term = number(query(request.query, "term").value_or("")); + const auto last_index = + number(query(request.query, "last_index").value_or("")); + const auto last_term = + number(query(request.query, "last_term").value_or("")); + const auto candidate = query(request.query, "candidate"); + if (!term || !last_index || !last_term || !candidate || + !safe_token(*candidate)) { + return text_response(400, "bad vote request"); + } + if (!store.vote(*term, *candidate, *last_index, *last_term)) { + return text_response(409, "vote rejected"); + } + return text_response(200, "granted"); + }); + if (!registered) { + return 4; + } + + registered = add( + Void::Net::Method::Post, "/voter/append", + [&store](const Void::Net::ServerRequest& request) { + const auto term = number(query(request.query, "term").value_or("")); + const auto prev_index = + number(query(request.query, "prev_index").value_or("")); + const auto prev_term = + number(query(request.query, "prev_term").value_or("")); + const auto commit = + number(query(request.query, "commit").value_or("")); + if (!term || !prev_index || !prev_term || !commit) { + return text_response(400, "bad append request"); + } + std::vector entries; + std::size_t pos = 0; + while (pos < request.body.size()) { + const std::size_t end = request.body.find('\n', pos); + const std::string_view line = std::string_view{request.body}.substr( + pos, end == std::string::npos ? std::string::npos : end - pos); + if (!line.empty()) { + LogEntry entry; + std::string key; + std::string value; + const std::size_t first = line.find(','); + const std::size_t second = + first == std::string_view::npos + ? std::string_view::npos + : line.find(',', first + 1); + const std::size_t third = + second == std::string_view::npos + ? std::string_view::npos + : line.find(',', second + 1); + if (first == std::string_view::npos || + second == std::string_view::npos || + third == std::string_view::npos) { + return text_response(400, "bad entry"); + } + const auto entry_term = number(line.substr(0, first)); + const auto entry_index = + number(line.substr(first + 1, second - first - 1)); + key = line.substr(second + 1, third - second - 1); + value = line.substr(third + 1); + if (!entry_term || !entry_index || !safe_token(key) || + !(safe_token(value) || value == "-")) { + return text_response(400, "bad entry"); + } + entry.term = *entry_term; + entry.index = *entry_index; + entry.key = key; + entry.value = value; + entries.push_back(std::move(entry)); + } + if (end == std::string::npos) { + break; + } + pos = end + 1; + } + const auto matched = + store.append(*term, *prev_index, *prev_term, *commit, entries); + if (!matched) { + return text_response(409, "append rejected"); + } + return text_response(200, "matched=" + std::to_string(*matched)); + }); + if (!registered) { + return 4; + } + + registered = add( + Void::Net::Method::Get, "/voter/value", + [&store](const Void::Net::ServerRequest& request) { + const auto key = query(request.query, "key"); + if (!key) { + return text_response(400, "key required"); + } + const auto value = store.value(*key); + if (!value) { + return text_response(404, "not found"); + } + return text_response(200, *value); + }); + if (!registered) { + return 4; + } + + registered = add( + Void::Net::Method::Get, "/voter/entries", + [&store](const Void::Net::ServerRequest& request) { + const auto from = number(query(request.query, "from").value_or("1")); + if (!from) { + return text_response(400, "from required"); + } + std::string body; + for (const auto& entry : store.entries_from(*from)) { + body += std::to_string(entry.term) + "," + + std::to_string(entry.index) + "," + entry.key + "," + + entry.value + "\n"; + } + return text_response(200, std::move(body)); + }); + if (!registered) { + return 4; + } + + if (auto started = server.start(); !started) { + std::fprintf(stderr, "voter agent: failed to bind listener\n"); + return 5; + } + + { + const auto port_path = directory / "port"; + std::ofstream out{port_path, std::ios::trunc}; + out << server.bound_port() << "\n"; + } + + // Serve until the parent kills this process. An agent whose supervising + // parent disappeared exits on its own so it can never orphan and hold the + // harness's output pipes open. + while (parent == 0 || ::getppid() == parent) { + std::this_thread::sleep_for(std::chrono::milliseconds{200}); + } + return 0; +} diff --git a/examples/distributed/host-graph/tests/multi_process_test.cpp b/examples/distributed/host-graph/tests/multi_process_test.cpp new file mode 100644 index 0000000..5e2cf80 --- /dev/null +++ b/examples/distributed/host-graph/tests/multi_process_test.cpp @@ -0,0 +1,465 @@ +// Multi-process acceptance harness for the distributed KV reference. +// +// Spawns three independent voter-agent processes, drives elections and +// quorum replication over authenticated HTTP, kills and restarts processes +// with SIGKILL, and checks a single-client history: every acknowledged write +// is observed by later reads and survives crash/restart, and a write without +// a durable reply is never observed half-applied. +// +// multi_process_test + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + constexpr std::string_view kToken{"peer-secret"}; + + struct Agent { + std::string id; + std::filesystem::path directory; + std::uint16_t port{0}; + std::optional child; + bool alive{false}; + }; + + struct LogEntry { + std::uint64_t term{0}; + std::uint64_t index{0}; + std::string key; + std::string value; + }; + + struct State { + std::uint64_t term{0}; + std::uint64_t last_index{0}; + std::uint64_t last_term{0}; + std::uint64_t commit{0}; + std::size_t entries{0}; + }; + + [[nodiscard]] std::optional + field(std::string_view text, std::string_view name) + { + const std::string needle = std::string{name} + "="; + const std::size_t at = text.find(needle); + if (at == std::string_view::npos) { + return std::nullopt; + } + std::uint64_t value = 0; + const char* begin = text.data() + at + needle.size(); + const auto parsed = std::from_chars(begin, text.data() + text.size(), value); + if (parsed.ec != std::errc{}) { + return std::nullopt; + } + return value; + } + + class Harness + { + public: + + Harness(std::string agent_binary, std::size_t count) + { + const auto root = + std::filesystem::temp_directory_path() / + ("void-mp-" + std::to_string(::getpid())); + std::filesystem::remove_all(root); + for (std::size_t i = 0; i < count; ++i) { + Agent agent; + agent.id = "node-" + std::to_string(i); + agent.directory = root / agent.id; + std::filesystem::create_directories(agent.directory); + m_agents.push_back(std::move(agent)); + } + m_agent_binary = std::move(agent_binary); + } + + ~Harness() + { + for (auto& agent : m_agents) { + if (agent.child && agent.alive) { + (void)::kill(static_cast(agent.child->pid()), + SIGKILL); + (void)agent.child->wait_blocking( + std::chrono::seconds{5}); + } + } + } + + [[nodiscard]] bool launch(std::size_t index) + { + Agent& agent = m_agents[index]; + std::filesystem::remove(agent.directory / "port"); + Void::Process::SpawnOptions options; + options.executable = m_agent_binary; + options.arguments = {"--dir", agent.directory.string(), + "--port", "0", "--token", + std::string{kToken}, "--parent", + std::to_string(::getpid())}; + options.stdin_pipe = false; + options.stdout_pipe = false; + options.stderr_pipe = false; + auto child = Void::Process::spawn(options); + if (!child) { + return false; + } + agent.child.emplace(std::move(*child)); + agent.alive = true; + // The agent publishes its bound port once serving. + for (int attempt = 0; attempt < 500; ++attempt) { + const auto port_file = agent.directory / "port"; + if (std::filesystem::exists(port_file)) { + std::FILE* file = std::fopen(port_file.c_str(), "r"); + if (file != nullptr) { + unsigned int port = 0; + const int matched = std::fscanf(file, "%u", &port); + std::fclose(file); + if (matched == 1) { + agent.port = static_cast(port); + return agent.port != 0; + } + } + } + std::this_thread::sleep_for( + std::chrono::milliseconds{10}); + } + return false; + } + + void kill(std::size_t index) + { + Agent& agent = m_agents[index]; + if (!agent.child || !agent.alive) { + return; + } + (void)::kill(static_cast(agent.child->pid()), SIGKILL); + (void)agent.child->wait_blocking(std::chrono::seconds{5}); + agent.child.reset(); + agent.alive = false; + } + + [[nodiscard]] std::string endpoint(std::size_t index) const + { + return "http://127.0.0.1:" + + std::to_string(m_agents[index].port); + } + + [[nodiscard]] bool alive(std::size_t index) const + { + return m_agents[index].alive; + } + + [[nodiscard]] std::size_t size() const { return m_agents.size(); } + + // ── RPC ───────────────────────────────────────────────────────── + + [[nodiscard]] std::optional + get(std::size_t index, const std::string& path) + { + auto response = m_client.get( + endpoint(index) + path, + {Void::Net::Header{"authorization", + "Bearer " + std::string{kToken}}}); + if (!response.has_value() || response->status != 200) { + return std::nullopt; + } + return response->body; + } + + [[nodiscard]] int post(std::size_t index, const std::string& path, + std::string body = {}) + { + Void::Net::Request request; + request.method = Void::Net::Method::Post; + request.url = endpoint(index) + path; + request.body = std::move(body); + request.headers.push_back(Void::Net::Header{ + "authorization", "Bearer " + std::string{kToken}}); + auto response = m_client.send(request); + if (!response.has_value()) { + return -1; + } + return response->status; + } + + [[nodiscard]] std::optional state(std::size_t index) + { + auto body = get(index, "/voter/state"); + if (!body) { + return std::nullopt; + } + State out; + out.term = field(*body, "term").value_or(0); + out.last_index = field(*body, "last_index").value_or(0); + out.last_term = field(*body, "last_term").value_or(0); + out.commit = field(*body, "commit").value_or(0); + out.entries = static_cast( + field(*body, "entries").value_or(0)); + return out; + } + + [[nodiscard]] int vote(std::size_t index, std::uint64_t term, + std::string_view candidate, + std::uint64_t last_index, + std::uint64_t last_term) + { + return post(index, + "/voter/vote?term=" + std::to_string(term) + + "&candidate=" + std::string{candidate} + + "&last_index=" + std::to_string(last_index) + + "&last_term=" + std::to_string(last_term)); + } + + [[nodiscard]] int append(std::size_t index, std::uint64_t term, + std::uint64_t prev_index, + std::uint64_t prev_term, + std::uint64_t commit, + std::string_view entries) + { + return post(index, + "/voter/append?term=" + std::to_string(term) + + "&prev_index=" + std::to_string(prev_index) + + "&prev_term=" + std::to_string(prev_term) + + "&commit=" + std::to_string(commit), + std::string{entries}); + } + + [[nodiscard]] std::optional + value(std::size_t index, std::string_view key) + { + return get(index, + "/voter/value?key=" + std::string{key}); + } + + private: + + std::string m_agent_binary; + std::vector m_agents; + Void::Net::HttpClient m_client; + }; + + /// Single-client linearizable reference: sequential operations, one + /// leader at a time. + class Driver + { + public: + + explicit Driver(Harness& harness) : m_harness(harness) {} + + [[nodiscard]] bool elect(std::size_t candidate) + { + const auto candidate_state = m_harness.state(candidate); + if (!candidate_state) { + return false; + } + m_term = std::max(m_term, candidate_state->term) + 1; + std::size_t votes = 0; + for (std::size_t i = 0; i < m_harness.size(); ++i) { + if (!m_harness.alive(i)) { + continue; + } + if (m_harness.vote(i, m_term, + "node-" + std::to_string(candidate), + candidate_state->last_index, + candidate_state->last_term) == 200) { + ++votes; + } + } + if (votes * 2 <= m_harness.size()) { + return false; + } + m_leader = candidate; + return true; + } + + enum class Write { Applied, NoQuorum, NotLeader }; + + [[nodiscard]] Write propose(std::string key, std::string value) + { + if (!m_leader.has_value() || !m_harness.alive(*m_leader)) { + return Write::NotLeader; + } + const LogEntry entry{ + .term = m_term, + .index = m_commit + 1, + .key = std::move(key), + .value = std::move(value)}; + const std::string line = + std::to_string(entry.term) + "," + + std::to_string(entry.index) + "," + entry.key + "," + + entry.value + "\n"; + auto line_of = [](const LogEntry& e) { + return std::to_string(e.term) + "," + + std::to_string(e.index) + "," + e.key + "," + e.value + + "\n"; + }; + std::size_t acks = 0; + for (std::size_t i = 0; i < m_harness.size(); ++i) { + if (!m_harness.alive(i)) { + continue; + } + int status = m_harness.append(i, m_term, m_commit, m_prev_term, + m_commit, line); + if (status == 409) { + // The follower is behind: back off to its last entry and + // replay everything it is missing (Raft catch-up). + const auto peer = m_harness.state(i); + if (peer) { + std::string catchup; + for (const auto& acked : m_acknowledged) { + if (acked.index > peer->last_index) { + catchup += line_of(acked); + } + } + catchup += line; + status = m_harness.append( + i, m_term, peer->last_index, peer->last_term, + m_commit, catchup); + } + } + if (status == 200) { + ++acks; + } + } + if (acks * 2 <= m_harness.size()) { + return Write::NoQuorum; + } + // Majority acknowledged: publish the commit index so every + // reachable voter applies the entry (AppendEntries carries it). + m_commit = entry.index; + for (std::size_t i = 0; i < m_harness.size(); ++i) { + if (!m_harness.alive(i)) { + continue; + } + (void)m_harness.append(i, m_term, entry.index, entry.term, + m_commit, {}); + } + m_prev_term = entry.term; + m_acknowledged.push_back(entry); + return Write::Applied; + } + + [[nodiscard]] std::optional read(std::string_view key) + { + if (!m_leader.has_value() || !m_harness.alive(*m_leader)) { + return std::nullopt; + } + // Confirm leadership in this term with a majority heartbeat. + std::size_t reachable = 0; + for (std::size_t i = 0; i < m_harness.size(); ++i) { + if (!m_harness.alive(i)) { + continue; + } + const auto peer = m_harness.state(i); + if (!peer || peer->term > m_term) { + return std::nullopt; + } + ++reachable; + } + if (reachable * 2 <= m_harness.size()) { + return std::nullopt; + } + return m_harness.value(*m_leader, key); + } + + [[nodiscard]] const std::vector& acknowledged() const + { + return m_acknowledged; + } + + [[nodiscard]] std::optional + latest_acknowledged(std::string_view key) const + { + for (auto it = m_acknowledged.rbegin(); + it != m_acknowledged.rend(); ++it) { + if (it->key == key) { + return it->value; + } + } + return std::nullopt; + } + + private: + + Harness& m_harness; + std::uint64_t m_term{0}; + std::uint64_t m_commit{0}; + std::uint64_t m_prev_term{0}; + std::optional m_leader; + std::vector m_acknowledged; + }; +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2) { + std::fprintf(stderr, + "usage: multi_process_test \n"); + return 2; + } + + Harness harness{argv[1], 3}; + for (std::size_t i = 0; i < harness.size(); ++i) { + assert(harness.launch(i)); + } + Driver driver{harness}; + + // Majority election and a durable first write. + assert(driver.elect(0)); + assert(driver.propose("k", "v1") == Driver::Write::Applied); + assert(driver.read("k") == std::optional{"v1"}); + + // One process dies: the write is still durably acknowledged. + harness.kill(2); + assert(driver.propose("k", "v2") == Driver::Write::Applied); + assert(driver.read("k") == std::optional{"v2"}); + + // A second death loses quorum: no durable reply, no readable value. + harness.kill(1); + assert(driver.propose("k", "v3") == Driver::Write::NoQuorum); + assert(!driver.read("k").has_value()); + + // Restart the killed processes: durable state comes back from disk. + assert(harness.launch(1)); + assert(harness.launch(2)); + // The recovered majority still holds every acknowledged write. + assert(driver.elect(1)); + const auto recovered = driver.read("k"); + assert(recovered.has_value()); + // Never the unacknowledged write. + assert(*recovered != "v3"); + assert(*recovered == driver.latest_acknowledged("k")); + + // The recovered cluster keeps serving new writes. + assert(driver.propose("k", "v4") == Driver::Write::Applied); + assert(driver.read("k") == std::optional{"v4"}); + assert(driver.propose("other", "x") == Driver::Write::Applied); + assert(driver.read("other") == std::optional{"x"}); + + // Every acknowledged entry is present on the restarted majority. + for (std::size_t i = 0; i < harness.size(); ++i) { + if (!harness.alive(i)) { + continue; + } + const auto state = harness.state(i); + assert(state.has_value()); + assert(state->last_index >= driver.acknowledged().back().index); + } + + std::puts("distributed multi-process acceptance ok"); + return 0; +}