DistributedApplications: backup/restore with identity retention, overlapping trust rotation and mixed-version rollout gates (P-DISTRIBUTED-06)

This commit is contained in:
faumaray committed 2026-12-04 10:38:10 +03:00
1 parent b386140899
commit cdc55a594e
3 files changed
+407

No files matched your search

@@ -33,9 +33,13 @@ target_link_libraries(distributed_cluster_fixture_test PRIVATE distributed_host_
add_executable(distributed_replicated_queue_test tests/replicated_queue_test.cpp)
target_link_libraries(distributed_replicated_queue_test PRIVATE distributed_host_graph)
add_executable(distributed_operations_test tests/operations_test.cpp)
target_link_libraries(distributed_operations_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)
add_test(NAME distributed_cluster_fixture COMMAND distributed_cluster_fixture_test)
add_test(NAME distributed_replicated_queue COMMAND distributed_replicated_queue_test)
add_test(NAME distributed_operations COMMAND distributed_operations_test)
@@ -0,0 +1,261 @@
#pragma once
#include "distributed_host/replicated_kv.hpp"
#include <Void/Functional/Result.hpp>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <map>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace DistributedHost
{
// ── Backup / restore ────────────────────────────────────────────────────
/// Stable cluster identity that a backup carries. A restore rehearsal must
/// retain it: restoring into a differently identified cluster would merge
/// unrelated histories.
struct ClusterIdentity {
std::string cluster;
std::vector<std::string> voters;
[[nodiscard]] bool operator==(const ClusterIdentity& other) const
{
return cluster == other.cluster &&
std::ranges::is_permutation(voters, other.voters);
}
};
struct ClusterBackup {
ClusterIdentity identity;
/// Commit index observed when the backup was captured.
std::uint64_t commit_index{0};
/// Quorum-confirmed applied state at that point.
std::map<std::string, std::string, std::less<>> state;
};
/// Capture a consistent backup from a quorum-confirmed leader.
[[nodiscard]] inline Void::Result::Result<ClusterBackup> capture_backup(
ReplicatedKvCluster& cluster, std::string_view leader,
ClusterIdentity identity)
{
auto snapshot = cluster.quorum_snapshot(leader);
if (!snapshot) {
return std::unexpected{std::move(snapshot).error()};
}
ClusterBackup backup;
backup.identity = std::move(identity);
backup.commit_index = cluster.committed_index();
backup.state = std::move(*snapshot);
return backup;
}
/// Restore a backup into an empty, separately identified cluster.
///
/// The target identity must match the backup exactly. Every entry is
/// written through the leader and must be majority-committed; a failed
/// write stops the restore with the partial state left visible.
[[nodiscard]] inline Void::Result::Result<std::size_t> restore_backup(
ReplicatedKvCluster& cluster, std::string_view leader,
const ClusterBackup& backup, const ClusterIdentity& target)
{
if (!(backup.identity == target)) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::invalid_argument,
"Restore: cluster identity does not match the backup"}};
}
std::size_t restored = 0;
for (const auto& [key, value] : backup.state) {
const KvWriteReply reply = cluster.propose(leader, key, value);
if (reply.outcome != KvWriteOutcome::Applied) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::exhausted,
"Restore: entry was not majority-committed"}};
}
++restored;
}
return restored;
}
// ── Trust rotation ──────────────────────────────────────────────────────
struct TrustGeneration {
std::uint64_t id{0};
std::vector<std::string> fingerprints;
};
/// Overlapping trust generations for credential rotation.
///
/// Rotation validates the new generation while the old one stays trusted,
/// so live connections drain without ever disabling verification. An empty
/// trust set trusts nothing (fail closed).
class TrustStore
{
public:
explicit TrustStore(std::vector<std::string> initial_fingerprints = {})
{
if (!initial_fingerprints.empty()) {
m_generations.push_back(
TrustGeneration{m_next_id++, std::move(initial_fingerprints)});
}
}
[[nodiscard]] bool trusted(std::string_view fingerprint) const noexcept
{
if (fingerprint.empty()) {
return false;
}
for (const auto& generation : m_generations) {
if (std::ranges::find(generation.fingerprints, fingerprint) !=
generation.fingerprints.end()) {
return true;
}
}
return false;
}
/// Add a new trusted generation while keeping the old ones.
/// Returns the new generation id.
[[nodiscard]] Void::Result::Result<std::uint64_t>
begin_rotation(std::vector<std::string> new_fingerprints)
{
if (new_fingerprints.empty()) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::invalid_argument,
"TrustStore: a rotation needs at least one fingerprint"}};
}
m_generations.push_back(
TrustGeneration{m_next_id++, std::move(new_fingerprints)});
return m_generations.back().id;
}
/// Revoke every generation older than `generation` after the
/// overlap drained. The chosen generation must be active.
[[nodiscard]] Void::Result::Result<void>
complete_rotation(std::uint64_t generation)
{
const auto found = std::ranges::find_if(
m_generations, [generation](const TrustGeneration& candidate) {
return candidate.id == generation;
});
if (found == m_generations.end()) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::not_found,
"TrustStore: unknown trust generation"}};
}
std::erase_if(m_generations,
[generation](const TrustGeneration& candidate) {
return candidate.id < generation;
});
return {};
}
[[nodiscard]] std::size_t active_generations() const noexcept
{
return m_generations.size();
}
private:
std::vector<TrustGeneration> m_generations;
std::uint64_t m_next_id{1};
};
// ── Mixed-version rollout ──────────────────────────────────────────────
struct VersionPolicy {
/// Format version this binary writes.
std::uint32_t format_version{2};
/// Oldest node version that can still read existing durable data.
std::uint32_t min_reader{1};
};
/// Per-voter version advertisement gate.
///
/// Readers may roll out first (every node must still read the durable
/// format), and a new command is admitted only when every voter
/// advertises support. Unknown voters are rejected rather than assumed
/// current.
class RolloutGate
{
public:
RolloutGate(std::vector<std::string> voters, VersionPolicy policy)
: m_policy(policy)
{
for (auto& voter : voters) {
m_advertised.emplace(std::move(voter), 0);
}
}
[[nodiscard]] Void::Result::Result<void>
report_version(std::string_view node, std::uint32_t version)
{
const auto found = m_advertised.find(node);
if (found == m_advertised.end()) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::not_found,
"RolloutGate: unknown voter"}};
}
found->second = version;
return {};
}
[[nodiscard]] Void::Result::Result<void>
admit_read(std::string_view node) const
{
const auto found = m_advertised.find(node);
if (found == m_advertised.end()) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::not_found,
"RolloutGate: unknown voter"}};
}
if (found->second < m_policy.min_reader) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::unsupported,
"RolloutGate: node cannot read the durable format"}};
}
return {};
}
/// A new command requires every voter to advertise it.
[[nodiscard]] Void::Result::Result<void>
admit_new_command(std::string_view node) const
{
if (m_advertised.find(node) == m_advertised.end()) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::not_found,
"RolloutGate: unknown voter"}};
}
for (const auto& [id, version] : m_advertised) {
(void)id;
if (version < m_policy.format_version) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::unsupported,
"RolloutGate: not every voter advertises the new "
"command"}};
}
}
return {};
}
[[nodiscard]] bool all_advertised() const noexcept
{
return std::ranges::all_of(
m_advertised, [this](const auto& entry) {
return entry.second >= m_policy.format_version;
});
}
private:
VersionPolicy m_policy;
std::map<std::string, std::uint32_t, std::less<>> m_advertised;
};
} // namespace DistributedHost
@@ -0,0 +1,142 @@
#include "distributed_host/operations.hpp"
#include <cassert>
#include <cstdio>
#include <string>
namespace
{
using namespace DistributedHost;
ClusterIdentity identity()
{
return ClusterIdentity{"prod-cluster", {"a", "b", "c"}};
}
void backup_and_restore_retains_identity_and_state()
{
ReplicatedKvCluster source{{"a", "b", "c"}};
assert(source.elect("a").has_value());
assert(source.propose("a", "x", std::string{"1"}).outcome ==
KvWriteOutcome::Applied);
assert(source.propose("a", "y", std::string{"2"}).outcome ==
KvWriteOutcome::Applied);
assert(source.propose("a", "z", std::string{"3"}).outcome ==
KvWriteOutcome::Applied);
assert(source.propose("a", "y", std::nullopt).outcome ==
KvWriteOutcome::Applied);
auto backup = capture_backup(source, "a", identity());
assert(backup.has_value());
assert(backup->identity == identity());
assert(backup->commit_index == source.committed_index());
assert(backup->state.size() == 2);
assert(!backup->state.contains("y"));
// Restore rehearsal into a separately started cluster.
ReplicatedKvCluster target{{"a", "b", "c"}};
assert(target.elect("a").has_value());
auto restored = restore_backup(target, "a", *backup, identity());
assert(restored.has_value());
assert(*restored == 2);
auto x = target.quorum_read("a", "x");
auto z = target.quorum_read("a", "z");
auto y = target.quorum_read("a", "y");
assert(x.has_value() && x->has_value() && **x == "1");
assert(z.has_value() && z->has_value() && **z == "3");
assert(y.has_value() && !y->has_value());
// A different cluster identity is refused, so histories cannot merge.
ClusterIdentity staging{"staging-cluster", {"a", "b", "c"}};
assert(!restore_backup(target, "a", *backup, staging).has_value());
ClusterIdentity fewer_voters{"prod-cluster", {"a", "b"}};
assert(!restore_backup(target, "a", *backup, fewer_voters).has_value());
}
void backup_without_quorum_fails()
{
ReplicatedKvCluster source{{"a", "b", "c"}};
assert(source.elect("a").has_value());
source.set_partition("b", 1);
source.set_partition("c", 1);
auto backup = capture_backup(source, "a", identity());
assert(!backup.has_value());
}
void trust_rotation_overlaps_then_revokes()
{
TrustStore trust{{"old-fp"}};
assert(trust.trusted("old-fp"));
assert(!trust.trusted("new-fp"));
assert(!trust.trusted(""));
// Empty rotation is rejected: verification is never disabled.
assert(!trust.begin_rotation({}).has_value());
auto generation = trust.begin_rotation({"new-fp"});
assert(generation.has_value());
// Overlap: both generations remain trusted while connections drain.
assert(trust.trusted("old-fp"));
assert(trust.trusted("new-fp"));
assert(trust.active_generations() == 2);
assert(trust.complete_rotation(*generation).has_value());
assert(!trust.trusted("old-fp"));
assert(trust.trusted("new-fp"));
assert(trust.active_generations() == 1);
assert(!trust.complete_rotation(99).has_value());
// An empty store trusts nothing.
TrustStore empty;
assert(!empty.trusted("anything"));
}
void mixed_version_rollout_readers_first()
{
RolloutGate gate{{"a", "b", "c"},
VersionPolicy{.format_version = 2, .min_reader = 1}};
assert(!gate.all_advertised());
assert(gate.report_version("a", 2).has_value());
assert(gate.report_version("b", 1).has_value());
assert(gate.report_version("c", 1).has_value());
// Old readers can still read the durable format.
assert(gate.admit_read("b").has_value());
// But new commands wait for every voter.
assert(!gate.admit_new_command("a").has_value());
assert(!gate.all_advertised());
assert(gate.report_version("b", 2).has_value());
assert(gate.report_version("c", 2).has_value());
assert(gate.admit_new_command("a").has_value());
assert(gate.all_advertised());
// Unknown voters are never assumed current.
assert(!gate.report_version("d", 2).has_value());
assert(!gate.admit_read("d").has_value());
}
void reader_floor_is_enforced()
{
RolloutGate gate{{"a"}, VersionPolicy{.format_version = 2,
.min_reader = 2}};
assert(gate.report_version("a", 1).has_value());
assert(!gate.admit_read("a").has_value());
assert(gate.report_version("a", 2).has_value());
assert(gate.admit_read("a").has_value());
}
} // namespace
int main()
{
backup_and_restore_retains_identity_and_state();
backup_without_quorum_fails();
trust_rotation_overlaps_then_revokes();
mixed_version_rollout_readers_first();
reader_floor_is_enforced();
std::puts("distributed operations ok");
return 0;
}