ReloadableApplications: retained-resource ledger and failure-injection matrix; reject publish after failed drain (P-RELOADABLE-05)

This commit is contained in:
faumaray committed 2026-12-04 10:24:12 +03:00
1 parent 2489098478
commit 2da3971760
5 files changed
+382 -1

No files matched your search

+6 -1
View File
@@ -12,7 +12,8 @@ add_library(reloadable_host STATIC
src/checkpoint.cpp
src/control.cpp
src/release_registry.cpp
src/reload_transaction.cpp)
src/reload_transaction.cpp
src/resources.cpp)
target_include_directories(reloadable_host PUBLIC include)
target_link_libraries(reloadable_host PUBLIC Void::Functional)
@@ -31,9 +32,13 @@ target_link_libraries(reloadable_host_checkpoint_test PRIVATE reloadable_host)
add_executable(reloadable_host_activation_test tests/activation_test.cpp)
target_link_libraries(reloadable_host_activation_test PRIVATE reloadable_host)
add_executable(reloadable_host_failure_matrix_test tests/reload_failure_matrix_test.cpp)
target_link_libraries(reloadable_host_failure_matrix_test PRIVATE reloadable_host)
enable_testing()
add_test(NAME reloadable_host_transaction COMMAND reloadable_host_test)
add_test(NAME reloadable_host_release COMMAND reloadable_host_release_test)
add_test(NAME reloadable_host_control COMMAND reloadable_host_control_test)
add_test(NAME reloadable_host_checkpoint COMMAND reloadable_host_checkpoint_test)
add_test(NAME reloadable_host_activation COMMAND reloadable_host_activation_test)
add_test(NAME reloadable_host_failure_matrix COMMAND reloadable_host_failure_matrix_test)
@@ -0,0 +1,64 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <map>
#include <mutex>
namespace ReloadableHost
{
/// Aggregate retained-resource permits shared by candidate and retired
/// generations. These are host-owned budgets, not a total-process RSS
/// promise: mapped images, stacks and kernel buffers are accounted
/// separately by the platform.
struct ResourceLimits {
std::size_t max_total_bytes{256ULL * 1024ULL * 1024ULL};
std::size_t max_generation_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t max_generations{4};
};
struct ResourceUsage {
std::size_t total_bytes{0};
std::size_t generations{0};
};
/// Thread-safe byte/generation ledger.
///
/// `reserve` is admission: it rejects an over-budget generation with
/// `exhausted` before any publication happens. A generation stays reserved
/// until every pin on it is gone and the host releases it, so budget
/// saturation is observable and recoverable rather than silent eviction.
class ResourceLedger
{
public:
explicit ResourceLedger(ResourceLimits limits = {});
[[nodiscard]] Void::Result::Result<void>
reserve(std::uint64_t generation, std::size_t bytes);
/// Release one reserved generation. False when it was not held.
bool release(std::uint64_t generation) noexcept;
[[nodiscard]] bool holds(std::uint64_t generation) const noexcept;
[[nodiscard]] ResourceUsage usage() const noexcept;
/// High-water mark, for retained-resource and RSS reporting.
[[nodiscard]] ResourceUsage peak_usage() const noexcept;
[[nodiscard]] const ResourceLimits& limits() const noexcept
{
return m_limits;
}
private:
mutable std::mutex m_mutex;
ResourceLimits m_limits;
std::map<std::uint64_t, std::size_t> m_reserved;
std::size_t m_total_bytes{0};
ResourceUsage m_peak{};
};
} // namespace ReloadableHost
@@ -145,6 +145,11 @@ namespace ReloadableHost
std::lock_guard lock{m_mutex};
if (!quiesced) {
// Quiescence was not reached: the transaction must not be
// publishable. The old owner keeps its pins and the candidate fails
// safely instead of racing a second writer.
m_phase = ReloadPhase::Failed;
m_outcome = ReloadOutcome::Failed;
m_error = "drain deadline expired with pinned calls";
return std::unexpected{
Void::Result::Error{Void::Result::ErrorKind::timeout, m_error}};
@@ -0,0 +1,87 @@
#include "reloadable_host/resources.hpp"
#include <algorithm>
#include <string>
#include <utility>
namespace ReloadableHost
{
namespace
{
[[nodiscard]] Void::Result::Error exhausted(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::exhausted,
std::move(message)};
}
[[nodiscard]] Void::Result::Error conflict(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
} // namespace
ResourceLedger::ResourceLedger(ResourceLimits limits)
: m_limits(limits)
{
}
Void::Result::Result<void>
ResourceLedger::reserve(std::uint64_t generation, std::size_t bytes)
{
std::lock_guard lock{m_mutex};
if (m_reserved.contains(generation)) {
return std::unexpected{
conflict("ResourceLedger: generation is already reserved")};
}
if (bytes > m_limits.max_generation_bytes) {
return std::unexpected{exhausted(
"ResourceLedger: generation exceeds max_generation_bytes")};
}
if (m_reserved.size() >= m_limits.max_generations) {
return std::unexpected{exhausted(
"ResourceLedger: retained generation cap reached; release "
"pinned generations before reloading")};
}
if (bytes > m_limits.max_total_bytes - m_total_bytes) {
return std::unexpected{exhausted(
"ResourceLedger: aggregate retained budget reached")};
}
m_reserved.emplace(generation, bytes);
m_total_bytes += bytes;
m_peak.total_bytes = std::max(m_peak.total_bytes, m_total_bytes);
m_peak.generations =
std::max(m_peak.generations, m_reserved.size());
return {};
}
bool ResourceLedger::release(std::uint64_t generation) noexcept
{
std::lock_guard lock{m_mutex};
const auto found = m_reserved.find(generation);
if (found == m_reserved.end()) {
return false;
}
m_total_bytes -= found->second;
m_reserved.erase(found);
return true;
}
bool ResourceLedger::holds(std::uint64_t generation) const noexcept
{
std::lock_guard lock{m_mutex};
return m_reserved.contains(generation);
}
ResourceUsage ResourceLedger::usage() const noexcept
{
std::lock_guard lock{m_mutex};
return ResourceUsage{m_total_bytes, m_reserved.size()};
}
ResourceUsage ResourceLedger::peak_usage() const noexcept
{
std::lock_guard lock{m_mutex};
return m_peak;
}
} // namespace ReloadableHost
@@ -0,0 +1,220 @@
#include "reloadable_host/activation.hpp"
#include "reloadable_host/release_registry.hpp"
#include "reloadable_host/reload_transaction.hpp"
#include "reloadable_host/resources.hpp"
#include <cassert>
#include <chrono>
#include <cstdio>
#include <string>
#include <vector>
namespace
{
using namespace ReloadableHost;
ReleaseDescriptor release(std::string id)
{
return ReleaseDescriptor{std::move(id), "/releases/x", 0};
}
void budget_enforces_generation_and_total_caps()
{
ResourceLimits limits;
limits.max_generation_bytes = 100;
limits.max_total_bytes = 150;
limits.max_generations = 2;
ResourceLedger ledger{limits};
// Per-generation cap.
auto oversized = ledger.reserve(1, 101);
assert(!oversized.has_value());
assert(oversized.error().kind() == Void::Result::ErrorKind::exhausted);
assert(ledger.reserve(1, 100).has_value());
// Aggregate cap (only 50 bytes left).
assert(!ledger.reserve(2, 51).has_value());
assert(ledger.reserve(2, 50).has_value());
// Generation cap.
assert(!ledger.reserve(3, 0).has_value());
// Duplicate reservation.
auto duplicate = ledger.reserve(1, 0);
assert(!duplicate.has_value());
assert(duplicate.error().kind() == Void::Result::ErrorKind::conflict);
const auto usage = ledger.usage();
assert(usage.total_bytes == 150);
assert(usage.generations == 2);
assert(ledger.peak_usage().total_bytes == 150);
// Release recovers admission.
assert(ledger.release(1));
assert(!ledger.release(1));
assert(ledger.usage().total_bytes == 50);
assert(ledger.reserve(3, 100).has_value());
assert(ledger.holds(3));
assert(!ledger.holds(1));
}
void uncooperative_pin_blocks_reload_until_released()
{
ReleaseRegistry registry{ReleaseLimits{.max_retained_generations = 1}};
assert(registry.publish(release("a"), {}).has_value());
const ReleaseHandle pinned = registry.acquire();
assert(pinned != nullptr);
assert(registry.publish(release("b"), {}).has_value());
// The pinned generation cannot be reclaimed: the cap rejects reload.
auto rejected = registry.publish(release("c"), {});
assert(!rejected.has_value());
assert(rejected.error().kind() == Void::Result::ErrorKind::exhausted);
assert(pinned->id == "a");
assert(registry.current()->id == "b");
// Dropping the pin lets collection progress.
const ReleaseHandle still_pinned = pinned;
assert(registry.collect() == 0);
assert(registry.retained() == 1);
}
void sustained_reload_stays_bounded()
{
ReleaseRegistry registry{ReleaseLimits{.max_retained_generations = 2}};
ResourceLimits limits;
limits.max_generations = 3;
limits.max_total_bytes = 3 * 1024;
limits.max_generation_bytes = 1024;
ResourceLedger ledger{limits};
MemoryActivationStorage storage;
ActivationJournal journal{storage};
Quiescence quiescence{
ReloadLimits{.drain_deadline = std::chrono::milliseconds{50},
.max_pins = 8}};
std::uint64_t next_generation = 1;
for (int cycle = 0; cycle < 200; ++cycle) {
const std::string id = "release-" + std::to_string(cycle);
assert(registry.publish(release(id), {}).has_value());
const std::uint64_t generation = next_generation++;
// Admission is checked before publishing work.
assert(ledger.reserve(generation, 512).has_value());
// A transient reader pins the generation; release it promptly.
{
assert(quiescence.admit().has_value());
const ReleaseHandle handle = registry.acquire();
assert(handle != nullptr);
quiescence.release();
}
// A reload transaction publishes and commits every cycle.
ReloadTransaction transaction{generation};
assert(transaction.prepare(
ReleaseCandidate{id, "/releases/x", generation}, {})
.has_value());
assert(transaction.drain(quiescence));
assert(transaction.publish().has_value());
transaction.commit(true);
const auto report = transaction.report();
assert(report.phase == ReloadPhase::Completed);
assert(report.outcome == ReloadOutcome::Published);
// The host reopens admissions once the new generation owns them.
quiescence.resume();
// Reclaim: registry collect plus ledger release of generations
// that are no longer pinned.
(void)registry.collect();
for (std::uint64_t old = 1; old < generation; ++old) {
(void)ledger.release(old);
}
assert(registry.retained() <= 2);
assert(ledger.usage().generations <= 2);
}
// Readers are admitted again after every drain.
assert(!quiescence.draining());
assert(quiescence.admit().has_value());
quiescence.release();
}
void drain_timeout_keeps_pins_and_blocks_publication()
{
Quiescence quiescence{
ReloadLimits{.drain_deadline = std::chrono::milliseconds{10},
.max_pins = 1}};
assert(quiescence.admit().has_value());
ReloadTransaction transaction{1};
assert(transaction
.prepare(ReleaseCandidate{"a", "/r", 1}, {})
.has_value());
auto drained = transaction.drain(quiescence);
assert(!drained.has_value());
assert(drained.error().kind() == Void::Result::ErrorKind::timeout);
// The publication point was never reached.
assert(!transaction.publish().has_value());
assert(quiescence.pins() == 1);
// Safe rollback: resume admission only after the pin drains.
quiescence.release();
quiescence.resume();
assert(!quiescence.draining());
transaction.cancel();
assert(transaction.report().outcome == ReloadOutcome::RolledBack);
}
void health_window_downtime_is_measured()
{
using Clock = std::chrono::steady_clock;
HealthWindow window{std::chrono::milliseconds{50}};
const auto start = Clock::now();
// Mutations are unavailable for the whole reversible window.
assert(!window.admit_write().has_value());
assert(window.admit_read());
assert(window.evaluate(start) == HealthWindow::Decision::Pending);
const auto commit_at = start + std::chrono::milliseconds{100};
assert(window.evaluate(commit_at) == HealthWindow::Decision::Commit);
// Downtime is at least the configured health window.
assert(commit_at - start >= std::chrono::milliseconds{50});
// A failed observation rolls back immediately instead of waiting.
HealthWindow failing{std::chrono::milliseconds{50}};
failing.observe(false);
assert(failing.evaluate(start) == HealthWindow::Decision::Rollback);
}
void committed_marker_survives_cleanup_failure()
{
MemoryActivationStorage storage;
ActivationJournal journal{storage};
ActivationRecord record;
record.transaction_id = 9;
record.previous_release = "a";
record.candidate_release = "b";
assert(journal.activate(record).has_value());
assert(journal.commit_healthy(9) == CommitOutcome::Committed);
// Cleanup is best effort after the durable marker: a failure must not
// turn the committed outcome into a rollback.
storage.fail_next_write(true);
const auto recovered = journal.reconcile();
assert(recovered.action == RecoveryAction::UseCandidate);
assert(recovered.cleanup_pending);
assert(journal.cleanup().has_value());
assert(journal.reconcile().action == RecoveryAction::None);
}
} // namespace
int main()
{
budget_enforces_generation_and_total_caps();
uncooperative_pin_blocks_reload_until_released();
sustained_reload_stays_bounded();
drain_timeout_keeps_pins_and_blocks_publication();
health_window_downtime_is_measured();
committed_marker_survives_cleanup_failure();
std::puts("reloadable-host failure matrix ok");
return 0;
}