ReloadableApplications: durable activation journal, crash recovery and read-only health window (P-RELOADABLE-04)

This commit is contained in:
faumaray committed 2026-12-04 10:15:38 +03:00
1 parent 03542d0d2f
commit 50595bdabc
4 files changed
+852

No files matched your search

+407
View File
@@ -0,0 +1,407 @@
#include "reloadable_host/activation.hpp"
#include <array>
#include <string>
#include <utility>
namespace ReloadableHost
{
namespace
{
constexpr std::array<std::byte, 4> kMagic{
std::byte{'V'}, std::byte{'A'}, std::byte{'C'}, std::byte{'T'}};
constexpr std::uint32_t kVersion{1};
[[nodiscard]] Void::Result::Error invalid(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
std::move(message)};
}
[[nodiscard]] Void::Result::Error corrupt(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::corrupt,
std::move(message)};
}
[[nodiscard]] Void::Result::Error conflict(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
void append_u32(std::vector<std::byte>& out, std::uint32_t value)
{
for (int shift = 24; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
}
}
void append_u64(std::vector<std::byte>& out, std::uint64_t value)
{
for (int shift = 56; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
}
}
[[nodiscard]] bool read_u32(std::span<const std::byte> in,
std::size_t& pos, std::uint32_t& value) noexcept
{
if (pos + 4 > in.size()) {
return false;
}
value = 0;
for (int i = 0; i < 4; ++i) {
value = (value << 8) |
std::to_integer<std::uint32_t>(in[pos + i]);
}
pos += 4;
return true;
}
[[nodiscard]] bool read_u64(std::span<const std::byte> in,
std::size_t& pos, std::uint64_t& value) noexcept
{
if (pos + 8 > in.size()) {
return false;
}
value = 0;
for (int i = 0; i < 8; ++i) {
value = (value << 8) |
std::to_integer<std::uint64_t>(in[pos + i]);
}
pos += 8;
return true;
}
void append_string(std::vector<std::byte>& out, std::string_view text)
{
append_u32(out, static_cast<std::uint32_t>(text.size()));
for (const char c : text) {
out.push_back(static_cast<std::byte>(
static_cast<unsigned char>(c)));
}
}
[[nodiscard]] bool read_string(std::span<const std::byte> in,
std::size_t& pos, std::string& out,
std::size_t max_bytes) noexcept
{
std::uint32_t length = 0;
if (!read_u32(in, pos, length) || length > max_bytes ||
pos + length > in.size()) {
return false;
}
out.clear();
out.reserve(length);
for (std::uint32_t i = 0; i < length; ++i) {
out.push_back(static_cast<char>(
std::to_integer<unsigned char>(in[pos + i])));
}
pos += length;
return true;
}
[[nodiscard]] std::uint64_t checksum(std::span<const std::byte> bytes)
{
std::uint64_t hash = 0xCBF29CE484222325ULL;
for (const std::byte byte : bytes) {
hash ^= std::to_integer<std::uint64_t>(byte);
hash *= 0x100000001B3ULL;
}
return hash;
}
[[nodiscard]] bool is_known_phase(ActivationPhase phase) noexcept
{
return phase == ActivationPhase::Activated ||
phase == ActivationPhase::HealthyCommitted ||
phase == ActivationPhase::RolledBack;
}
} // namespace
Void::Result::Result<std::vector<std::byte>>
encode_activation(const ActivationRecord& record, ActivationLimits limits)
{
if (record.previous_release.size() > limits.max_release_bytes ||
record.candidate_release.size() > limits.max_release_bytes) {
return std::unexpected{
invalid("Activation: release id exceeds the size limit")};
}
if (!is_known_phase(record.phase)) {
return std::unexpected{
invalid("Activation: cannot encode an unset phase")};
}
std::vector<std::byte> out;
out.insert(out.end(), kMagic.begin(), kMagic.end());
append_u32(out, kVersion);
append_u64(out, record.transaction_id);
append_u64(out, record.checkpoint_generation);
out.push_back(static_cast<std::byte>(record.phase));
append_string(out, record.previous_release);
append_string(out, record.candidate_release);
append_u64(out, checksum(out));
if (out.size() > limits.max_record_bytes) {
return std::unexpected{
invalid("Activation: record exceeds max_record_bytes")};
}
return out;
}
Void::Result::Result<ActivationRecord>
decode_activation(std::span<const std::byte> bytes,
ActivationLimits limits)
{
if (bytes.size() > limits.max_record_bytes ||
bytes.size() < kMagic.size() + 4 + 8 + 8 + 1 + 4 + 4 + 8) {
return std::unexpected{corrupt("Activation: record is truncated")};
}
if (!std::equal(kMagic.begin(), kMagic.end(), bytes.begin())) {
return std::unexpected{corrupt("Activation: bad magic")};
}
const std::size_t payload = bytes.size() - 8;
std::uint64_t stored_checksum = 0;
{
std::size_t pos = payload;
if (!read_u64(bytes, pos, stored_checksum)) {
return std::unexpected{
corrupt("Activation: missing checksum")};
}
}
if (checksum(bytes.first(payload)) != stored_checksum) {
return std::unexpected{
corrupt("Activation: checksum mismatch")};
}
std::size_t pos = kMagic.size();
std::uint32_t version = 0;
if (!read_u32(bytes, pos, version) || version != kVersion) {
return std::unexpected{
corrupt("Activation: unsupported record version")};
}
ActivationRecord record;
if (!read_u64(bytes, pos, record.transaction_id) ||
!read_u64(bytes, pos, record.checkpoint_generation) ||
pos >= payload) {
return std::unexpected{corrupt("Activation: malformed record")};
}
record.phase = static_cast<ActivationPhase>(
std::to_integer<unsigned char>(bytes[pos++]));
if (!is_known_phase(record.phase)) {
return std::unexpected{corrupt("Activation: unknown phase")};
}
if (!read_string(bytes, pos, record.previous_release,
limits.max_release_bytes) ||
!read_string(bytes, pos, record.candidate_release,
limits.max_release_bytes) ||
pos != payload) {
return std::unexpected{corrupt("Activation: malformed record")};
}
return record;
}
ActivationJournal::ActivationJournal(ActivationStorage& storage,
ActivationLimits limits)
: m_storage(storage), m_limits(limits)
{
}
Void::Result::Result<std::optional<ActivationRecord>>
ActivationJournal::load()
{
auto bytes = m_storage.read();
if (!bytes) {
return std::unexpected{std::move(bytes).error()};
}
if (!bytes->has_value()) {
return std::optional<ActivationRecord>{};
}
auto decoded = decode_activation(**bytes, m_limits);
if (!decoded) {
return std::unexpected{std::move(decoded).error()};
}
return std::optional<ActivationRecord>{std::move(*decoded)};
}
Void::Result::Result<void>
ActivationJournal::activate(ActivationRecord record)
{
record.phase = ActivationPhase::Activated;
auto existing = load();
if (!existing) {
return std::unexpected{std::move(existing).error()};
}
if (existing->has_value()) {
return std::unexpected{conflict(
"Activation: journal already holds a record; cleanup first")};
}
auto encoded = encode_activation(record, m_limits);
if (!encoded) {
return std::unexpected{std::move(encoded).error()};
}
if (auto written = m_storage.write(*encoded); !written) {
// The write may still have landed durably; make the caller decide
// from the journal rather than assuming nothing happened.
return std::unexpected{std::move(written).error()};
}
return {};
}
CommitOutcome
ActivationJournal::commit_healthy(std::uint64_t transaction_id) noexcept
{
auto existing = load();
if (!existing || !existing->has_value() ||
(*existing)->transaction_id != transaction_id) {
return CommitOutcome::Rejected;
}
ActivationRecord record = **existing;
if (record.phase == ActivationPhase::HealthyCommitted) {
return CommitOutcome::Committed;
}
if (record.phase != ActivationPhase::Activated) {
return CommitOutcome::Rejected;
}
record.phase = ActivationPhase::HealthyCommitted;
auto encoded = encode_activation(record, m_limits);
if (!encoded) {
return CommitOutcome::Unknown;
}
if (auto written = m_storage.write(*encoded); written) {
return CommitOutcome::Committed;
}
// Lost acknowledgement: re-read the durable record. The marker being
// present means committed; its absence is Unknown, never a rollback.
auto reread = load();
if (reread && reread->has_value() &&
(*reread)->phase == ActivationPhase::HealthyCommitted &&
(*reread)->transaction_id == transaction_id) {
return CommitOutcome::Committed;
}
return CommitOutcome::Unknown;
}
Void::Result::Result<void>
ActivationJournal::rollback(std::uint64_t transaction_id)
{
auto existing = load();
if (!existing) {
return std::unexpected{std::move(existing).error()};
}
if (!existing->has_value()) {
return std::unexpected{
conflict("Activation: no activation to roll back")};
}
ActivationRecord record = **existing;
if (record.transaction_id != transaction_id) {
return std::unexpected{
conflict("Activation: transaction is not the active one")};
}
if (record.phase == ActivationPhase::HealthyCommitted) {
return std::unexpected{conflict(
"Activation: healthy marker is durable; rollback is not the "
"recovery action")};
}
if (record.phase == ActivationPhase::RolledBack) {
return {};
}
record.phase = ActivationPhase::RolledBack;
auto encoded = encode_activation(record, m_limits);
if (!encoded) {
return std::unexpected{std::move(encoded).error()};
}
return m_storage.write(*encoded);
}
Void::Result::Result<void> ActivationJournal::cleanup()
{
auto existing = load();
if (!existing) {
return std::unexpected{std::move(existing).error()};
}
if (existing->has_value() &&
(*existing)->phase == ActivationPhase::Activated) {
return std::unexpected{conflict(
"Activation: cannot clean up an uncommitted activation")};
}
return m_storage.clear();
}
RecoveryDecision ActivationJournal::reconcile()
{
RecoveryDecision decision;
auto existing = load();
if (!existing) {
decision.action = RecoveryAction::Diagnostic;
decision.diagnostic = existing.error().message();
return decision;
}
if (!existing->has_value()) {
decision.action = RecoveryAction::None;
return decision;
}
decision.record = **existing;
switch (decision.record.phase) {
case ActivationPhase::Activated:
// Crash before the healthy marker: the activation is
// reversible, so the prior healthy release wins.
decision.action = RecoveryAction::UsePrevious;
break;
case ActivationPhase::HealthyCommitted:
// Committed even if reclaim never ran.
decision.action = RecoveryAction::UseCandidate;
decision.cleanup_pending = true;
break;
case ActivationPhase::RolledBack:
decision.action = RecoveryAction::UsePrevious;
break;
case ActivationPhase::None:
decision.action = RecoveryAction::Diagnostic;
decision.diagnostic = "Activation: unset phase";
break;
}
return decision;
}
Void::Result::Result<std::optional<ActivationRecord>>
ActivationJournal::current()
{
return load();
}
HealthWindow::HealthWindow(std::chrono::milliseconds duration) noexcept
: m_deadline(std::chrono::steady_clock::now() + duration)
{
}
Void::Result::Result<void> HealthWindow::admit_write() const
{
if (!m_open) {
return {};
}
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::overloaded,
"HealthWindow: mutations are closed during the read-only health "
"window"}};
}
void HealthWindow::observe(bool healthy) noexcept
{
if (!healthy) {
m_failed = true;
}
}
HealthWindow::Decision HealthWindow::evaluate(
std::chrono::steady_clock::time_point now) const noexcept
{
if (!m_open) {
return Decision::Pending;
}
if (m_failed) {
return Decision::Rollback;
}
return now >= m_deadline ? Decision::Commit : Decision::Pending;
}
} // namespace ReloadableHost