Files
aevolution/tests/simulation_tests.cpp
T

358 lines
16 KiB
C++

#include "evo/simulation/scheduler.hpp"
#include "evo/simulation/world.hpp"
#include "evo/telemetry/sinks.hpp"
#include <algorithm>
#include <array>
#include <exception>
#include <iostream>
#include <limits>
#include <source_location>
#include <sstream>
#include <stdexcept>
#include <string>
namespace {
void check(bool condition, const char* expression,
std::source_location location = std::source_location::current()) {
if (!condition) {
throw std::runtime_error(std::string{location.file_name()} + ":" +
std::to_string(location.line()) + " " + expression);
}
}
#define CHECK(expression) check(static_cast<bool>(expression), #expression)
void advance(evo::SimulationWorld& world, std::uint64_t ticks) {
for (std::uint64_t tick = 0; tick < ticks; ++tick) {
CHECK(world.tick());
}
}
evo::SimulationWorld fixture(std::uint64_t seed, std::uint32_t count) {
evo::SimulationWorld world{seed};
for (std::uint32_t index = 0; index < count; ++index) {
CHECK(world.create_entity());
}
return world;
}
void put(evo::Snapshot& bytes, std::size_t offset, std::uint64_t value, std::size_t width) {
for (std::size_t index = 0; index < width; ++index) {
bytes.at(offset + index) = static_cast<std::uint8_t>(value & 0xffU);
value >>= 8U;
}
}
void resign(evo::Snapshot& bytes) {
std::uint64_t hash = 14695981039346656037ULL;
for (std::size_t index = 0; index < bytes.size() - 8; ++index) {
hash = (hash ^ bytes[index]) * 1099511628211ULL;
}
put(bytes, bytes.size() - 8, hash, 8);
}
void random_vectors() {
evo::Random random{0};
constexpr std::array<std::uint64_t, 4> expected{0xe220a8397b1dcdafULL, 0x6e789e6aa1b965f4ULL,
0x06c45d188009454fULL, 0xf88bb8a8724c81ecULL};
for (const auto value : expected) {
CHECK(random.next() == value);
}
evo::Random resumed{random.state()};
CHECK(resumed.next() == random.next());
evo::Random zero_first{0x61c8864680b583ebULL};
CHECK(zero_first.ternary() == 1);
CHECK(zero_first.state() == 0x9e3779b97f4a7c15ULL);
for (int index = 0; index < 10'000; ++index) {
CHECK(random.ternary() < 3);
}
}
void entity_lifecycle() {
evo::SimulationWorld world{42};
CHECK(world.entities().empty());
const auto first = world.create_entity();
const auto second = world.create_entity({evo::Millimetres{1023}, evo::Millimetres{0}});
CHECK(first && second);
CHECK(first->value == 1 && second->value == 2);
const auto before = world.serialize();
const auto invalid = world.create_entity({evo::Millimetres{1024}, evo::Millimetres{0}});
CHECK(!invalid && invalid.error() == evo::Error::invalid_position);
CHECK(world.serialize() == before);
CHECK(world.remove_entity(*first));
const auto stale = world.remove_entity(*first);
CHECK(!stale && stale.error() == evo::Error::entity_not_found);
const auto third = world.create_entity();
CHECK(third && third->value == 3);
CHECK(world.entities()[0].id == *second);
CHECK(world.entities()[1].id == *third);
CHECK(!world.remove_entity(evo::EntityId{0}));
}
void golden_simulation() {
auto world = fixture(123456, 8);
advance(world, 1000);
CHECK(world.state_hash() == 0xd61ad5bf0c928c76ULL);
constexpr std::array<std::array<std::uint32_t, 2>, 8> positions{
{{49, 10}, {985, 993}, {39, 33}, {1008, 0}, {16, 1}, {7, 3}, {1004, 1007}, {995, 15}}};
for (std::size_t index = 0; index < positions.size(); ++index) {
CHECK(world.entities()[index].position.x.value == positions[index][0]);
CHECK(world.entities()[index].position.y.value == positions[index][1]);
}
auto other = fixture(123457, 8);
advance(other, 1000);
CHECK(other.state_hash() != world.state_hash());
}
void replay_properties() {
for (std::uint64_t seed = 0; seed < 64; ++seed) {
auto full = fixture(seed, static_cast<std::uint32_t>(seed % 17));
auto partial = full;
const auto total = 2 * seed + 1;
advance(full, total);
advance(partial, seed);
const auto bytes = partial.serialize();
auto restored = evo::SimulationWorld::restore(bytes);
CHECK(restored);
CHECK(restored->serialize() == bytes);
advance(*restored, total - seed);
CHECK(restored->serialize() == full.serialize());
CHECK(restored->current_tick().value == total);
for (const auto& entity : restored->entities()) {
CHECK(entity.position.x.value < evo::domain_extent_mm);
CHECK(entity.position.y.value < evo::domain_extent_mm);
}
}
}
void stream_independence() {
auto full = fixture(91, 2);
auto reduced = full;
CHECK(reduced.remove_entity(evo::EntityId{1}));
advance(full, 500);
advance(reduced, 500);
CHECK(full.entities()[1].position == reduced.entities()[0].position);
CHECK(full.entities()[1].random.state() == reduced.entities()[0].random.state());
}
void malformed_snapshots() {
const auto bytes = fixture(77, 2).serialize();
for (std::size_t length = 0; length < bytes.size(); ++length) {
CHECK(!evo::SimulationWorld::restore(std::span{bytes}.first(length)));
}
for (std::size_t index = 0; index < bytes.size(); ++index) {
auto corrupted = bytes;
corrupted[index] ^= 0x80U;
CHECK(!evo::SimulationWorld::restore(corrupted));
}
auto extra = bytes;
extra.push_back(0);
CHECK(!evo::SimulationWorld::restore(extra));
CHECK(!evo::SimulationWorld::restore(evo::Snapshot(evo::max_snapshot_bytes + 1)));
struct Field {
std::size_t offset;
std::uint64_t value;
std::size_t width;
};
const std::array fields{Field{40, 0, 8},
Field{40, 2, 8}, // invalid next ID
Field{48, evo::max_entities + 1, 4},
Field{48, 1, 4}, // count/length
Field{52, 0, 8},
Field{52, 2, 8},
Field{76, 1, 8}, // zero/duplicate/order
Field{60, evo::domain_extent_mm, 4},
Field{64, evo::domain_extent_mm, 4}};
for (const auto field : fields) {
auto invalid = bytes;
put(invalid, field.offset, field.value, field.width);
resign(invalid); // Reach semantic checks beyond checksum rejection.
CHECK(!evo::SimulationWorld::restore(invalid));
}
for (const auto offset : {8U, 12U, 16U}) {
auto unsupported = bytes;
put(unsupported, offset, 999, 4);
resign(unsupported);
const auto restored = evo::SimulationWorld::restore(unsupported);
CHECK(!restored && restored.error() == evo::Error::unsupported_version);
}
}
void exhaustion_is_atomic() {
auto bytes = fixture(17, 1).serialize();
put(bytes, 32, std::numeric_limits<std::uint64_t>::max(), 8);
resign(bytes);
auto full_tick = evo::SimulationWorld::restore(bytes);
CHECK(full_tick);
const auto result = full_tick->tick();
CHECK(!result && result.error() == evo::Error::tick_exhausted);
CHECK(full_tick->serialize() == bytes);
bytes = fixture(17, 1).serialize();
put(bytes, 40, std::numeric_limits<std::uint64_t>::max(), 8);
resign(bytes);
auto full_id = evo::SimulationWorld::restore(bytes);
CHECK(full_id);
const auto created = full_id->create_entity();
CHECK(!created && created.error() == evo::Error::id_exhausted);
CHECK(full_id->serialize() == bytes);
}
void capacity_boundary() {
auto world = fixture(31, evo::max_entities);
const auto before = world.state_hash();
const auto result = world.create_entity();
CHECK(!result && result.error() == evo::Error::entity_limit);
CHECK(world.state_hash() == before);
const auto restored = evo::SimulationWorld::restore(world.serialize());
CHECK(restored && restored->entities().size() == evo::max_entities);
}
void wire_layout_and_empty_state() {
evo::SimulationWorld world{0x1122334455667788ULL};
const auto bytes = world.serialize();
CHECK(bytes.size() == 60);
CHECK(bytes[8] == 1 && bytes[9] == 0);
CHECK(bytes[24] == 0x88 && bytes[31] == 0x11);
auto restored = evo::SimulationWorld::restore(bytes);
CHECK(restored && restored->serialize() == bytes);
const auto created = restored->create_entity();
CHECK(created && created->value == 1);
}
void telemetry_is_host_owned() {
const auto world = fixture(4, 3);
const auto before = world.serialize();
std::ostringstream text;
evo::PrometheusTextSink sink{text};
sink.observe({world.current_tick(), static_cast<std::uint64_t>(world.entities().size())});
CHECK(text.str().find("evo_active_entities 3\n") != std::string::npos);
CHECK(world.serialize() == before);
std::ostringstream log;
evo::log_error(log, evo::Error::invalid_snapshot);
CHECK(log.str() == "{\"level\":\"error\",\"event\":\"invalid_snapshot\"}\n");
}
void scheduled_order_and_recovery() {
for (std::uint64_t seed = 0; seed < 32; ++seed) {
auto expected = fixture(seed, 2);
CHECK(expected.remove_entity(evo::EntityId{1}));
CHECK(expected.create_entity({evo::Millimetres{1023}, evo::Millimetres{0}}));
CHECK(expected.create_entity());
CHECK(expected.tick());
std::array commands{
evo::Command{10, evo::RemoveEntity{evo::EntityId{1}}},
evo::Command{20, evo::CreateEntity{{evo::Millimetres{1023}, evo::Millimetres{0}}}},
evo::Command{30, evo::CreateEntity{}}};
do {
auto world = fixture(seed, 2);
const auto receipts = evo::advance(world, evo::Tick{1}, commands);
CHECK(receipts && receipts->size() == 3);
CHECK((*receipts)[0] == (evo::CommandReceipt{10, evo::EntityId{1}}));
CHECK((*receipts)[1] == (evo::CommandReceipt{20, evo::EntityId{3}}));
CHECK((*receipts)[2] == (evo::CommandReceipt{30, evo::EntityId{4}}));
CHECK(world.serialize() == expected.serialize());
auto restored = evo::SimulationWorld::restore(world.serialize());
CHECK(restored);
for (std::uint64_t tick = 2; tick < 20; ++tick) {
const std::array next{evo::Command{1, evo::CreateEntity{}}};
CHECK(evo::advance(world, evo::Tick{tick}, next));
CHECK(evo::advance(*restored, evo::Tick{tick}, next));
}
CHECK(restored->serialize() == world.serialize());
} while (std::ranges::next_permutation(commands, {}, &evo::Command::sequence).found);
}
auto scheduled = fixture(123456, 8);
for (std::uint64_t tick = 1; tick <= 1000; ++tick) {
CHECK(evo::advance(scheduled, evo::Tick{tick}));
}
CHECK(scheduled.state_hash() == 0xd61ad5bf0c928c76ULL);
}
void scheduled_rejection() {
auto world = fixture(17, 2);
const auto before = world.serialize();
const auto reject = [&](evo::Tick tick, std::span<const evo::Command> commands,
evo::ScheduleErrorCode code) {
const auto result = evo::advance(world, tick, commands);
CHECK(!result && result.error().code == code);
CHECK(world.serialize() == before);
return result.error();
};
reject(evo::Tick{0}, {}, evo::ScheduleErrorCode::wrong_tick);
reject(evo::Tick{2}, {}, evo::ScheduleErrorCode::wrong_tick);
std::array commands{evo::Command{1, evo::CreateEntity{}},
evo::Command{1, evo::RemoveEntity{evo::EntityId{1}}}};
reject(evo::Tick{1}, commands, evo::ScheduleErrorCode::duplicate_sequence);
commands[1].sequence = 0;
reject(evo::Tick{1}, commands, evo::ScheduleErrorCode::invalid_sequence);
commands[1] = evo::Command{2, evo::RemoveEntity{evo::EntityId{99}}};
auto error = reject(evo::Tick{1}, commands, evo::ScheduleErrorCode::simulation_failure);
CHECK(error.sequence == 2 && error.cause == evo::Error::entity_not_found);
commands[1] = evo::Command{2, evo::CreateEntity{{evo::Millimetres{1024}, {}}}};
error = reject(evo::Tick{1}, commands, evo::ScheduleErrorCode::simulation_failure);
CHECK(error.cause == evo::Error::invalid_position);
commands = {evo::Command{1, evo::RemoveEntity{evo::EntityId{1}}},
evo::Command{2, evo::RemoveEntity{evo::EntityId{1}}}};
reject(evo::Tick{1}, commands, evo::ScheduleErrorCode::simulation_failure);
std::vector<evo::Command> large(evo::max_commands_per_tick + 1,
evo::Command{1, evo::CreateEntity{}});
reject(evo::Tick{1}, large, evo::ScheduleErrorCode::batch_limit);
large.pop_back();
for (std::size_t index = 0; index < large.size(); ++index) {
large[index].sequence = index + 1;
}
CHECK(evo::advance(world, evo::Tick{1}, large));
const auto committed = world.serialize();
const auto retry = evo::advance(world, evo::Tick{1}, large);
CHECK(!retry && retry.error().code == evo::ScheduleErrorCode::wrong_tick);
CHECK(world.serialize() == committed);
auto full = fixture(1, evo::max_entities);
const auto full_before = full.serialize();
const std::array create{evo::Command{1, evo::CreateEntity{}}};
const auto capacity = evo::advance(full, evo::Tick{1}, create);
CHECK(!capacity && capacity.error().cause == evo::Error::entity_limit);
CHECK(full.serialize() == full_before);
for (const auto offset : {32U, 40U}) {
auto bytes = before;
put(bytes, offset, std::numeric_limits<std::uint64_t>::max(), 8);
resign(bytes);
auto exhausted = evo::SimulationWorld::restore(bytes);
CHECK(exhausted);
const auto result = evo::advance(*exhausted, evo::Tick{1}, create);
CHECK(!result && result.error().cause == (offset == 32 ? evo::Error::tick_exhausted
: evo::Error::id_exhausted));
CHECK(exhausted->serialize() == bytes);
}
}
} // namespace
int main(int argc, char**) try {
// Dedicated CTest WILL_FAIL entry checks that this harness fails in Release.
if (argc > 1) {
try {
CHECK(false);
} catch (const std::exception&) {
return 1;
}
return 0;
}
struct Test {
const char* name;
void (*run)();
};
const std::array tests{Test{"random reference vectors", random_vectors},
Test{"entity lifecycle", entity_lifecycle},
Test{"frozen simulation fixture", golden_simulation},
Test{"seeded replay properties", replay_properties},
Test{"independent streams", stream_independence},
Test{"bounded snapshots", malformed_snapshots},
Test{"atomic exhaustion", exhaustion_is_atomic},
Test{"capacity", capacity_boundary},
Test{"canonical empty state", wire_layout_and_empty_state},
Test{"host telemetry", telemetry_is_host_owned},
Test{"scheduled order and recovery", scheduled_order_and_recovery},
Test{"atomic scheduler rejection", scheduled_rejection}};
int failures = 0;
for (const auto& test : tests) {
try {
test.run();
std::cout << "PASS " << test.name << '\n';
} catch (const std::exception& error) {
++failures;
std::cerr << "FAIL " << test.name << ": " << error.what() << '\n';
}
}
return failures == 0 ? 0 : 1;
} catch (...) {
return 1;
}