Files
stoneheart_at_home/tests/session_tests.cpp

408 lines
23 KiB
C++

#include "settlement/core/command_dispatcher.hpp"
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <array>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
namespace {
using namespace settlement;
using Void::Testing::expect_throw;
using Void::Testing::Test;
constexpr TrustedClient host{colony_host};
constexpr TrustedClient guest{2};
thread_local std::optional<CommandMutationPhase> injected_failure;
void observe_mutation(CommandMutationPhase phase) {
if (injected_failure == phase) throw std::runtime_error("injected command mutation failure");
}
void require(bool condition, std::string_view message) {
if (!condition) throw std::runtime_error(std::string(message));
}
SessionIdentity session_identity(std::uint8_t incarnation = 1) {
Void::Uuid::Uuid world;
world.bytes.back() = 41;
Void::Uuid::Uuid session;
session.bytes.back() = incarnation;
return {world, session, 1};
}
CommandEnvelope envelope(std::uint64_t request, SessionPayload payload,
SessionIdentity identity = session_identity()) {
return {command_envelope_version, identity.world, identity.session, identity.city, request, payload};
}
std::string saved_state(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
}
std::unique_ptr<World> load_state(const std::string& bytes, std::size_t workers = 2) {
std::istringstream input(bytes, std::ios::binary);
return World::read_save(input, workers,
workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel);
}
void require_completed(const DispatchReceipt& receipt, CommandStatus expected, std::uint64_t tick,
std::uint64_t revision) {
require(receipt == DispatchReceipt{DispatchStatus::Completed, expected, tick, revision},
"the completed result differs from the authoritative outcome");
}
struct [[= Void::Testing::name("SessionTests")]] SessionTests : Void::Testing::Suite<SessionTests> {
[[= Void::Testing::tag("session")]] Test test_session_configuration_requires_valid_identity_and_capacity();
[[= Void::Testing::tag("session")]] Test test_two_clients_replay_accepted_and_rejected_results();
[[= Void::Testing::tag("session")]] Test test_conflicting_reuse_checks_every_payload_field_and_context();
[[= Void::Testing::tag("session")]] Test test_transient_rejections_preserve_request_order();
[[= Void::Testing::tag("session")]] Test test_capacity_retains_all_old_receipts_for_each_client();
[[= Void::Testing::tag("session")]] Test test_rollback_fences_old_session_before_receipt_lookup();
[[= Void::Testing::tag("session")]] Test test_dispatch_is_identical_in_reference_and_worker_modes();
[[= Void::Testing::tag("session")]] Test test_legacy_cabin_placement_uses_the_same_ledger();
[[= Void::Testing::tag("session")]] Test test_ledger_can_be_staged_with_an_unpublished_world();
[[= Void::Testing::tag("session")]] Test test_exception_fences_uncommitted_receipts_and_preserves_old_results();
};
Test SessionTests::test_session_configuration_requires_valid_identity_and_capacity() {
auto invalid = session_identity();
invalid.world = {};
expect_throw<std::invalid_argument>([&] { CommandDispatcher dispatcher(invalid); });
invalid = session_identity();
invalid.session = {};
expect_throw<std::invalid_argument>([&] { CommandDispatcher dispatcher(invalid); });
invalid = session_identity();
invalid.city = 0;
expect_throw<std::invalid_argument>([&] { CommandDispatcher dispatcher(invalid); });
expect_throw<std::invalid_argument>([] { CommandDispatcher dispatcher(session_identity(), {0}); });
expect_throw<std::invalid_argument>([] {
CommandDispatcher dispatcher(session_identity(), {std::numeric_limits<std::size_t>::max()});
});
CommandDispatcher dispatcher(session_identity());
require(dispatcher.next_request(host) == 1 && dispatcher.next_request(guest) == 1 &&
dispatcher.next_request({0}) == 0 && !dispatcher.faulted(),
"new session sequence or client validation is incorrect");
}
Test SessionTests::test_two_clients_replay_accepted_and_rejected_results() {
auto world = make_first_colony(2);
CommandDispatcher dispatcher(session_identity());
const auto pause = envelope(1, CommandPayload{CommandKind::SetPaused, {}, 1});
const auto guest_pause = envelope(1, CommandPayload{CommandKind::SetPaused, {}, 0});
const auto first_bed = envelope(2, CommandPayload{CommandKind::PlaceBed, {16, 18}});
const auto second_bed = envelope(2, CommandPayload{CommandKind::PlaceBed, {17, 18}, 1});
const auto occupied = envelope(3, CommandPayload{CommandKind::PlaceBed, {16, 18}});
const auto resume = envelope(3, CommandPayload{CommandKind::SetPaused, {}, 0});
const auto paused = dispatcher.dispatch(*world, host, pause);
const auto denied = dispatcher.dispatch(*world, guest, guest_pause);
const auto host_bed = dispatcher.dispatch(*world, host, first_bed);
const auto guest_bed = dispatcher.dispatch(*world, guest, second_bed);
const auto invalid = dispatcher.dispatch(*world, guest, occupied);
require_completed(paused, CommandStatus::Accepted, 0, 1);
require_completed(denied, CommandStatus::Unauthorized, 0, 1);
require_completed(host_bed, CommandStatus::Accepted, 0, 2);
require_completed(guest_bed, CommandStatus::Accepted, 0, 3);
require_completed(invalid, CommandStatus::InvalidTarget, 0, 3);
require_completed(dispatcher.dispatch(*world, host, resume), CommandStatus::Accepted, 0, 4);
for (int tick = 0; tick < 30; ++tick) world->step();
const auto before_retry = saved_state(*world);
require(dispatcher.dispatch(*world, host, pause) == paused &&
dispatcher.dispatch(*world, guest, guest_pause) == denied &&
dispatcher.dispatch(*world, host, first_bed) == host_bed &&
dispatcher.dispatch(*world, guest, second_bed) == guest_bed &&
dispatcher.dispatch(*world, guest, occupied) == invalid,
"a delayed retry changed its original outcome, tick or revision");
require(saved_state(*world) == before_retry && !world->paused(),
"a repeated operation applied its effects again");
const auto corrected = envelope(4, CommandPayload{CommandKind::PlaceBed, {18, 18}});
require_completed(dispatcher.dispatch(*world, guest, corrected), CommandStatus::Accepted, 30, 5);
require(world->next_command_sequence(1) == 4 && world->next_command_sequence(2) == 3 &&
dispatcher.next_request(host) == 4 && dispatcher.next_request(guest) == 5,
"dispatcher rejections changed the legacy accepted-command sequence");
require(dispatcher.lookup(guest, occupied) == invalid,
"reconnection to the same trusted slot lost a rejected result");
}
Test SessionTests::test_conflicting_reuse_checks_every_payload_field_and_context() {
auto world = make_first_colony(2);
CommandDispatcher dispatcher(session_identity());
const auto original = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}});
const auto recorded = dispatcher.dispatch(*world, host, original);
const auto before = saved_state(*world);
const auto conflict = [&](CommandEnvelope changed) {
require(dispatcher.dispatch(*world, host, changed).status == DispatchStatus::Conflict,
"changed payload reused a completed request");
require(saved_state(*world) == before && dispatcher.receipt_count(host) == 1,
"conflicting reuse changed the world or its original record");
};
auto changed = original;
++changed.city;
conflict(changed);
changed = original;
std::get<CommandPayload>(changed.payload).kind = CommandKind::SetForaging;
conflict(changed);
changed = original;
++std::get<CommandPayload>(changed.payload).cell.x;
conflict(changed);
changed = original;
++std::get<CommandPayload>(changed.payload).value;
conflict(changed);
changed = original;
++std::get<CommandPayload>(changed.payload).destination.y;
conflict(changed);
changed = original;
++std::get<CommandPayload>(changed.payload).resident;
conflict(changed);
changed = original;
changed.payload = LegacyCabinPayload{{5, 5}, {3, 3}, {4, 3}};
conflict(changed);
changed = original;
++changed.version;
require(dispatcher.dispatch(*world, host, changed).status == DispatchStatus::UnsupportedVersion,
"cached result bypassed protocol validation");
changed = original;
changed.world.bytes.back() ^= 1;
require(dispatcher.dispatch(*world, host, changed).status == DispatchStatus::WrongWorld,
"cached result bypassed world validation");
changed = original;
changed.session.bytes.back() ^= 1;
require(dispatcher.dispatch(*world, host, changed).status == DispatchStatus::StaleSession,
"cached result bypassed incarnation validation");
require(dispatcher.dispatch(*world, {0}, original).status == DispatchStatus::UnauthorizedClient &&
dispatcher.dispatch(*world, {3}, original).status == DispatchStatus::UnauthorizedClient &&
dispatcher.dispatch(*world, host, original) == recorded && saved_state(*world) == before,
"a transport identity error changed a retained result");
}
Test SessionTests::test_transient_rejections_preserve_request_order() {
auto world = make_first_colony(2);
CommandDispatcher dispatcher(session_identity());
const auto before = saved_state(*world);
auto command = envelope(0, CommandPayload{CommandKind::PlaceBed, {16, 18}});
require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::InvalidRequest,
"request zero was accepted");
command.request = std::numeric_limits<std::uint64_t>::max();
require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::OutOfOrder,
"request arithmetic wrapped at the uint64 boundary");
command.request = 2;
require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::OutOfOrder &&
dispatcher.next_request(host) == 1 && !dispatcher.lookup(host, command),
"a missing request advanced the ledger");
command.request = 1;
command.session = {};
require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::StaleSession,
"nil session was accepted");
command = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}});
command.world = {};
require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::WrongWorld &&
saved_state(*world) == before,
"nil world or transient rejection changed state");
command = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}});
command.city = 9;
require_completed(dispatcher.dispatch(*world, host, command), CommandStatus::Unauthorized, 0, 0);
require(saved_state(*world) == before && dispatcher.next_request(host) == 2,
"city denial mutated state or failed to retain the rejection");
command.city = 1;
require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::Conflict,
"corrected city reused an already completed number");
command.request = 2;
require_completed(dispatcher.dispatch(*world, host, command), CommandStatus::Accepted, 0, 1);
const auto unknown = envelope(3, CommandPayload{static_cast<CommandKind>(255)});
require_completed(dispatcher.dispatch(*world, host, unknown), CommandStatus::InvalidTarget, 0, 1);
require(dispatcher.next_request(host) == 4 && world->next_command_sequence(1) == 2,
"unsupported action confused dispatcher and legacy sequences");
const auto extreme_room = envelope(4, CommandPayload{CommandKind::PlaceRoom,
{std::numeric_limits<std::int32_t>::min(), 0}, 0, {std::numeric_limits<std::int32_t>::max(), 4}});
const auto before_extreme = saved_state(*world);
require_completed(dispatcher.dispatch(*world, host, extreme_room), CommandStatus::InvalidTarget, 0, 1);
require(saved_state(*world) == before_extreme, "unbounded room coordinates reached legacy size arithmetic");
}
Test SessionTests::test_capacity_retains_all_old_receipts_for_each_client() {
auto world = make_first_colony(2);
CommandDispatcher dispatcher(session_identity(), {2});
const auto first = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}});
const auto second = envelope(2, CommandPayload{CommandKind::PlaceBed, {16, 18}});
const auto one = dispatcher.dispatch(*world, host, first);
const auto two = dispatcher.dispatch(*world, host, second);
require_completed(one, CommandStatus::Accepted, 0, 1);
require_completed(two, CommandStatus::InvalidTarget, 0, 1);
const auto before = saved_state(*world);
const auto third = envelope(3, CommandPayload{CommandKind::PlaceBed, {17, 18}});
require(dispatcher.dispatch(*world, host, third).status == DispatchStatus::Busy &&
dispatcher.dispatch(*world, host, third).status == DispatchStatus::Busy,
"full receipt ledger admitted a new effect");
require(dispatcher.next_request(host) == 3 && dispatcher.receipt_count(host) == 2 &&
dispatcher.dispatch(*world, host, first) == one && dispatcher.dispatch(*world, host, second) == two &&
saved_state(*world) == before,
"capacity backpressure evicted/reexecuted an old receipt");
require_completed(dispatcher.dispatch(*world, guest,
envelope(1, CommandPayload{CommandKind::PlaceBed, {17, 18}})), CommandStatus::Accepted, 0, 2);
require(dispatcher.next_request(guest) == 2 && dispatcher.receipt_count({0}) == 0,
"one client's retention capacity blocked another client");
}
Test SessionTests::test_rollback_fences_old_session_before_receipt_lookup() {
auto world = make_first_colony(2);
const auto early = saved_state(*world);
CommandDispatcher previous(session_identity());
const auto old = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}});
require_completed(previous.dispatch(*world, host, old), CommandStatus::Accepted, 0, 1);
for (int tick = 0; tick < 20; ++tick) world->step();
auto restored = load_state(early);
CommandDispatcher current(session_identity(2));
require(current.dispatch(*restored, host, old).status == DispatchStatus::StaleSession &&
current.lookup(host, old)->status == DispatchStatus::StaleSession &&
saved_state(*restored) == early && current.next_request(host) == 1,
"a request from before rollback changed or queried the new incarnation");
const auto fresh = envelope(1, std::get<CommandPayload>(old.payload), session_identity(2));
const auto accepted = current.dispatch(*restored, host, fresh);
require_completed(accepted, CommandStatus::Accepted, 0, 1);
const auto after = saved_state(*restored);
require(current.dispatch(*restored, host, fresh) == accepted && saved_state(*restored) == after,
"a retry in the new session executed twice");
}
Test SessionTests::test_dispatch_is_identical_in_reference_and_worker_modes() {
const auto initial = make_first_colony(2);
const auto bytes = saved_state(*initial);
constexpr std::array<std::size_t, 4> worker_counts{1, 2, 6, 12};
std::array<std::unique_ptr<World>, 4> worlds;
std::array dispatchers{CommandDispatcher(session_identity()), CommandDispatcher(session_identity()),
CommandDispatcher(session_identity()), CommandDispatcher(session_identity())};
for (std::size_t index = 0; index < worlds.size(); ++index) worlds[index] = load_state(bytes, worker_counts[index]);
const auto issue = [&](TrustedClient client, CommandEnvelope command, CommandStatus status) {
const auto expected = dispatchers[0].dispatch(*worlds[0], client, command);
require(expected.status == DispatchStatus::Completed && expected.command_status == status,
"reference command failed its expected domain check");
for (std::size_t index = 1; index < worlds.size(); ++index) {
require(dispatchers[index].dispatch(*worlds[index], client, command) == expected,
"dispatch receipt differs across worker modes");
}
};
issue(host, envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}), CommandStatus::Accepted);
issue(guest, envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}), CommandStatus::InvalidTarget);
issue(guest, envelope(2, CommandPayload{CommandKind::PlaceBed, {17, 18}, 1}), CommandStatus::Accepted);
issue(host, envelope(2, CommandPayload{CommandKind::PlaceBed, {18, 18}}), CommandStatus::Accepted);
issue(host, envelope(3, CommandPayload{CommandKind::SetForaging, {14, 12}, 1}), CommandStatus::Accepted);
for (int tick = 0; tick < 700; ++tick) {
if (tick == 30) {
issue(host, envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}), CommandStatus::Accepted);
issue(guest, envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}), CommandStatus::InvalidTarget);
}
worlds[0]->step();
const auto expected = saved_state(*worlds[0]);
for (std::size_t index = 1; index < worlds.size(); ++index) {
worlds[index]->step();
require(saved_state(*worlds[index]) == expected, "authoritative dispatch world diverged by worker count");
}
}
require(worlds[0]->scenario_progress().completed && worlds[0]->meals_eaten() >= 3,
"the dispatched colony failed to build and feed its residents");
}
Test SessionTests::test_legacy_cabin_placement_uses_the_same_ledger() {
World world(1, 10, 10);
CommandDispatcher dispatcher(session_identity());
const auto cabin = envelope(1, LegacyCabinPayload{{5, 5}, {3, 3}, {4, 3}});
const auto denied = dispatcher.dispatch(world, guest, cabin);
require_completed(denied, CommandStatus::Unauthorized, 0, 0);
const auto accepted = dispatcher.dispatch(world, host, cabin);
require_completed(accepted, CommandStatus::Accepted, 0, 1);
require(world.production_orders().size() == 6 && world.production_orders().back().recipe == RecipeId::BuildCabin,
"legacy placement did not queue its cabin and five material orders");
const auto bytes = saved_state(world);
require(dispatcher.dispatch(world, host, cabin) == accepted &&
dispatcher.dispatch(world, guest, cabin) == denied && saved_state(world) == bytes,
"legacy cabin retry was applied again");
auto occupied = cabin;
occupied.request = 2;
require_completed(dispatcher.dispatch(world, host, occupied), CommandStatus::InvalidTarget, 0, 1);
require(saved_state(world) == bytes && dispatcher.next_request(host) == 3,
"invalid legacy placement partially changed the world");
auto changed = cabin;
std::get<LegacyCabinPayload>(changed.payload).sawmill.x = 2;
require(dispatcher.dispatch(world, host, changed).status == DispatchStatus::Conflict,
"cabin workshop change bypassed payload conflict detection");
auto colony = make_first_colony(2);
CommandDispatcher active(session_identity());
require_completed(active.dispatch(*colony, host, cabin), CommandStatus::Unavailable, 0, 0);
}
Test SessionTests::test_ledger_can_be_staged_with_an_unpublished_world() {
auto world = make_first_colony(2);
CommandDispatcher committed(session_identity());
require_completed(committed.dispatch(*world, host,
envelope(1, CommandPayload{CommandKind::SetPaused, {}, 1})), CommandStatus::Accepted, 0, 1);
const auto before = saved_state(*world);
auto candidate = load_state(before);
auto staged = committed;
const auto building = envelope(2, CommandPayload{CommandKind::PlaceBed, {16, 18}});
const auto prepared = staged.dispatch(*candidate, host, building);
require_completed(prepared, CommandStatus::Accepted, 0, 2);
require(!committed.lookup(host, building) && committed.next_request(host) == 2 &&
saved_state(*world) == before && saved_state(*candidate) != before,
"an unpublished candidate leaked its result or world state");
committed = std::move(staged);
world = std::move(candidate);
const auto published = saved_state(*world);
require(committed.dispatch(*world, host, building) == prepared && saved_state(*world) == published,
"a committed candidate lost its retained receipt");
}
Test SessionTests::test_exception_fences_uncommitted_receipts_and_preserves_old_results() {
for (const auto phase : {CommandMutationPhase::BeforeMutation, CommandMutationPhase::AfterMutation}) {
auto committed_world = make_first_colony(2);
CommandDispatcher committed(session_identity(), {8, observe_mutation});
const auto pause = envelope(1, CommandPayload{CommandKind::SetPaused, {}, 1});
const auto previous = committed.dispatch(*committed_world, host, pause);
require_completed(previous, CommandStatus::Accepted, 0, 1);
const auto committed_bytes = saved_state(*committed_world);
auto candidate = load_state(committed_bytes);
auto staged = committed;
const auto building = envelope(2, CommandPayload{CommandKind::PlaceBed, {16, 18}});
injected_failure = phase;
bool observed_failure = false;
try {
static_cast<void>(staged.dispatch(*candidate, host, building));
} catch (const std::runtime_error& error) {
observed_failure = std::string_view(error.what()) == "injected command mutation failure";
}
injected_failure.reset();
require(observed_failure && staged.faulted(), "an exceptional command did not fence the candidate");
require((saved_state(*candidate) != committed_bytes) == (phase == CommandMutationPhase::AfterMutation),
"the mutation observer did not bracket the actual game effect");
require(staged.lookup(host, pause) == previous && staged.dispatch(*candidate, host, pause) == previous,
"faulted state hid or reexecuted an earlier completed result");
require(staged.lookup(host, building)->status == DispatchStatus::Faulted &&
staged.dispatch(*candidate, host, building).status == DispatchStatus::Faulted,
"an uncommitted command became a replayable success");
const auto faulted_bytes = saved_state(*candidate);
require(staged.dispatch(*candidate, host,
envelope(3, CommandPayload{CommandKind::PlaceBed, {17, 18}})).status == DispatchStatus::Faulted &&
saved_state(*candidate) == faulted_bytes && staged.revision() == previous.revision,
"the faulted owner admitted another effect or committed a result revision");
require(saved_state(*committed_world) == committed_bytes && !committed.lookup(host, building) &&
committed.lookup(host, pause) == previous,
"a failed candidate leaked state or receipts into the publication");
candidate.reset();
auto restored = load_state(committed_bytes);
CommandDispatcher recovered(session_identity(2));
require(recovered.dispatch(*restored, host, building).status == DispatchStatus::StaleSession,
"recovery admitted an envelope from the retired candidate");
const auto fresh = envelope(1, building.payload, session_identity(2));
require_completed(recovered.dispatch(*restored, host, fresh), CommandStatus::Accepted, 0, 1);
}
}
} // namespace