Files
stoneheart_at_home/tests/runtime_tests.cpp
T

462 lines
23 KiB
C++

#include "settlement/core/simulation_runtime.hpp"
#include "replay_diagnostics.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <sstream>
#include <stdexcept>
#include <thread>
namespace {
using namespace settlement;
using namespace std::chrono_literals;
using Void::Testing::require;
using Void::Testing::Test;
constexpr TrustedClient host{1};
constexpr TrustedClient guest{2};
std::string bytes(const World& world) {
return replay_diagnostics::canonical(world);
}
WorldCheckpoint colony(std::size_t workers = 2, WorkerPoolOptions options = {}) {
auto original = make_first_colony(2);
std::istringstream input(bytes(*original), std::ios::binary);
auto world = World::read_save(input, workers,
workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel, std::move(options));
Void::Uuid::Uuid id;
id.bytes.back() = 71;
auto rules = default_rules_manifest();
require(rules.has_value());
return {std::move(world), id, 1, std::move(*rules)};
}
template<class Submit>
RuntimeSubmission admitted(Submit submit) {
const auto limit = std::chrono::steady_clock::now() + 5s;
for (;;) {
auto operation = submit();
if (operation.admission != RuntimeAdmission::Busy) return operation;
require(std::chrono::steady_clock::now() < limit);
std::this_thread::yield();
}
}
RuntimeResult finished(RuntimeSubmission operation) {
require(operation.admission == RuntimeAdmission::Accepted);
require(operation.completion.wait_for(5s) == std::future_status::ready);
return operation.completion.get();
}
RuntimeResult fence(SimulationRuntime& runtime) {
return finished(admitted([&] { return runtime.synchronize(); }));
}
CommandEnvelope envelope(const PublishedSnapshot& snapshot, std::uint64_t request,
CommandKind kind, std::uint8_t value = 0) {
return {command_envelope_version, snapshot.identity.world, snapshot.identity.session,
snapshot.identity.city, request, CommandPayload{kind, {}, value}};
}
RuntimeResult send(SimulationRuntime& runtime, TrustedClient client, const CommandEnvelope& command) {
return finished(admitted([&] { return runtime.try_submit(client, command); }));
}
struct Gate {
std::mutex mutex;
std::condition_variable changed;
bool entered = false;
bool released = false;
void block() {
std::unique_lock lock(mutex);
entered = true;
changed.notify_all();
if (!changed.wait_for(lock, 5s, [&] { return released; })) throw std::runtime_error("gate timed out");
}
void wait() {
std::unique_lock lock(mutex);
require(changed.wait_for(lock, 5s, [&] { return entered; }));
}
void release() {
std::lock_guard lock(mutex);
released = true;
changed.notify_all();
}
};
std::atomic<bool> fail_after_mutation{false};
void command_observer(CommandMutationPhase phase) {
if (phase == CommandMutationPhase::AfterMutation && fail_after_mutation.exchange(false)) {
throw std::runtime_error("after command mutation");
}
}
struct [[= Void::Testing::name("RuntimeTests")]] RuntimeTests : Void::Testing::Suite<RuntimeTests> {
[[= Void::Testing::tag("runtime")]] Test test_queued_same_save_install_drains_old_world();
[[= Void::Testing::tag("runtime")]] Test test_fixed_clock_matches_reference_and_suspend_discards_idle_time();
[[= Void::Testing::tag("runtime")]] Test test_paused_commands_publish_and_two_clients_replay_exact_results();
[[= Void::Testing::tag("runtime")]] Test test_readers_and_save_capture_progress_during_real_worker_tick();
[[= Void::Testing::tag("runtime")]] Test test_tick_and_capture_failures_keep_previous_publication_and_recover();
[[= Void::Testing::tag("runtime")]] Test test_failed_command_keeps_committed_receipts_and_settles_queue();
[[= Void::Testing::tag("runtime")]] Test test_newer_load_supersedes_preparing_candidate_and_fences_old_commands();
[[= Void::Testing::tag("runtime")]] Test test_invalid_install_preserves_healthy_world_and_ticket_scope();
[[= Void::Testing::tag("runtime")]] Test test_capacity_and_shutdown_settle_accepted_work();
[[= Void::Testing::tag("runtime")]] Test test_command_capture_failure_settles_queued_mutations();
[[= Void::Testing::tag("runtime")]] Test test_exhausted_clock_faults_without_spinning();
};
Test RuntimeTests::test_queued_same_save_install_drains_old_world() {
auto gate = std::make_shared<Gate>();
auto clock = std::make_shared<Void::Time::ManualClock>();
std::atomic<std::size_t> started{0}, completed{0};
std::atomic<bool> install_saw_drained{false};
WorkerPoolOptions workers;
workers.before_execute = [&](std::size_t index) {
++started;
if (index == 0) gate->block();
};
workers.after_execute = [&](std::size_t) { ++completed; };
RuntimeOptions options{.clock = clock};
options.observer = [&](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeInstallCapture) {
install_saw_drained = started.load() >= 2 && started.load() == completed.load();
}
};
auto replacement = colony();
const auto replacement_bytes = replay_diagnostics::canonical(*replacement.world);
SimulationRuntime runtime(colony(2, std::move(workers)), std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto old_view = runtime.latest();
const auto old_bytes = replay_diagnostics::canonical(*old_view->world);
const auto stale_command = envelope(*old_view, 1, CommandKind::SetPaused, 1);
require(clock->advance(50ms).has_value());
runtime.notify_clock();
gate->wait();
const auto ticket = runtime.begin_load();
require(ticket.has_value());
auto installing = admitted([&] { return runtime.try_install(*ticket, replacement); });
require(installing.admission == RuntimeAdmission::Accepted && !replacement.world);
auto stale = admitted([&] { return runtime.try_submit(host, stale_command); });
require(stale.admission == RuntimeAdmission::Accepted);
require(installing.completion.wait_for(0s) == std::future_status::timeout);
require(stale.completion.wait_for(0s) == std::future_status::timeout);
require(!install_saw_drained && started.load() > completed.load());
require(runtime.latest() == old_view);
require(runtime.snapshot_for_save().value() == old_view);
require(replay_diagnostics::canonical(*old_view->world) == old_bytes);
gate->release();
const auto installed = finished(std::move(installing));
require(installed.outcome == RuntimeOutcome::Completed && install_saw_drained);
require(installed.snapshot->identity.world == old_view->identity.world);
require(installed.snapshot->identity.session != old_view->identity.session);
require(installed.snapshot->world->tick() == 0);
const auto rejected = finished(std::move(stale));
require(rejected.receipt && rejected.receipt->status == DispatchStatus::StaleSession);
const auto drained_count = completed.load();
require(fence(runtime).outcome == RuntimeOutcome::Completed);
require(runtime.latest() == installed.snapshot);
require(replay_diagnostics::canonical(*runtime.latest()->world) == replacement_bytes);
require(replay_diagnostics::canonical(*old_view->world) == old_bytes);
require(completed.load() == drained_count && started.load() == completed.load());
auto serial = colony(1);
serial.world->step();
require(clock->advance(50ms).has_value());
require(fence(runtime).outcome == RuntimeOutcome::Completed);
const auto diagnostic = replay_diagnostics::difference(*serial.world, *runtime.latest()->world,
{1, 2, "old-worker-held", "same-save-replacement", 4096});
if (!diagnostic.empty()) throw std::runtime_error(diagnostic);
require(completed.load() == drained_count);
}
Test RuntimeTests::test_fixed_clock_matches_reference_and_suspend_discards_idle_time() {
for (const auto workers : {1U, 2U, 6U, 12U}) {
auto clock = std::make_shared<Void::Time::ManualClock>();
auto reference = colony(1);
SimulationRuntime runtime(colony(workers), {.clock = clock});
for (int i = 0; i < 20; ++i) {
require(clock->advance(50ms).has_value());
require(fence(runtime).outcome == RuntimeOutcome::Completed);
reference.world->step();
require(bytes(*runtime.latest()->world) == bytes(*reference.world));
}
require(runtime.latest()->world->tick() == 20);
require(finished(admitted([&] { return runtime.set_ticking(false); })).outcome == RuntimeOutcome::Completed);
require(clock->advance(1h).has_value());
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 20);
static_cast<void>(finished(admitted([&] { return runtime.set_ticking(true); })));
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 20);
require(clock->advance(1s).has_value());
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 40);
}
}
Test RuntimeTests::test_paused_commands_publish_and_two_clients_replay_exact_results() {
auto clock = std::make_shared<Void::Time::ManualClock>();
SimulationRuntime runtime(colony(), {.clock = clock});
const auto initial = runtime.latest();
auto pause = envelope(*initial, 1, CommandKind::SetPaused, 1);
auto result = send(runtime, host, pause);
require(result.receipt->command_status == CommandStatus::Accepted);
require(result.snapshot->world->paused() && result.snapshot->world->tick() == 0);
require(result.snapshot->revision > initial->revision);
require(clock->advance(1h).has_value());
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 0);
auto invalid = envelope(*initial, 1, CommandKind::SetPriority, 255);
const auto rejected = send(runtime, guest, invalid);
require(rejected.receipt->status == DispatchStatus::Completed);
require(rejected.receipt->command_status != CommandStatus::Accepted);
const auto prior = runtime.latest();
require(send(runtime, guest, invalid).receipt == rejected.receipt);
require(runtime.latest() == prior);
auto conflict = invalid;
std::get<CommandPayload>(conflict.payload).value = 1;
require(send(runtime, guest, conflict).receipt->status == DispatchStatus::Conflict);
require(send(runtime, host, pause).receipt == result.receipt);
require(runtime.latest()->next_requests == (std::array<std::uint64_t, 2>{2, 2}));
auto resume = envelope(*initial, 2, CommandKind::SetPaused, 0);
require(send(runtime, host, resume).receipt->command_status == CommandStatus::Accepted);
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 0);
require(clock->advance(50ms).has_value());
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 1);
}
Test RuntimeTests::test_readers_and_save_capture_progress_during_real_worker_tick() {
auto gate = std::make_shared<Gate>();
auto clock = std::make_shared<Void::Time::ManualClock>();
WorkerPoolOptions workers;
workers.before_execute = [gate](std::size_t) { gate->block(); };
SimulationRuntime runtime(colony(2, std::move(workers)), {.clock = clock});
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto before = runtime.latest();
const auto saved = bytes(*before->world);
require(clock->advance(50ms).has_value());
runtime.notify_clock();
gate->wait();
auto reader = std::async(std::launch::async, [&] {
const auto snapshot = runtime.snapshot_for_save();
require(snapshot.has_value() && *snapshot == before);
return bytes(*runtime.latest()->world);
});
require(reader.wait_for(1s) == std::future_status::ready);
require(reader.get() == saved);
gate->release();
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 1);
require(bytes(*before->world) == saved);
}
Test RuntimeTests::test_tick_and_capture_failures_keep_previous_publication_and_recover() {
for (const bool stage_failure : {false, true}) {
auto clock = std::make_shared<Void::Time::ManualClock>();
auto fail = std::make_shared<std::atomic<bool>>(false);
WorkerPoolOptions workers;
if (stage_failure) workers.before_execute = [fail](std::size_t) {
if (fail->exchange(false)) throw std::runtime_error("stage failure");
};
RuntimeOptions options{.clock = clock};
options.observer = [fail, stage_failure](RuntimePhase phase) {
if (!stage_failure && phase == RuntimePhase::BeforeCapture && fail->exchange(false)) {
throw std::runtime_error("snapshot preparation failure");
}
};
SimulationRuntime runtime(colony(2, std::move(workers)), std::move(options));
const auto previous = runtime.latest();
fail->store(true);
require(clock->advance(50ms).has_value());
require(fence(runtime).outcome == RuntimeOutcome::Faulted);
require(runtime.view().state == RuntimeState::Faulted && runtime.view().failure);
require(runtime.latest() == previous && !runtime.snapshot_for_save());
auto command = envelope(*previous, 1, CommandKind::SetPaused, 1);
require(send(runtime, host, command).outcome == RuntimeOutcome::Faulted);
auto ticket = runtime.begin_load();
require(ticket.has_value());
auto replacement = colony();
const auto installed = finished(admitted([&] { return runtime.try_install(*ticket, replacement); }));
require(installed.outcome == RuntimeOutcome::Completed && !replacement.world);
require(runtime.view().state == RuntimeState::Running && !runtime.view().failure);
require(runtime.latest()->identity.session != previous->identity.session);
require(send(runtime, host, command).receipt->status == DispatchStatus::StaleSession);
require(clock->advance(50ms).has_value());
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 1);
}
}
Test RuntimeTests::test_failed_command_keeps_committed_receipts_and_settles_queue() {
auto gate = std::make_shared<Gate>();
auto armed = std::make_shared<std::atomic<bool>>(false);
auto clock = std::make_shared<Void::Time::ManualClock>();
RuntimeOptions options{.clock = clock, .dispatcher = {.mutation_observer = command_observer}};
options.observer = [gate, armed](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeCapture && armed->load()) gate->block();
};
SimulationRuntime runtime(colony(), std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); fail_after_mutation.store(false); });
const auto first = envelope(*runtime.latest(), 1, CommandKind::SetPaused, 1);
const auto accepted = send(runtime, host, first);
const auto committed = runtime.latest();
fail_after_mutation.store(true);
auto second = envelope(*committed, 2, CommandKind::SetPriority, 1);
require(send(runtime, host, second).outcome == RuntimeOutcome::Faulted);
require(runtime.latest() == committed);
require(runtime.lookup(host, first) == accepted.receipt);
require(!runtime.lookup(host, second));
require(send(runtime, host, first).receipt == accepted.receipt);
require(send(runtime, host, second).outcome == RuntimeOutcome::Faulted);
require(!runtime.snapshot_for_save());
require(fence(runtime).outcome == RuntimeOutcome::Faulted);
const auto ticket = runtime.begin_load();
auto replacement = colony();
require(finished(admitted([&] { return runtime.try_install(*ticket, replacement); })).outcome == RuntimeOutcome::Completed);
armed->store(true);
const auto before = runtime.latest();
auto change = envelope(*before, 1, CommandKind::SetPaused, 1);
auto pending = admitted([&] { return runtime.try_submit(host, change); });
gate->wait();
require(runtime.latest() == before && !runtime.lookup(host, change));
armed->store(false);
gate->release();
require(finished(std::move(pending)).receipt->command_status == CommandStatus::Accepted);
}
Test RuntimeTests::test_newer_load_supersedes_preparing_candidate_and_fences_old_commands() {
auto gate = std::make_shared<Gate>();
auto clock = std::make_shared<Void::Time::ManualClock>();
RuntimeOptions options{.clock = clock};
options.observer = [gate](RuntimePhase phase) { if (phase == RuntimePhase::BeforeInstallCapture) gate->block(); };
SimulationRuntime runtime(colony(), std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto previous = runtime.latest();
const auto first = runtime.begin_load();
auto earlier = colony();
auto installing = admitted([&] { return runtime.try_install(*first, earlier); });
gate->wait();
const auto second = runtime.begin_load();
require(second.has_value());
gate->release();
require(finished(std::move(installing)).outcome == RuntimeOutcome::Superseded);
require(runtime.latest() == previous);
auto newer = colony();
require(finished(admitted([&] { return runtime.try_install(*second, newer); })).outcome == RuntimeOutcome::Completed);
require(runtime.latest()->identity.world == previous->identity.world);
require(runtime.latest()->identity.session != previous->identity.session);
auto stale = envelope(*previous, 1, CommandKind::SetPaused, 1);
require(send(runtime, host, stale).receipt->status == DispatchStatus::StaleSession);
auto reused = colony();
require(finished(admitted([&] { return runtime.try_install(*second, reused); })).outcome == RuntimeOutcome::Superseded);
}
Test RuntimeTests::test_invalid_install_preserves_healthy_world_and_ticket_scope() {
auto clock = std::make_shared<Void::Time::ManualClock>();
auto fail = std::make_shared<std::atomic<bool>>(false);
RuntimeOptions options{.clock = clock};
options.observer = [fail](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeInstallCapture && fail->load()) throw std::bad_alloc();
};
SimulationRuntime runtime(colony(), std::move(options));
const auto previous = runtime.latest();
auto invalid = colony();
invalid.world_id = {};
auto ticket = runtime.begin_load();
require(finished(admitted([&] { return runtime.try_install(*ticket, invalid); })).outcome == RuntimeOutcome::InvalidCandidate);
require(runtime.latest() == previous && runtime.view().state == RuntimeState::Running);
fail->store(true);
auto valid = colony();
require(finished(admitted([&] { return runtime.try_install(*ticket, valid); })).outcome == RuntimeOutcome::InvalidCandidate);
require(runtime.latest() == previous && runtime.snapshot_for_save());
fail->store(false);
require(clock->advance(50ms).has_value());
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 1);
}
Test RuntimeTests::test_capacity_and_shutdown_settle_accepted_work() {
auto gate = std::make_shared<Gate>();
auto clock = std::make_shared<Void::Time::ManualClock>();
RuntimeOptions options{.capacity = 2, .clock = clock};
options.observer = [gate](RuntimePhase phase) { if (phase == RuntimePhase::BeforeCapture) gate->block(); };
SimulationRuntime runtime(colony(), std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto before = runtime.latest();
auto command = envelope(*before, 1, CommandKind::SetPaused, 1);
auto active = admitted([&] { return runtime.try_submit(host, command); });
gate->wait();
auto queued = admitted([&] { return runtime.synchronize(); });
auto full = runtime.synchronize();
require(full.admission == RuntimeAdmission::Busy && !full.completion.valid());
auto candidate = colony();
auto ticket = runtime.begin_load();
require(runtime.try_install(*ticket, candidate).admission == RuntimeAdmission::Busy && candidate.world);
auto stopped = std::async(std::launch::async, [&] { runtime.shutdown(); });
const auto deadline = std::chrono::steady_clock::now() + 5s;
while (runtime.view().state != RuntimeState::Closed) {
require(std::chrono::steady_clock::now() < deadline);
std::this_thread::yield();
}
gate->release();
require(finished(std::move(active)).outcome == RuntimeOutcome::Closed);
require(finished(std::move(queued)).outcome == RuntimeOutcome::Closed);
require(stopped.wait_for(5s) == std::future_status::ready);
stopped.get();
runtime.shutdown();
require(runtime.latest() == before);
require(runtime.try_submit(host, command).admission == RuntimeAdmission::Closed);
require(runtime.begin_load().error() == RuntimeAdmission::Closed);
require(!runtime.snapshot_for_save());
}
Test RuntimeTests::test_command_capture_failure_settles_queued_mutations() {
auto gate = std::make_shared<Gate>();
auto fail = std::make_shared<std::atomic<bool>>(false);
auto clock = std::make_shared<Void::Time::ManualClock>();
RuntimeOptions options{.clock = clock};
options.observer = [gate, fail](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeCapture && fail->load()) {
gate->block();
throw std::bad_alloc();
}
};
SimulationRuntime runtime(colony(), std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto first = envelope(*runtime.latest(), 1, CommandKind::SetPaused, 1);
const auto accepted = send(runtime, host, first);
const auto committed = runtime.latest();
const auto second = envelope(*committed, 2, CommandKind::SetPriority, 1);
fail->store(true);
auto active = admitted([&] { return runtime.try_submit(host, second); });
gate->wait();
auto third = envelope(*committed, 3, CommandKind::SetPaused, 0);
auto queued = admitted([&] { return runtime.try_submit(host, third); });
auto repeat = admitted([&] { return runtime.try_submit(host, first); });
require(runtime.lookup(host, first) == accepted.receipt);
require(!runtime.lookup(host, second));
gate->release();
require(finished(std::move(active)).outcome == RuntimeOutcome::Faulted);
require(finished(std::move(queued)).outcome == RuntimeOutcome::Faulted);
require(finished(std::move(repeat)).receipt == accepted.receipt);
require(runtime.latest() == committed && !runtime.snapshot_for_save());
}
Test RuntimeTests::test_exhausted_clock_faults_without_spinning() {
auto clock = std::make_shared<Void::Time::ManualClock>();
require(clock->set(Void::Time::MonotonicClock::time_point::max()).has_value());
SimulationRuntime runtime(colony(), {.clock = clock});
require(fence(runtime).outcome == RuntimeOutcome::Faulted);
require(runtime.latest()->world->tick() == 0);
require(runtime.view().failure != nullptr);
}
} // namespace