Files
Library/examples/distributed/host-graph/tests/multi_process_test.cpp
T

466 lines
13 KiB
C++

// 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 <path-to-distributed_voter_agent>
#include <Void/Net/Http.hpp>
#include <Void/System/Process.hpp>
#include <csignal>
#include <unistd.h>
#include <cassert>
#include <chrono>
#include <cstdio>
#include <filesystem>
#include <optional>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace
{
constexpr std::string_view kToken{"peer-secret"};
struct Agent {
std::string id;
std::filesystem::path directory;
std::uint16_t port{0};
std::optional<Void::Process::Child> 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<std::uint64_t>
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<pid_t>(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<std::uint16_t>(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<pid_t>(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<std::string>
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> 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<std::size_t>(
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<std::string>
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<Agent> 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<std::string> 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<LogEntry>& acknowledged() const
{
return m_acknowledged;
}
[[nodiscard]] std::optional<std::string>
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<std::size_t> m_leader;
std::vector<LogEntry> m_acknowledged;
};
} // namespace
int main(int argc, char** argv)
{
if (argc < 2) {
std::fprintf(stderr,
"usage: multi_process_test <voter-agent-binary>\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<std::string>{"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<std::string>{"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<std::string>{"v4"});
assert(driver.propose("other", "x") == Driver::Write::Applied);
assert(driver.read("other") == std::optional<std::string>{"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;
}