985 lines
54 KiB
C++
985 lines
54 KiB
C++
#define NOMINMAX
|
|
#include <winsock2.h>
|
|
#include <ws2tcpip.h>
|
|
|
|
#include "lan_session.hpp"
|
|
#include "lan_wire.hpp"
|
|
#include "settlement/core/simulation_runtime.hpp"
|
|
|
|
#include <Void/Core/Scope.hpp>
|
|
#include <Void/Testing/Assert.hpp>
|
|
#include <Void/Testing/Suite.hpp>
|
|
|
|
#include <chrono>
|
|
#include <condition_variable>
|
|
#include <future>
|
|
#include <mutex>
|
|
#include <spanstream>
|
|
#include <sstream>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <thread>
|
|
#include <vector>
|
|
|
|
namespace {
|
|
|
|
using namespace std::chrono_literals;
|
|
using namespace std::string_view_literals;
|
|
using namespace settlement;
|
|
using namespace settlement::viewer;
|
|
|
|
using Void::Testing::expect_throw;
|
|
using Void::Testing::require;
|
|
using Void::Testing::Test;
|
|
|
|
constexpr auto hello_bytes = "\x0d\x00\x00\x00\x01\x0b\x00\x00\x00\x10\x32\x54\x76\x98\xba\xdc\xfe"sv;
|
|
constexpr auto command_bytes = "\x23\x00\x00\x00\x03"
|
|
"\x11\x22\x33\x44\x55\x66\x77\x88\x07"
|
|
"\xfe\xff\xff\xff\x78\x56\x34\x12\xa5"
|
|
"\x04\x03\x02\x01\xfc\xfc\xfd\xfe\x87\x96\xa5\xb4\xc3\xd2\xe1\xf0"sv;
|
|
constexpr auto receipt_bytes = "\x0a\x00\x00\x00\x04\x04\x10\x32\x54\x76\x98\xba\xdc\xfe"sv;
|
|
constexpr auto ping_bytes = "\x01\x00\x00\x00\x06"sv;
|
|
|
|
WorldCheckpoint colony_checkpoint() {
|
|
auto identity = Void::Uuid::try_v4();
|
|
auto rules = default_rules_manifest();
|
|
require(identity.has_value() && rules.has_value());
|
|
return {make_first_colony(2), *identity, 1, std::move(*rules)};
|
|
}
|
|
|
|
std::unique_ptr<World> mixed_delivery() {
|
|
auto world = std::make_unique<World>(43, 32, 32, 2);
|
|
const auto store = world->add_storage({3, 3}, 5);
|
|
world->stock_storage(store, ItemType::Plank, 3);
|
|
world->stock_storage(store, ItemType::StoneBlock, 2);
|
|
static_cast<void>(world->spawn_agent({1, 3}));
|
|
world->start_scenario({6, 6});
|
|
world->queue_production({14, 3}, RecipeId::BuildCabin);
|
|
for (int tick = 0; tick < 100 && world->agents().front().inventory.empty(); ++tick) world->step();
|
|
const auto& cargo = world->agents().front().inventory;
|
|
require(cargo.item_count(ItemType::Plank) == 3 && cargo.item_count(ItemType::StoneBlock) == 2);
|
|
// Keep canceled cargo blocked at its real owner through later steps.
|
|
world->stock_storage(store, ItemType::Wood, 5);
|
|
require(world->legacy_representable());
|
|
return world;
|
|
}
|
|
|
|
void cancel_mixed_delivery(World& world) {
|
|
require(world.cancel_production(world.production_orders().front().id) == CommandStatus::Accepted);
|
|
require(!world.legacy_representable());
|
|
world.validate_custody();
|
|
}
|
|
|
|
template<class Pump, class Condition>
|
|
void pump_until(Pump pump, Condition condition, const char* message) {
|
|
const auto deadline = std::chrono::steady_clock::now() + 3s;
|
|
do {
|
|
pump();
|
|
if (condition()) return;
|
|
std::this_thread::sleep_for(1ms);
|
|
} while (std::chrono::steady_clock::now() < deadline);
|
|
throw std::runtime_error(message);
|
|
}
|
|
|
|
struct CaptureGate {
|
|
std::mutex mutex;
|
|
std::condition_variable changed;
|
|
bool armed = false;
|
|
bool entered = false;
|
|
bool released = false;
|
|
|
|
void block() {
|
|
std::unique_lock lock(mutex);
|
|
if (!armed) return;
|
|
entered = true;
|
|
changed.notify_all();
|
|
if (!changed.wait_for(lock, 5s, [&] { return released; })) {
|
|
throw std::runtime_error("LAN test capture gate timed out.");
|
|
}
|
|
}
|
|
|
|
void capture(RuntimePhase phase) {
|
|
if (phase == RuntimePhase::BeforeCapture) block();
|
|
}
|
|
|
|
void arm() { std::lock_guard lock(mutex); armed = true; }
|
|
bool waiting() { std::lock_guard lock(mutex); return entered; }
|
|
void release() {
|
|
std::lock_guard lock(mutex);
|
|
released = true;
|
|
changed.notify_all();
|
|
}
|
|
};
|
|
|
|
struct RawGuest {
|
|
SOCKET socket = INVALID_SOCKET;
|
|
std::string input;
|
|
std::string output;
|
|
bool closed = false;
|
|
std::vector<lan_wire::Receipt> receipts;
|
|
std::unique_ptr<World> snapshot;
|
|
|
|
RawGuest(std::uint16_t port, std::uint64_t key) {
|
|
socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
|
if (socket == INVALID_SOCKET) throw std::runtime_error("Raw guest socket failed.");
|
|
auto close_on_error = Void::Scope::on_exit([&] { closesocket(socket); });
|
|
sockaddr_in remote{};
|
|
remote.sin_family = AF_INET;
|
|
remote.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
|
remote.sin_port = htons(port);
|
|
if (connect(socket, reinterpret_cast<const sockaddr*>(&remote), sizeof(remote)) != 0) {
|
|
throw std::runtime_error("Raw guest connect failed.");
|
|
}
|
|
u_long enabled = 1;
|
|
require(ioctlsocket(socket, static_cast<long>(FIONBIO), &enabled) == 0);
|
|
const auto hello = lan_wire::encode_hello({lan_wire::protocol_version, key});
|
|
lan_wire::append_frame(output, lan_wire::Message::Hello, std::string_view(hello));
|
|
close_on_error.release();
|
|
}
|
|
~RawGuest() { closesocket(socket); }
|
|
RawGuest(const RawGuest&) = delete;
|
|
RawGuest& operator=(const RawGuest&) = delete;
|
|
|
|
void command(std::uint64_t sequence, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0,
|
|
AgentId resident = 0) {
|
|
const auto bytes = lan_wire::encode_command({2, sequence, kind, cell, value, {}, resident});
|
|
lan_wire::append_frame(output, lan_wire::Message::Command, std::string_view(bytes));
|
|
}
|
|
|
|
void poll() {
|
|
if (closed) return;
|
|
if (!output.empty()) {
|
|
const auto sent = send(socket, output.data(), static_cast<int>(output.size()), 0);
|
|
if (sent > 0) output.erase(0, static_cast<std::size_t>(sent));
|
|
else if (sent == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) closed = true;
|
|
}
|
|
std::array<char, 8192> bytes{};
|
|
for (int attempt = 0; attempt < 16 && !closed; ++attempt) {
|
|
const auto count = recv(socket, bytes.data(), static_cast<int>(bytes.size()), 0);
|
|
if (count == SOCKET_ERROR) {
|
|
if (WSAGetLastError() != WSAEWOULDBLOCK) closed = true;
|
|
break;
|
|
}
|
|
if (count == 0) { closed = true; break; }
|
|
input.append(bytes.data(), static_cast<std::size_t>(count));
|
|
std::size_t consumed = 0;
|
|
while (const auto frame = lan_wire::next_frame(std::string_view(input).substr(consumed))) {
|
|
if (frame->message == lan_wire::Message::Receipt) {
|
|
auto receipt = lan_wire::decode_receipt(frame->payload);
|
|
require(receipt.has_value());
|
|
receipts.push_back(*receipt);
|
|
} else if (frame->message == lan_wire::Message::Snapshot) {
|
|
std::ispanstream stream(frame->payload);
|
|
snapshot = World::read_save(stream);
|
|
}
|
|
consumed += frame->size;
|
|
}
|
|
input.erase(0, consumed);
|
|
}
|
|
}
|
|
};
|
|
|
|
struct LanTests : Void::Testing::Suite<LanTests> {
|
|
[[= Void::Testing::tag("wire")]] Test test_protocol_11_fixed_messages();
|
|
[[= Void::Testing::tag("wire")]] Test test_fragmented_and_coalesced_frames();
|
|
[[= Void::Testing::tag("wire")]] Test test_frame_size_limits();
|
|
[[= Void::Testing::tag("lan")]] Test test_shared_colony_over_loopback();
|
|
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_receipts_and_corrected_legacy_sequence();
|
|
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_wrong_sequence_busy_and_pipelining();
|
|
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_retains_slot_work_across_reconnect();
|
|
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_reauthenticates_after_pending_rollback();
|
|
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_rejects_nondefault_rules_and_faults();
|
|
[[= Void::Testing::tag("lan-owner")]] Test test_legacy_custody_refuses_handshake_and_preserves_modern_owner();
|
|
[[= Void::Testing::tag("lan-owner")]] Test test_standalone_custody_discards_queued_snapshot_and_command();
|
|
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_custody_cuts_off_queued_guest_but_settles_admitted_work();
|
|
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_custody_discards_queued_snapshot_before_admission();
|
|
[[= Void::Testing::tag("lan-admission")]] Test test_guest_admission_cannot_cross_incompatible_publication();
|
|
[[= Void::Testing::tag("lan-admission")]] Test test_guest_retries_same_sequence_after_compatible_publication();
|
|
[[= Void::Testing::tag("lan-admission")]] Test test_conditional_admission_preserves_accepted_work_and_reports_refusals();
|
|
[[= Void::Testing::tag("lan-admission")]] Test test_conditional_admission_rejects_faulted_owner_with_retained_publication();
|
|
};
|
|
|
|
Test LanTests::test_protocol_11_fixed_messages() {
|
|
using namespace lan_wire;
|
|
constexpr Hello hello{protocol_version, 0xfedcba9876543210ULL};
|
|
constexpr PlayerCommand command{
|
|
1, 0x8877665544332211ULL, CommandKind::MoveObject, {-2, 0x12345678}, 0xa5,
|
|
{0x01020304, -0x01020304}, 0xf0e1d2c3b4a59687ULL
|
|
};
|
|
constexpr Receipt receipt{CommandStatus::InvalidTarget, 0xfedcba9876543210ULL};
|
|
|
|
std::string encoded;
|
|
const auto hello_payload = encode_hello(hello);
|
|
append_frame(encoded, Message::Hello, std::string_view(hello_payload));
|
|
require(encoded == hello_bytes);
|
|
encoded.clear();
|
|
const auto command_payload = encode_command(command);
|
|
append_frame(encoded, Message::Command, std::string_view(command_payload));
|
|
require(encoded == command_bytes);
|
|
encoded.clear();
|
|
const auto receipt_payload = encode_receipt(receipt);
|
|
append_frame(encoded, Message::Receipt, std::string_view(receipt_payload));
|
|
require(encoded == receipt_bytes);
|
|
|
|
const auto hello_frame = next_frame(hello_bytes);
|
|
require(hello_frame && hello_frame->message == Message::Hello && hello_frame->size == hello_bytes.size());
|
|
const auto decoded_hello = decode_hello(hello_frame->payload);
|
|
require(decoded_hello && decoded_hello->version == 11 && decoded_hello->key == hello.key);
|
|
require(!decode_hello(hello_frame->payload.substr(1)));
|
|
require(!decode_hello(std::string(hello_frame->payload) + '\0'));
|
|
|
|
const auto command_frame = next_frame(command_bytes);
|
|
require(command_frame && command_frame->message == Message::Command && command_frame->size == command_bytes.size());
|
|
const auto decoded_command = decode_command(command_frame->payload);
|
|
require(decoded_command.has_value());
|
|
require(decoded_command->player == 2);
|
|
require(decoded_command->sequence == command.sequence);
|
|
require(decoded_command->kind == command.kind);
|
|
require(decoded_command->cell == command.cell);
|
|
require(decoded_command->value == command.value);
|
|
require(decoded_command->destination == command.destination);
|
|
require(decoded_command->resident == command.resident);
|
|
require(!decode_command(command_frame->payload.substr(1)));
|
|
require(!decode_command(std::string(command_frame->payload) + '\0'));
|
|
|
|
const auto receipt_frame = next_frame(receipt_bytes);
|
|
require(receipt_frame && receipt_frame->message == Message::Receipt && receipt_frame->size == receipt_bytes.size());
|
|
const auto decoded_receipt = decode_receipt(receipt_frame->payload);
|
|
require(decoded_receipt && decoded_receipt->status == receipt.status &&
|
|
decoded_receipt->next_sequence == receipt.next_sequence);
|
|
require(!decode_receipt(receipt_frame->payload.substr(1)));
|
|
require(!decode_receipt(std::string(receipt_frame->payload) + '\0'));
|
|
}
|
|
|
|
Test LanTests::test_fragmented_and_coalesced_frames() {
|
|
using namespace lan_wire;
|
|
std::string received(command_bytes.substr(0, 3));
|
|
require(!next_frame(received));
|
|
received.append(command_bytes.substr(3, 8));
|
|
require(!next_frame(received));
|
|
received.append(command_bytes.substr(11));
|
|
received.append(ping_bytes);
|
|
received.append(hello_bytes.substr(0, 5));
|
|
|
|
std::size_t consumed = 0;
|
|
{
|
|
const auto command = next_frame(received);
|
|
require(command && command->message == Message::Command && command->size == command_bytes.size());
|
|
require(command->payload.data() == received.data() + 5);
|
|
require(command->payload == command_bytes.substr(5));
|
|
|
|
const auto ping = next_frame(std::string_view(received).substr(command->size));
|
|
require(ping && ping->message == Message::Ping && ping->payload.empty() && ping->size == ping_bytes.size());
|
|
consumed = command->size + ping->size;
|
|
require(!next_frame(std::string_view(received).substr(consumed)));
|
|
}
|
|
|
|
received.erase(0, consumed);
|
|
received.append(hello_bytes.substr(5));
|
|
const auto hello = next_frame(received);
|
|
require(hello && hello->message == Message::Hello && hello->size == received.size());
|
|
require(hello->payload == hello_bytes.substr(5));
|
|
}
|
|
|
|
Test LanTests::test_frame_size_limits() {
|
|
using namespace lan_wire;
|
|
constexpr auto empty_prefix = "\x00\x00\x00\x00"sv;
|
|
constexpr auto max_prefix = "\x00\x00\x40\x00"sv;
|
|
constexpr auto oversized_prefix = "\x01\x00\x40\x00"sv;
|
|
|
|
require(!next_frame(empty_prefix.substr(0, 3)));
|
|
require(!next_frame(oversized_prefix.substr(0, 3)));
|
|
expect_throw<std::runtime_error>([] { static_cast<void>(next_frame(empty_prefix)); });
|
|
expect_throw<std::runtime_error>([] { static_cast<void>(next_frame(oversized_prefix)); });
|
|
require(!next_frame(max_prefix));
|
|
|
|
std::string output;
|
|
append_frame(output, Message::Ping);
|
|
require(output == ping_bytes);
|
|
|
|
std::string payload(4 * 1024 * 1024 - 1, '\xa5');
|
|
output.clear();
|
|
append_frame(output, Message::Snapshot, payload);
|
|
require(output.starts_with(max_prefix));
|
|
{
|
|
const auto snapshot = next_frame(output);
|
|
require(snapshot && snapshot->message == Message::Snapshot && snapshot->size == output.size());
|
|
require(snapshot->payload == payload);
|
|
payload.front() = '\0';
|
|
require(snapshot->payload.front() == '\xa5');
|
|
}
|
|
|
|
payload.push_back('\0');
|
|
expect_throw<std::runtime_error>([&] { append_frame(output, Message::Snapshot, payload); });
|
|
require(output.size() == ping_bytes.size() + payload.size() - 1);
|
|
}
|
|
|
|
Test LanTests::test_shared_colony_over_loopback() {
|
|
auto authoritative = make_first_colony(4);
|
|
auto client_view = make_first_colony(4);
|
|
for (int i = 0; i < 25; ++i) authoritative->step();
|
|
LanSession host;
|
|
LanSession guest;
|
|
host.host(0, true);
|
|
const auto port = host.port();
|
|
const auto code = host.join_code();
|
|
auto wrong_code = code;
|
|
wrong_code.front() = wrong_code.front() == 'f' ? 'e' : 'f';
|
|
const auto pump_until = [&](auto success, const char* message) {
|
|
const auto deadline = std::chrono::steady_clock::now() + 3s;
|
|
while (std::chrono::steady_clock::now() < deadline) {
|
|
static_cast<void>(host.poll(*authoritative));
|
|
if (auto snapshot = guest.poll(*client_view)) client_view = std::move(snapshot);
|
|
if (success()) return;
|
|
std::this_thread::sleep_for(1ms);
|
|
}
|
|
throw std::runtime_error(message);
|
|
};
|
|
guest.join("127.0.0.1", wrong_code, port);
|
|
pump_until([&] { return guest.state() == LanState::GuestDisconnected; },
|
|
"a guest with the wrong code was not disconnected");
|
|
require(host.state() == LanState::Hosting);
|
|
|
|
guest.join("127.0.0.1", code, port);
|
|
pump_until([&] { return guest.state() == LanState::GuestConnected; }, "the guest could not join");
|
|
require(client_view->tick() == 25 && client_view->agents().size() == authoritative->agents().size());
|
|
require(!guest.submit(CommandKind::SetPaused, {}, 1));
|
|
require(guest.submit(CommandKind::PlaceBed, {16, 18}, static_cast<std::uint8_t>(BedBase::Stone)));
|
|
pump_until([&] {
|
|
return client_view->production_orders().size() == 1 &&
|
|
client_view->production_orders().front().position == GridPosition{16, 18} &&
|
|
client_view->production_orders().front().bed_base == BedBase::Stone;
|
|
}, "the guest's bed was not applied and synchronized");
|
|
require(authoritative->production_orders().front().bed_base == BedBase::Stone);
|
|
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 0));
|
|
pump_until([&] {
|
|
const auto rejected = guest.take_rejection();
|
|
return rejected && rejected->status == CommandStatus::InvalidTarget &&
|
|
rejected->kind == CommandKind::PlaceBed && rejected->cell == GridPosition{16, 18} &&
|
|
rejected->value == 0;
|
|
},
|
|
"a conflicting guest command did not return a rejection");
|
|
require(authoritative->production_orders().size() == 1);
|
|
|
|
guest.leave();
|
|
pump_until([&] { return host.state() == LanState::Hosting; }, "the guest slot was not released");
|
|
for (int i = 0; i < 10; ++i) authoritative->step();
|
|
guest.join("127.0.0.1", code, port);
|
|
pump_until([&] { return guest.state() == LanState::GuestConnected; }, "the guest could not rejoin");
|
|
require(client_view->tick() == authoritative->tick() && client_view->next_command_sequence(2) == 2 &&
|
|
client_view->production_orders().size() == 1);
|
|
require(guest.submit(CommandKind::SetForaging, {14, 12}, 1));
|
|
pump_until([&] {
|
|
if (client_view->next_command_sequence(2) != 3) return false;
|
|
for (const auto& node : client_view->resource_nodes()) {
|
|
if (node.position == GridPosition{14, 12}) return node.foraging_enabled;
|
|
}
|
|
return false;
|
|
}, "the reconnected guest's command did not synchronize");
|
|
const auto owner_sleeping = [](const World& simulation) {
|
|
for (const auto& agent : simulation.agents()) {
|
|
if (agent.state == AgentState::Sleeping && simulation.assigned_bed(agent.id) != nullptr) return true;
|
|
}
|
|
return false;
|
|
};
|
|
for (int i = 0; i < 600 && !owner_sleeping(*authoritative); ++i) authoritative->step();
|
|
require(owner_sleeping(*authoritative));
|
|
pump_until([&] {
|
|
return client_view->tick() == authoritative->tick() && owner_sleeping(*client_view);
|
|
}, "the host's sleep state did not reach the guest");
|
|
const GridPosition field{14, 15};
|
|
const GridPosition new_field{14, 17};
|
|
require(guest.submit(CommandKind::PlaceBerryField, field, 0));
|
|
const auto has_field = [&](GridPosition position) {
|
|
for (const auto& node : client_view->resource_nodes()) {
|
|
if (node.site == ResourceSite::BerryField && node.position == position) return true;
|
|
}
|
|
return false;
|
|
};
|
|
pump_until([&] { return has_field(field); }, "the planted field was not synchronized");
|
|
require(guest.submit(CommandKind::MoveObject, field, 0, new_field));
|
|
pump_until([&] { return has_field(new_field) && !has_field(field); }, "the move destination was not synchronized");
|
|
require(guest.submit(CommandKind::DemolishObject, new_field, 0));
|
|
pump_until([&] { return !has_field(new_field); },
|
|
"demolishing a field was not synchronized");
|
|
const auto resident = authoritative->agents().back().id;
|
|
require(guest.submit(CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), {}, resident));
|
|
pump_until([&] {
|
|
return client_view->agents().back().id == resident &&
|
|
client_view->agents().back().profession == Profession::Miner;
|
|
}, "the assigned profession was not synchronized");
|
|
require(guest.submit(CommandKind::PlaceFlaxField, field, 0));
|
|
pump_until([&] {
|
|
return client_view->resource_nodes().back().site == ResourceSite::FlaxField &&
|
|
client_view->resource_nodes().back().position == field;
|
|
}, "the flax field did not arrive in the guest snapshot");
|
|
require(guest.submit(CommandKind::PlaceLoom, new_field, 0));
|
|
pump_until([&] {
|
|
const auto& orders = client_view->production_orders();
|
|
return orders.size() >= 2 && orders.back().recipe == RecipeId::CraftLoom &&
|
|
orders[orders.size() - 2].recipe == RecipeId::InstallLoom &&
|
|
orders[orders.size() - 2].position == new_field;
|
|
}, "the loom installation and workshop order did not arrive in the guest snapshot");
|
|
for (int i = 0; i < 160 && authoritative->resource_nodes().back().reserved_workers == 0; ++i) {
|
|
authoritative->step();
|
|
}
|
|
require(authoritative->resource_nodes().back().needs_tending() &&
|
|
authoritative->resource_nodes().back().reserved_workers == 1);
|
|
pump_until([&] {
|
|
return client_view->tick() == authoritative->tick() &&
|
|
client_view->resource_nodes().back().needs_tending() &&
|
|
client_view->resource_nodes().back().reserved_workers == 1;
|
|
}, "a snapshot lost the resident's sowing assignment");
|
|
RoomPlan room{};
|
|
bool found_room = false;
|
|
for (int y = 2; y < 29 && !found_room; ++y) {
|
|
for (int x = 2; x < 29 && !found_room; ++x) {
|
|
const auto candidate = make_room_plan({x, y}, {x + 2, y + 2});
|
|
if (!authoritative->can_place_room(candidate)) continue;
|
|
room = candidate;
|
|
found_room = true;
|
|
}
|
|
}
|
|
require(found_room);
|
|
const auto entrance = static_cast<std::uint8_t>(room.entrance);
|
|
const auto previous_size = authoritative->production_orders().size();
|
|
require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last));
|
|
pump_until([&] {
|
|
return client_view->production_orders().size() == previous_size + 10 &&
|
|
client_view->production_orders().back().recipe == RecipeId::CraftWoodenDoor;
|
|
}, "snapshot did not carry the room and carpenter's order");
|
|
require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last));
|
|
pump_until([&] {
|
|
const auto rejected = guest.take_rejection();
|
|
return rejected && rejected->kind == CommandKind::PlaceRoom && rejected->cell == room.first &&
|
|
rejected->destination == room.last && rejected->value == entrance &&
|
|
rejected->status == CommandStatus::InvalidTarget;
|
|
}, "room rejection lost the geometry needed to restore the draft");
|
|
require(authoritative->production_orders().size() == previous_size + 10);
|
|
}
|
|
|
|
Test LanTests::test_runtime_host_receipts_and_corrected_legacy_sequence() {
|
|
SimulationRuntime runtime(colony_checkpoint(), {.ticking = false});
|
|
LanSession host, guest;
|
|
host.host(0, true);
|
|
guest.join("127.0.0.1", host.join_code(), host.port());
|
|
std::unique_ptr<World> view;
|
|
const auto pump = [&] {
|
|
host.poll_host(runtime);
|
|
if (auto latest = guest.poll_guest()) view = std::move(latest);
|
|
};
|
|
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Runtime guest did not join.");
|
|
require(view && view->tick() == 0);
|
|
const auto resident = view->agents().back().id;
|
|
require(guest.submit(CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), {}, resident));
|
|
std::optional<LanCommandResult> result;
|
|
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Profession receipt missing.");
|
|
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::AssignProfession &&
|
|
result->resident == resident && result->value == static_cast<std::uint8_t>(Profession::Miner));
|
|
require(runtime.latest()->world->agents().back().profession == Profession::Miner);
|
|
|
|
require(guest.submit(CommandKind::PlaceBed, {16, 18}, static_cast<std::uint8_t>(BedBase::Stone)));
|
|
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Bed receipt missing.");
|
|
require(result->status == CommandStatus::Accepted && result->cell == GridPosition{16, 18});
|
|
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 0));
|
|
require(guest.submit(CommandKind::SetForaging, {14, 12}, 1));
|
|
pump_until(pump, [&] { return guest.take_rejection().has_value(); }, "Bed rejection missing.");
|
|
// The failed result remains undrained. The queued correction cannot execute.
|
|
for (int attempt = 0; attempt < 20; ++attempt) pump();
|
|
require(runtime.latest()->next_requests[1] == 4);
|
|
result = guest.take_result();
|
|
require(result && result->status == CommandStatus::InvalidTarget && result->kind == CommandKind::PlaceBed &&
|
|
result->cell == GridPosition{16, 18} && result->destination == GridPosition{} && result->value == 0);
|
|
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Corrected command receipt missing.");
|
|
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::SetForaging);
|
|
require(runtime.latest()->next_requests[1] == 5 && runtime.latest()->world->next_command_sequence(2) == 4);
|
|
require(runtime.latest()->world->production_orders().size() == 1);
|
|
pump_until(pump, [&] { return view->next_command_sequence(2) == 4; }, "Same-tick snapshot missing.");
|
|
require(view->tick() == 0);
|
|
guest.leave();
|
|
require(!guest.take_result());
|
|
}
|
|
|
|
Test LanTests::test_runtime_host_wrong_sequence_busy_and_pipelining() {
|
|
CaptureGate gate;
|
|
RuntimeOptions options{.capacity = 1, .ticking = false};
|
|
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
|
|
SimulationRuntime runtime(colony_checkpoint(), options);
|
|
auto release = Void::Scope::on_exit([&] { gate.release(); });
|
|
LanSession host;
|
|
host.host(0, true);
|
|
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
|
|
const auto pump = [&] { host.poll_host(runtime); guest.poll(); };
|
|
pump_until(pump, [&] { return guest.snapshot != nullptr; }, "Raw runtime guest did not join.");
|
|
guest.command(99, CommandKind::SetForaging, {14, 12}, 1);
|
|
pump_until(pump, [&] { return guest.receipts.size() == 1; }, "Wrong-sequence receipt missing.");
|
|
require(guest.receipts[0].status == CommandStatus::WrongSequence && guest.receipts[0].next_sequence == 1);
|
|
const auto snapshot = runtime.latest();
|
|
gate.arm();
|
|
const auto& id = snapshot->identity;
|
|
auto local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city, 1,
|
|
CommandPayload{CommandKind::SetForaging, {13, 14}, 1}});
|
|
require(local.admission == RuntimeAdmission::Accepted);
|
|
pump_until(pump, [&] { return gate.waiting(); }, "Owner did not reach blocked capture.");
|
|
guest.command(1, CommandKind::SetForaging, {14, 12}, 1);
|
|
pump_until(pump, [&] { return guest.receipts.size() == 2; }, "Busy receipt missing.");
|
|
require(guest.receipts[1].status == CommandStatus::Busy && guest.receipts[1].next_sequence == 1);
|
|
require(runtime.latest()->next_requests[1] == 1);
|
|
gate.release();
|
|
require(local.completion.wait_for(3s) == std::future_status::ready);
|
|
require(local.completion.get().receipt->command_status == CommandStatus::Accepted);
|
|
|
|
// Two coalesced commands cannot turn one guest slot into multiple in-flight operations.
|
|
guest.command(1, CommandKind::SetForaging, {14, 12}, 1);
|
|
guest.command(2, CommandKind::SetForaging, {18, 12}, 1);
|
|
pump_until(pump, [&] { return guest.closed; }, "Pipelined guest was not bounded.");
|
|
RuntimeSubmission fence{RuntimeAdmission::Busy, {}};
|
|
pump_until(pump, [&] {
|
|
fence = runtime.synchronize();
|
|
return fence.admission == RuntimeAdmission::Accepted;
|
|
}, "Owner did not release its admission slot.");
|
|
require(fence.completion.wait_for(3s) == std::future_status::ready);
|
|
require(fence.completion.get().outcome == RuntimeOutcome::Completed);
|
|
require(runtime.latest()->next_requests[1] == 2 && runtime.latest()->world->next_command_sequence(2) == 2);
|
|
}
|
|
|
|
Test LanTests::test_runtime_host_retains_slot_work_across_reconnect() {
|
|
CaptureGate gate;
|
|
RuntimeOptions options{.ticking = false};
|
|
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
|
|
SimulationRuntime runtime(colony_checkpoint(), options);
|
|
auto release = Void::Scope::on_exit([&] { gate.release(); });
|
|
LanSession host, first, next;
|
|
host.host(0, true);
|
|
const auto code = host.join_code();
|
|
const auto pump = [&] {
|
|
host.poll_host(runtime);
|
|
static_cast<void>(first.poll_guest());
|
|
static_cast<void>(next.poll_guest());
|
|
};
|
|
first.join("127.0.0.1", code, host.port());
|
|
pump_until(pump, [&] { return first.state() == LanState::GuestConnected; }, "First guest did not join.");
|
|
gate.arm();
|
|
require(first.submit(CommandKind::PlaceBed, {16, 18}, 1));
|
|
pump_until(pump, [&] { return gate.waiting(); }, "Guest command did not reach blocked owner.");
|
|
require(runtime.latest()->world->production_orders().empty());
|
|
first.leave();
|
|
pump_until(pump, [&] { return host.state() == LanState::Hosting; }, "Old socket did not close.");
|
|
next.join("127.0.0.1", code, host.port());
|
|
for (int attempt = 0; attempt < 20; ++attempt) pump();
|
|
require(next.state() == LanState::Connecting && !next.take_result());
|
|
gate.release();
|
|
pump_until(pump, [&] { return next.state() == LanState::GuestConnected; }, "Reconnected guest did not join.");
|
|
require(!next.take_result());
|
|
require(runtime.latest()->world->production_orders().size() == 1);
|
|
require(runtime.latest()->next_requests[1] == 2);
|
|
require(next.submit(CommandKind::SetForaging, {14, 12}, 1));
|
|
std::optional<LanCommandResult> result;
|
|
pump_until(pump, [&] { result = next.take_result(); return result.has_value(); }, "New guest receipt missing.");
|
|
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::SetForaging);
|
|
require(runtime.latest()->next_requests[1] == 3 && runtime.latest()->world->next_command_sequence(2) == 3);
|
|
}
|
|
|
|
Test LanTests::test_runtime_host_reauthenticates_after_pending_rollback() {
|
|
CaptureGate gate;
|
|
RuntimeOptions options{.ticking = false};
|
|
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
|
|
auto initial = colony_checkpoint();
|
|
const auto world_id = initial.world_id;
|
|
SimulationRuntime runtime(std::move(initial), options);
|
|
auto release = Void::Scope::on_exit([&] { gate.release(); });
|
|
LanSession host, guest;
|
|
host.host(0, true);
|
|
guest.join("127.0.0.1", host.join_code(), host.port());
|
|
const auto pump = [&] { host.poll_host(runtime); static_cast<void>(guest.poll_guest()); };
|
|
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Rollback guest did not join.");
|
|
const auto old_session = runtime.latest()->identity.session;
|
|
gate.arm();
|
|
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
|
|
pump_until(pump, [&] { return gate.waiting(); }, "Rollback guest command did not block.");
|
|
auto ticket = runtime.begin_load();
|
|
require(ticket.has_value());
|
|
auto rollback = colony_checkpoint();
|
|
rollback.world_id = world_id;
|
|
auto installed = runtime.try_install(*ticket, rollback);
|
|
require(installed.admission == RuntimeAdmission::Accepted);
|
|
gate.release();
|
|
require(installed.completion.wait_for(3s) == std::future_status::ready);
|
|
require(installed.completion.get().outcome == RuntimeOutcome::Completed);
|
|
pump_until(pump, [&] { return guest.state() == LanState::GuestDisconnected; }, "Old epoch peer stayed connected.");
|
|
require(runtime.latest()->identity.session != old_session && runtime.latest()->identity.world == world_id);
|
|
require(runtime.latest()->world->production_orders().empty() && !guest.take_result());
|
|
guest.reconnect();
|
|
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Guest could not reauthenticate.");
|
|
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
|
|
std::optional<LanCommandResult> result;
|
|
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "New epoch receipt missing.");
|
|
require(result->status == CommandStatus::Accepted && runtime.latest()->next_requests[1] == 2);
|
|
}
|
|
|
|
Test LanTests::test_runtime_host_rejects_nondefault_rules_and_faults() {
|
|
auto initial = colony_checkpoint();
|
|
auto packages = builtin_rule_packages();
|
|
require(packages.has_value());
|
|
const std::array selected{std::string{"settlement.core"}};
|
|
auto rules = resolve_rules(*packages, selected);
|
|
require(rules.has_value());
|
|
initial.rules = std::move(*rules);
|
|
SimulationRuntime incompatible(std::move(initial), {.ticking = false});
|
|
LanSession host, guest;
|
|
host.host(0, true);
|
|
guest.join("127.0.0.1", host.join_code(), host.port());
|
|
host.poll_host(incompatible);
|
|
require(host.state() == LanState::Hosting && host.detail().find("default rules") != std::string::npos);
|
|
for (int attempt = 0; attempt < 20; ++attempt) {
|
|
host.poll_host(incompatible);
|
|
require(!guest.poll_guest());
|
|
}
|
|
require(guest.state() != LanState::GuestConnected);
|
|
guest.leave();
|
|
RuntimeOptions options{.ticking = false};
|
|
options.observer = [](RuntimePhase phase) {
|
|
if (phase == RuntimePhase::BeforeCapture) throw std::runtime_error("Injected capture failure.");
|
|
};
|
|
SimulationRuntime faulting(colony_checkpoint(), options);
|
|
guest.join("127.0.0.1", host.join_code(), host.port());
|
|
const auto pump = [&] { host.poll_host(faulting); static_cast<void>(guest.poll_guest()); };
|
|
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Fault guest did not join.");
|
|
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
|
|
pump_until(pump, [&] { return guest.state() == LanState::GuestDisconnected; }, "Faulted peer stayed connected.");
|
|
require(faulting.view().state == RuntimeState::Faulted && faulting.latest()->world->production_orders().empty());
|
|
require(!guest.take_result());
|
|
}
|
|
|
|
Test LanTests::test_legacy_custody_refuses_handshake_and_preserves_modern_owner() {
|
|
auto initial = colony_checkpoint();
|
|
initial.world = mixed_delivery();
|
|
cancel_mixed_delivery(*initial.world);
|
|
const auto encoded = encode_checkpoint(*initial.world, initial.world_id, initial.city, initial.rules);
|
|
require(encoded.has_value());
|
|
auto packages = builtin_rule_packages();
|
|
require(packages.has_value());
|
|
auto restored = decode_checkpoint(*encoded, *packages, 2);
|
|
require(restored.has_value() && !restored->world->legacy_representable());
|
|
SimulationRuntime runtime(std::move(*restored), {.ticking = false});
|
|
LanSession host, guest;
|
|
host.host(0, true);
|
|
const auto port = host.port();
|
|
guest.join("127.0.0.1", host.join_code(), port);
|
|
for (int attempt = 0; attempt < 20; ++attempt) {
|
|
host.poll_host(runtime);
|
|
require(!guest.poll_guest());
|
|
}
|
|
require(host.state() == LanState::Hosting && host.port() == port && !host.detail().empty());
|
|
require(guest.state() != LanState::GuestConnected && !guest.take_result());
|
|
const auto before = runtime.latest();
|
|
const auto& id = before->identity;
|
|
auto local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
|
|
before->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}});
|
|
require(local.admission == RuntimeAdmission::Accepted && local.completion.wait_for(3s) == std::future_status::ready);
|
|
require(local.completion.get().receipt->command_status == CommandStatus::Accepted);
|
|
require(runtime.view().state == RuntimeState::Running && runtime.latest()->world->paused());
|
|
const auto current = runtime.latest();
|
|
auto saved = encode_checkpoint(*current->world, id.world, id.city, *current->rules);
|
|
require(saved.has_value() && decode_checkpoint(*saved, *packages, 2).has_value());
|
|
require(current->next_requests[1] == before->next_requests[1]);
|
|
}
|
|
|
|
Test LanTests::test_standalone_custody_discards_queued_snapshot_and_command() {
|
|
auto world = mixed_delivery();
|
|
// A real historical snapshot larger than one 64 KiB flush leaves output
|
|
// queued; gating only a subsequent send_snapshot call misses this case.
|
|
for (int job = 0; job < 4096; ++job) static_cast<void>(world->add_job({20, 20}, 1));
|
|
std::ostringstream bytes(std::ios::binary);
|
|
world->write_save(bytes);
|
|
require(bytes.view().size() > 64 * 1024);
|
|
LanSession host;
|
|
host.host(0, true);
|
|
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
|
|
guest.poll();
|
|
pump_until([&] { static_cast<void>(host.poll(*world)); },
|
|
[&] { return host.state() == LanState::HostConnected; }, "Standalone guest did not authenticate.");
|
|
guest.poll();
|
|
require(!guest.input.empty() && !guest.snapshot);
|
|
const auto partial = guest.input.size();
|
|
const auto profession = world->agents().front().profession;
|
|
cancel_mixed_delivery(*world);
|
|
guest.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner),
|
|
world->agents().front().id);
|
|
guest.poll();
|
|
pump_until([&] { static_cast<void>(host.poll(*world)); guest.poll(); },
|
|
[&] { return guest.closed; }, "Unsupported standalone peer stayed connected.");
|
|
require(host.state() == LanState::Hosting && !host.detail().empty());
|
|
require(guest.input.size() == partial && !guest.snapshot && guest.receipts.empty());
|
|
require(world->next_command_sequence(2) == 1 && world->agents().front().profession == profession);
|
|
const auto tick = world->tick();
|
|
world->step();
|
|
require(world->tick() == tick + 1);
|
|
world->validate_custody();
|
|
|
|
auto compatible = mixed_delivery();
|
|
RawGuest next(host.port(), std::stoull(host.join_code(), nullptr, 16));
|
|
const auto pump = [&] { static_cast<void>(host.poll(*compatible)); next.poll(); };
|
|
pump_until(pump, [&] { return next.snapshot != nullptr; }, "Representable counterpart could not join.");
|
|
next.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner),
|
|
compatible->agents().front().id);
|
|
pump_until(pump, [&] { return !next.receipts.empty(); }, "Representable counterpart command did not settle.");
|
|
require(next.receipts.front().status == CommandStatus::Accepted);
|
|
}
|
|
|
|
Test LanTests::test_runtime_custody_cuts_off_queued_guest_but_settles_admitted_work() {
|
|
CaptureGate gate;
|
|
RuntimeOptions options{.ticking = false};
|
|
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
|
|
auto initial = colony_checkpoint();
|
|
initial.world = mixed_delivery();
|
|
const auto production = initial.world->production_orders().front().id;
|
|
const auto resident = initial.world->agents().front().id;
|
|
SimulationRuntime runtime(std::move(initial), options);
|
|
auto release = Void::Scope::on_exit([&] { gate.release(); });
|
|
LanSession host;
|
|
host.host(0, true);
|
|
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
|
|
const auto pump = [&] { host.poll_host(runtime); guest.poll(); };
|
|
pump_until(pump, [&] { return guest.snapshot != nullptr; }, "Custody guest did not join.");
|
|
const auto before = runtime.latest();
|
|
const auto id = before->identity;
|
|
const CommandPayload accepted{CommandKind::AssignProfession, {},
|
|
static_cast<std::uint8_t>(Profession::Miner), {}, resident};
|
|
gate.arm();
|
|
guest.command(1, accepted.kind, {}, accepted.value, resident);
|
|
pump_until(pump, [&] { return gate.waiting(); }, "Guest work did not reach blocked capture.");
|
|
auto canceled = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
|
|
before->next_requests[0], CancelProductionPayload{production}});
|
|
require(canceled.admission == RuntimeAdmission::Accepted);
|
|
// This later wire intent is already in TCP when cancellation publishes.
|
|
guest.command(2, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Builder), resident);
|
|
guest.poll();
|
|
gate.release();
|
|
require(canceled.completion.wait_for(3s) == std::future_status::ready);
|
|
require(canceled.completion.get().receipt->command_status == CommandStatus::Accepted);
|
|
require(runtime.latest()->identity.session == id.session && !runtime.latest()->world->legacy_representable());
|
|
pump_until(pump, [&] { return guest.closed; }, "Incompatible runtime guest stayed connected.");
|
|
require(host.state() == LanState::Hosting && runtime.view().state == RuntimeState::Running);
|
|
require(guest.receipts.empty());
|
|
const auto current = runtime.latest();
|
|
require(current->next_requests[1] == 2 && current->world->next_command_sequence(2) == 2);
|
|
require(current->world->agents().front().profession == Profession::Miner);
|
|
const auto retained = runtime.lookup({2}, {command_envelope_version, id.world, id.session, id.city,
|
|
before->next_requests[1], accepted});
|
|
require(retained && retained->status == DispatchStatus::Completed && retained->command_status == CommandStatus::Accepted);
|
|
require(encode_checkpoint(*current->world, id.world, id.city, *current->rules).has_value());
|
|
|
|
// A later compatible incarnation can reconnect; neither the retained work
|
|
// nor its old socket's reply leaks into the new connection.
|
|
auto ticket = runtime.begin_load();
|
|
require(ticket.has_value());
|
|
auto replacement = colony_checkpoint();
|
|
auto installed = runtime.try_install(*ticket, replacement);
|
|
require(installed.admission == RuntimeAdmission::Accepted && installed.completion.wait_for(3s) == std::future_status::ready);
|
|
require(installed.completion.get().outcome == RuntimeOutcome::Completed);
|
|
RawGuest next(host.port(), std::stoull(host.join_code(), nullptr, 16));
|
|
pump_until([&] { host.poll_host(runtime); next.poll(); },
|
|
[&] { return next.snapshot != nullptr; }, "Guest could not reconnect after custody cutoff.");
|
|
require(next.receipts.empty() && next.snapshot->next_command_sequence(2) == 1);
|
|
}
|
|
|
|
Test LanTests::test_runtime_custody_discards_queued_snapshot_before_admission() {
|
|
auto initial = colony_checkpoint();
|
|
initial.world = mixed_delivery();
|
|
const auto production = initial.world->production_orders().front().id;
|
|
const auto resident = initial.world->agents().front().id;
|
|
for (int job = 0; job < 4096; ++job) static_cast<void>(initial.world->add_job({20, 20}, 1));
|
|
SimulationRuntime runtime(std::move(initial), {.ticking = false});
|
|
LanSession host;
|
|
host.host(0, true);
|
|
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
|
|
guest.poll();
|
|
pump_until([&] { host.poll_host(runtime); }, [&] { return host.state() == LanState::HostConnected; },
|
|
"Queued-snapshot guest did not authenticate.");
|
|
guest.poll();
|
|
require(!guest.input.empty() && !guest.snapshot);
|
|
const auto partial = guest.input.size();
|
|
const auto before = runtime.latest();
|
|
const auto id = before->identity;
|
|
auto canceled = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
|
|
before->next_requests[0], CancelProductionPayload{production}});
|
|
require(canceled.admission == RuntimeAdmission::Accepted && canceled.completion.wait_for(3s) == std::future_status::ready);
|
|
require(canceled.completion.get().receipt->command_status == CommandStatus::Accepted);
|
|
guest.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), resident);
|
|
guest.poll();
|
|
pump_until([&] { host.poll_host(runtime); guest.poll(); }, [&] { return guest.closed; },
|
|
"Guest receiving queued snapshot was not dropped.");
|
|
require(runtime.latest()->identity.session == id.session && !runtime.latest()->world->legacy_representable());
|
|
require(runtime.view().state == RuntimeState::Running && host.state() == LanState::Hosting);
|
|
require(guest.input.size() == partial && !guest.snapshot && guest.receipts.empty());
|
|
require(runtime.latest()->next_requests[1] == 1 && runtime.latest()->world->next_command_sequence(2) == 1);
|
|
}
|
|
|
|
Test LanTests::test_guest_admission_cannot_cross_incompatible_publication() {
|
|
CaptureGate admission;
|
|
auto initial = colony_checkpoint();
|
|
initial.world = mixed_delivery();
|
|
const auto production = initial.world->production_orders().front().id;
|
|
const auto resident = initial.world->agents().front().id;
|
|
SimulationRuntime runtime(std::move(initial), {.ticking = false});
|
|
LanSession host({.before_command_admission = [&] { admission.block(); }});
|
|
host.host(0, true);
|
|
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
|
|
pump_until([&] { host.poll_host(runtime); guest.poll(); }, [&] { return guest.snapshot != nullptr; },
|
|
"Admission-race guest did not join.");
|
|
const auto checked = runtime.latest();
|
|
const auto id = checked->identity;
|
|
const auto old_profession = checked->world->agents().front().profession;
|
|
const CommandPayload intent{CommandKind::AssignProfession, {},
|
|
static_cast<std::uint8_t>(Profession::Miner), {}, resident};
|
|
const CommandEnvelope envelope{command_envelope_version, id.world, id.session, id.city,
|
|
checked->next_requests[1], intent};
|
|
admission.arm();
|
|
guest.command(1, intent.kind, {}, intent.value, resident);
|
|
guest.poll();
|
|
auto polling = std::async(std::launch::async, [&] { host.poll_host(runtime); });
|
|
auto release = Void::Scope::on_exit([&] { admission.release(); });
|
|
pump_until([] {}, [&] { return admission.waiting(); }, "Guest did not reach pre-admission barrier.");
|
|
// This is a genuine owner publication between the adapter's compatibility
|
|
// check of S and admission of the remote command, without an epoch change.
|
|
RuntimeSubmission canceled{RuntimeAdmission::Busy, {}};
|
|
pump_until([&] {
|
|
canceled = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
|
|
checked->next_requests[0], CancelProductionPayload{production}});
|
|
}, [&] { return canceled.admission != RuntimeAdmission::Busy; }, "Cancel could not obtain owner admission.");
|
|
require(canceled.admission == RuntimeAdmission::Accepted && canceled.completion.wait_for(3s) == std::future_status::ready);
|
|
require(canceled.completion.get().receipt->command_status == CommandStatus::Accepted);
|
|
const auto cutoff = runtime.latest();
|
|
require(cutoff != checked && cutoff->identity.session == id.session && !cutoff->world->legacy_representable());
|
|
admission.release();
|
|
require(polling.wait_for(3s) == std::future_status::ready);
|
|
polling.get();
|
|
RuntimeSubmission fence{RuntimeAdmission::Busy, {}};
|
|
pump_until([&] { fence = runtime.synchronize(); }, [&] { return fence.admission != RuntimeAdmission::Busy; },
|
|
"Owner fence could not be admitted.");
|
|
require(fence.admission == RuntimeAdmission::Accepted && fence.completion.wait_for(3s) == std::future_status::ready);
|
|
require(fence.completion.get().outcome == RuntimeOutcome::Completed);
|
|
const auto after = runtime.latest();
|
|
const auto evidence = "Guest command crossed incompatible publication: next_request=" +
|
|
std::to_string(after->next_requests[1]);
|
|
if (after->next_requests[1] != checked->next_requests[1]) throw std::runtime_error(evidence);
|
|
require(after->world->next_command_sequence(2) == checked->world->next_command_sequence(2));
|
|
require(after->world->agents().front().profession == old_profession && !runtime.lookup({2}, envelope));
|
|
require(after == cutoff && runtime.view().state == RuntimeState::Running);
|
|
pump_until([&] { host.poll_host(runtime); guest.poll(); }, [&] { return guest.closed; },
|
|
"Race-cutoff peer was not disconnected.");
|
|
require(host.state() == LanState::Hosting && guest.receipts.empty());
|
|
require(encode_checkpoint(*after->world, id.world, id.city, *after->rules).has_value());
|
|
}
|
|
|
|
Test LanTests::test_guest_retries_same_sequence_after_compatible_publication() {
|
|
CaptureGate admission;
|
|
SimulationRuntime runtime(colony_checkpoint(), {.ticking = false});
|
|
LanSession host({.before_command_admission = [&] { admission.block(); }});
|
|
host.host(0, true);
|
|
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
|
|
const auto pump = [&] { host.poll_host(runtime); guest.poll(); };
|
|
pump_until(pump, [&] { return guest.snapshot != nullptr; }, "Compatible-race guest did not join.");
|
|
const auto checked = runtime.latest();
|
|
const auto id = checked->identity;
|
|
const auto resident = checked->world->agents().back().id;
|
|
admission.arm();
|
|
guest.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), resident);
|
|
guest.poll();
|
|
auto polling = std::async(std::launch::async, [&] { host.poll_host(runtime); });
|
|
auto release = Void::Scope::on_exit([&] { admission.release(); });
|
|
pump_until([] {}, [&] { return admission.waiting(); }, "Compatible command did not reach admission barrier.");
|
|
RuntimeSubmission local{RuntimeAdmission::Busy, {}};
|
|
pump_until([&] {
|
|
local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
|
|
checked->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}});
|
|
}, [&] { return local.admission != RuntimeAdmission::Busy; }, "Compatible local change could not be admitted.");
|
|
require(local.admission == RuntimeAdmission::Accepted && local.completion.wait_for(3s) == std::future_status::ready);
|
|
require(local.completion.get().receipt->command_status == CommandStatus::Accepted);
|
|
const auto changed = runtime.latest();
|
|
require(changed != checked && changed->identity.session == id.session && changed->world->legacy_representable());
|
|
admission.release();
|
|
require(polling.wait_for(3s) == std::future_status::ready);
|
|
polling.get();
|
|
pump_until(pump, [&] { return guest.receipts.size() == 1; }, "Compatible revision did not report retryable Busy.");
|
|
require(guest.receipts.front().status == CommandStatus::Busy && guest.receipts.front().next_sequence == 1);
|
|
require(runtime.latest() == changed && changed->next_requests[1] == 1 && host.state() == LanState::HostConnected);
|
|
guest.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), resident);
|
|
pump_until(pump, [&] { return guest.receipts.size() == 2; }, "Same-sequence guest retry did not settle.");
|
|
require(guest.receipts.back().status == CommandStatus::Accepted && guest.receipts.back().next_sequence == 2);
|
|
require(runtime.latest()->next_requests[1] == 2 && runtime.latest()->world->agents().back().profession == Profession::Miner);
|
|
}
|
|
|
|
Test LanTests::test_conditional_admission_preserves_accepted_work_and_reports_refusals() {
|
|
CaptureGate owner;
|
|
RuntimeOptions options{.capacity = 2, .ticking = false};
|
|
options.observer = [&](RuntimePhase phase) { owner.capture(phase); };
|
|
SimulationRuntime runtime(colony_checkpoint(), options);
|
|
auto release = Void::Scope::on_exit([&] { owner.release(); });
|
|
const auto checked = runtime.latest();
|
|
const auto id = checked->identity;
|
|
const CommandEnvelope local_command{command_envelope_version, id.world, id.session, id.city,
|
|
checked->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}};
|
|
const CommandEnvelope guest_command{command_envelope_version, id.world, id.session, id.city,
|
|
checked->next_requests[1], CommandPayload{CommandKind::AssignProfession, {},
|
|
static_cast<std::uint8_t>(Profession::Miner), {}, checked->world->agents().back().id}};
|
|
const auto invalid = runtime.try_submit_if_current({2}, guest_command, {});
|
|
require(invalid.admission == RuntimeAdmission::InvalidRequest && !invalid.completion.valid());
|
|
owner.arm();
|
|
RuntimeSubmission local{RuntimeAdmission::Busy, {}};
|
|
pump_until([&] { local = runtime.try_submit({1}, local_command); },
|
|
[&] { return local.admission != RuntimeAdmission::Busy; }, "Local work did not enter owner queue.");
|
|
require(local.admission == RuntimeAdmission::Accepted);
|
|
pump_until([] {}, [&] { return owner.waiting(); }, "Owner did not reach capture barrier.");
|
|
RuntimeSubmission accepted{RuntimeAdmission::Busy, {}};
|
|
pump_until([&] { accepted = runtime.try_submit_if_current({2}, guest_command, checked); },
|
|
[&] { return accepted.admission != RuntimeAdmission::Busy; }, "Conditional work did not enter remaining slot.");
|
|
require(accepted.admission == RuntimeAdmission::Accepted);
|
|
const auto full = runtime.try_submit_if_current({2}, guest_command, checked);
|
|
require(full.admission == RuntimeAdmission::Busy && !full.completion.valid());
|
|
// Both operations were admitted while S was current. Publishing the local
|
|
// result must not revoke the already queued guarded guest operation.
|
|
owner.release();
|
|
require(local.completion.wait_for(3s) == std::future_status::ready &&
|
|
local.completion.get().receipt->command_status == CommandStatus::Accepted);
|
|
require(accepted.completion.wait_for(3s) == std::future_status::ready &&
|
|
accepted.completion.get().receipt->command_status == CommandStatus::Accepted);
|
|
const auto current = runtime.latest();
|
|
require(current != checked && current->next_requests[1] == 2);
|
|
RuntimeSubmission stale{RuntimeAdmission::Busy, {}};
|
|
pump_until([&] { stale = runtime.try_submit_if_current({2}, guest_command, checked); },
|
|
[&] { return stale.admission != RuntimeAdmission::Busy; }, "Stale snapshot refusal remained contended.");
|
|
require(stale.admission == RuntimeAdmission::StaleSnapshot && !stale.completion.valid());
|
|
require(runtime.latest() == current);
|
|
runtime.shutdown();
|
|
const auto closed = runtime.try_submit_if_current({2}, guest_command, current);
|
|
require(closed.admission == RuntimeAdmission::Closed && !closed.completion.valid());
|
|
}
|
|
|
|
Test LanTests::test_conditional_admission_rejects_faulted_owner_with_retained_publication() {
|
|
RuntimeOptions options{.ticking = false};
|
|
options.observer = [](RuntimePhase phase) {
|
|
if (phase == RuntimePhase::BeforeCapture) throw std::runtime_error("Injected guarded-admission fault.");
|
|
};
|
|
SimulationRuntime runtime(colony_checkpoint(), options);
|
|
const auto checked = runtime.latest();
|
|
const auto id = checked->identity;
|
|
const CommandEnvelope command{command_envelope_version, id.world, id.session, id.city,
|
|
checked->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}};
|
|
RuntimeSubmission fault{RuntimeAdmission::Busy, {}};
|
|
pump_until([&] { fault = runtime.try_submit({1}, command); },
|
|
[&] { return fault.admission != RuntimeAdmission::Busy; }, "Fault trigger remained contended.");
|
|
require(fault.admission == RuntimeAdmission::Accepted && fault.completion.wait_for(3s) == std::future_status::ready);
|
|
require(fault.completion.get().outcome == RuntimeOutcome::Faulted);
|
|
require(runtime.latest() == checked && runtime.view().state == RuntimeState::Faulted);
|
|
RuntimeSubmission denied{RuntimeAdmission::Busy, {}};
|
|
pump_until([&] { denied = runtime.try_submit_if_current({1}, command, checked); },
|
|
[&] { return denied.admission != RuntimeAdmission::Busy; }, "Faulted owner refusal remained contended.");
|
|
require(denied.admission == RuntimeAdmission::Closed && !denied.completion.valid());
|
|
require(runtime.latest() == checked && !runtime.lookup({1}, command));
|
|
}
|
|
|
|
} // namespace
|