Files
stoneheart_at_home/tests/checkpoint_tests.cpp

412 lines
23 KiB
C++

#include "settlement/core/checkpoint.hpp"
#include <Void/Binary/Reader.hpp>
#include <Void/Binary/Writer.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <cstring>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace {
using namespace settlement;
using Void::Testing::Test;
constexpr Void::Uuid::Uuid world_id{{0x91, 2, 3, 4, 5, 6, 0x47, 8, 0x89, 10, 11, 12, 13, 14, 15, 16}};
void require(bool condition, std::string_view message) {
if (!condition) throw std::runtime_error(std::string(message));
}
template<class T, class Error>
T checked(std::expected<T, Error> result) {
if (!result) throw std::runtime_error(result.error().message);
return std::move(*result);
}
std::string saved_state(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return std::move(stream).str();
}
std::string encoded(const World& world, const RulesManifest& rules) {
return checked(encode_checkpoint(world, world_id, 7, rules));
}
WorldCheckpoint decoded(std::string_view bytes, std::span<const RulePackage> catalog) {
return checked(decode_checkpoint(bytes, catalog, 1, ExecutionMode::SerialReference));
}
void rejected(std::string_view bytes, std::span<const RulePackage> catalog,
CheckpointError code, std::string_view field = {}, std::string_view package = {}) {
const auto result = decode_checkpoint(bytes, catalog, 1, ExecutionMode::SerialReference);
require(!result, "invalid checkpoint was accepted");
require(result.error().code == code && !result.error().message.empty(), "checkpoint error lost its code or message");
require(result.error().field.find(field) != std::string::npos, "checkpoint error named the wrong field");
require(result.error().package.find(package) != std::string::npos, "checkpoint error lost its package");
}
template<class T>
void change(std::string& bytes, std::size_t offset, T value) {
Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}).subspan(offset));
require(writer.writeLittle(value).has_value(), "fixture field write failed");
}
void rehash(std::string& bytes) {
auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
require(hasher.has_value(), "fixture hasher creation failed");
require(hasher->update(std::string_view(bytes).substr(0, bytes.size() - 32)).has_value(), "fixture hash failed");
const auto checksum = hasher->finalize();
require(checksum.has_value() && checksum->size() == 32, "fixture hash finalization failed");
std::memcpy(bytes.data() + bytes.size() - 32, checksum->data(), checksum->size());
}
struct PackageLocation {
std::size_t begin;
std::size_t version_length;
std::size_t end;
};
struct FrameLayout {
std::uint32_t metadata_size;
std::uint64_t body_size;
std::size_t body_begin;
std::vector<PackageLocation> packages;
};
FrameLayout layout(std::string_view bytes) {
Void::Binary::Reader reader(std::as_bytes(std::span{bytes.data(), bytes.size()}));
require(reader.skip(12).has_value(), "fixture header skip failed");
FrameLayout result{};
result.metadata_size = reader.readLittle<std::uint32_t>().value();
result.body_size = reader.readLittle<std::uint64_t>().value();
result.body_begin = 24 + result.metadata_size;
require(reader.skip(64).has_value(), "fixture metadata skip failed");
const auto count = reader.readLittle<std::uint32_t>().value();
for (std::uint32_t i = 0; i < count; ++i) {
const auto begin = reader.position();
const auto id_size = reader.readLittle<std::uint16_t>().value();
require(reader.skip(id_size).has_value(), "fixture ID skip failed");
const auto version_length = reader.position();
const auto version_size = reader.readLittle<std::uint16_t>().value();
require(reader.skip(version_size + 32).has_value(), "fixture identity skip failed");
result.packages.push_back({begin, version_length, reader.position()});
}
return result;
}
std::string package_json(std::string_view id, std::string_view version = "1.0.0",
std::string_view dependencies = "[]") {
return "{\"schema\":1,\"id\":\"" + std::string(id) + "\",\"version\":\"" + std::string(version) +
"\",\"dependencies\":" + std::string(dependencies) + ",\"exclusive_capabilities\":[],\"definitions\":[]}";
}
RulePackage load(std::string_view json) { return checked(load_rule_package("checkpoint-fixture.json", json)); }
// Captured before S04 with the baseline 4ba64f7 library, using seed 43,
// a 3x3 world, one SawPlank order, default rules, world_id and city 7.
// The v13 frame is byte-for-byte original (SHA256
// 28043dcc2a9faa6e1b217eb19df5807e159a0ac4bfdcd65de464034527557847).
// v1/v8 bodies apply their historical field/footer layout to that fixed fixture.
std::string old_checkpoint(std::size_t variant) {
constexpr std::array<std::string_view, 3> hex{
"53544843484b505401000000b6000000cb000000000000009102030405064708890a0b0c0d0e0f1007000000000000000000"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530d0000002b00000000000000030000000300000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001"
"0000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000bd7066618db314e2ca874c7eae12d9f8cc45a222c446e23906dbd6645710cd62",
"53544843484b505401000000b6000000a4000000000000009102030405064708890a0b0c0d0e0f1007000000000000000000"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c455253010000002b00000000000000030000000300000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001"
"0000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000000"
"000000000000000000000000224ae83870bea33ac3afafcd0190d032cb7b517123fb4ac93479daa4cc71cc74ed17ba385446"
"aa69",
"53544843484b505401000000b6000000d3000000000000009102030405064708890a0b0c0d0e0f1007000000000000000000"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c455253080000002b00000000000000030000000300000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001"
"0000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000f92cb77443aeca815745b0132cc684f43738865a4034d4474a373902a294e9c31801c47cf80037e4",
};
std::string result;
const auto value = [](char c) { return c <= '9' ? c - '0' : c - 'a' + 10; };
for (std::size_t i = 0; i < hex[variant].size(); i += 2) {
result.push_back(static_cast<char>(value(hex[variant][i]) * 16 + value(hex[variant][i + 1])));
}
return result;
}
struct [[= Void::Testing::name("CheckpointTests")]] CheckpointTests : Void::Testing::Suite<CheckpointTests> {
[[= Void::Testing::tag("production-id")]] Test test_authentic_v1_import_and_authenticated_schema_body_pairing();
[[= Void::Testing::tag("checkpoint")]] Test test_round_trip_preserves_identity_and_legacy_world_bytes();
[[= Void::Testing::tag("checkpoint")]] Test test_mid_carry_round_trip_continues_the_same_world();
[[= Void::Testing::tag("checkpoint")]] Test test_selected_rules_survive_catalog_reordering();
[[= Void::Testing::tag("checkpoint")]] Test test_missing_changed_and_duplicate_installed_packages();
[[= Void::Testing::tag("checkpoint")]] Test test_integrity_covers_the_entire_frame_and_rejects_truncation();
[[= Void::Testing::tag("checkpoint")]] Test test_bounded_metadata_and_complete_dependency_closure();
[[= Void::Testing::tag("checkpoint")]] Test test_valid_checksum_still_requires_valid_identity_and_world();
[[= Void::Testing::tag("checkpoint")]] Test test_world_body_larger_than_one_shot_hash_limit();
};
Test CheckpointTests::test_authentic_v1_import_and_authenticated_schema_body_pairing() {
const auto catalog = checked(builtin_rule_packages());
const auto rules = checked(default_rules_manifest());
for (std::size_t variant = 0; variant < 3; ++variant) {
auto imported = decoded(old_checkpoint(variant), catalog);
require(imported.world_id == world_id && imported.city == 7 && imported.rules == rules &&
imported.world->production_orders().size() == 1 && imported.world->production_orders().front().id == 1,
"authentic schema-1 checkpoint did not import its legacy body");
imported.world->queue_production({2, 2}, RecipeId::SawPlank);
require(imported.world->production_orders().back().id == 2, "legacy import did not set its next production ID");
}
auto imported = decoded(old_checkpoint(0), catalog);
auto current = encoded(*imported.world, rules);
require(static_cast<unsigned char>(current[8]) == 3 &&
static_cast<unsigned char>(current[layout(current).body_begin + 8]) == 15,
"new checkpoint lacks the current schema/body pair");
auto false_legacy = current;
change(false_legacy, 8, std::uint32_t{1}); rehash(false_legacy);
rejected(false_legacy, catalog, CheckpointError::InvalidWorld, "world.version");
auto false_current = old_checkpoint(0);
change(false_current, 8, std::uint32_t{2}); rehash(false_current);
rejected(false_current, catalog, CheckpointError::InvalidWorld, "world.version");
for (std::size_t variant : {1U, 2U}) {
auto wrong = old_checkpoint(variant); // Inner FNV and outer SHA are both valid.
change(wrong, 8, std::uint32_t{2}); rehash(wrong);
rejected(wrong, catalog, CheckpointError::InvalidWorld, "world.version");
}
}
Test CheckpointTests::test_round_trip_preserves_identity_and_legacy_world_bytes() {
const auto catalog = checked(builtin_rule_packages());
const auto rules = checked(default_rules_manifest());
World world(43, 8, 9, 1, ExecutionMode::SerialReference);
static_cast<void>(world.spawn_agent({1, 1}));
static_cast<void>(world.add_job({6, 6}, 4));
for (int i = 0; i < 4; ++i) world.step();
const auto before = saved_state(world);
const auto bytes = encoded(world, rules);
auto restored = decoded(bytes, catalog);
require(restored.world_id == world_id && restored.city == 7 && restored.rules == rules,
"checkpoint lost stable world identity, city or rules");
require(saved_state(*restored.world) == before && saved_state(world) == before,
"checkpoint changed the original or restored canonical state");
std::ostringstream modern(std::ios::binary);
world.write_save(modern, WorldSaveFormat::Current15);
require(bytes.substr(layout(bytes).body_begin, modern.str().size()) == modern.str(),
"checkpoint did not use the current world serialization");
require(before.substr(0, 8) == "SETTLERS" && static_cast<unsigned char>(before[8]) == 13,
"canonical serialization version changed");
require(encoded(*restored.world, restored.rules) == bytes, "re-encoding changed the checkpoint frame");
auto parallel = checked(decode_checkpoint(bytes, catalog, 6));
require(parallel.world->worker_count() == 6 && saved_state(*parallel.world) == before,
"checkpoint did not honor requested execution configuration");
auto nil = encode_checkpoint(world, {}, 7, rules);
auto no_city = encode_checkpoint(world, world_id, 0, rules);
require(!nil && nil.error().code == CheckpointError::InvalidIdentity &&
!no_city && no_city.error().code == CheckpointError::InvalidIdentity,
"encode accepted an invalid world or city identity");
}
Test CheckpointTests::test_mid_carry_round_trip_continues_the_same_world() {
const auto catalog = checked(builtin_rule_packages());
const auto rules = checked(default_rules_manifest());
auto world = make_first_colony(2);
require(world->apply_command({1, 1, CommandKind::PlaceBed, {16, 18}}).status == CommandStatus::Accepted,
"fixture bed placement failed");
bool carrying = false;
for (int i = 0; i < 300 && !carrying; ++i) {
world->step();
carrying = std::any_of(world->agents().begin(), world->agents().end(), [](const Agent& agent) {
return agent.inventory.item_count(ItemType::Wood) > 0 ||
agent.inventory.item_count(ItemType::Stone) > 0 ||
agent.inventory.item_count(ItemType::Cloth) > 0;
});
}
require(carrying, "fixture never carried construction material");
const auto before = saved_state(*world);
auto restored = decoded(encoded(*world, rules), catalog);
require(saved_state(*restored.world) == before, "mid-carry checkpoint changed reservations or inventory");
for (int i = 0; i < 300; ++i) {
world->step();
restored.world->step();
require(saved_state(*world) == saved_state(*restored.world), "checkpoint continuation diverged");
}
require(world->scenario_progress().assigned_beds >= 1, "checkpoint fixture never completed its bed");
}
Test CheckpointTests::test_selected_rules_survive_catalog_reordering() {
std::vector<RulePackage> catalog{
load(package_json("game.core")),
load(package_json("game.water", "1.0.0", R"([{"id":"game.core","version":"1.0.0"}])")),
load(package_json("game.unselected"))};
const std::array dry_selection{std::string{"game.core"}};
const std::array wet_selection{std::string{"game.water"}};
const auto dry = checked(resolve_rules(catalog, dry_selection));
const auto wet = checked(resolve_rules(catalog, wet_selection));
World world(12, 5, 5, 1, ExecutionMode::SerialReference);
const auto dry_frame = encoded(world, dry);
const auto wet_frame = encoded(world, wet);
std::reverse(catalog.begin(), catalog.end());
require(decoded(dry_frame, catalog).rules == dry && decoded(wet_frame, catalog).rules == wet && dry != wet,
"installed discovery order changed selected world rules");
require(decoded(wet_frame, catalog).rules.packages().size() == 2,
"unselected installed package entered the saved rules");
}
Test CheckpointTests::test_missing_changed_and_duplicate_installed_packages() {
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
std::vector<RulePackage> catalog{load(package_json("game.core"))};
const std::array selected{std::string{"game.core"}};
const auto rules = checked(resolve_rules(catalog, selected));
const auto bytes = encoded(world, rules);
rejected(bytes, {}, CheckpointError::RulesMismatch, "packages", "game.core");
for (std::string_view version : {"1.0.1", "1.0.0+build2"}) {
const std::array changed{load(package_json("game.core", version))};
rejected(bytes, changed, CheckpointError::RulesMismatch, "version", "game.core");
}
const std::array changed_content{load(R"({"schema":1,"id":"game.core","version":"1.0.0","dependencies":[],"exclusive_capabilities":["game.core:changed"],"definitions":[]})")};
rejected(bytes, changed_content, CheckpointError::RulesMismatch, "sha256", "game.core");
catalog.push_back(catalog.front());
rejected(bytes, catalog, CheckpointError::RulesMismatch, "id", "game.core");
}
Test CheckpointTests::test_integrity_covers_the_entire_frame_and_rejects_truncation() {
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
const auto catalog = checked(builtin_rule_packages());
const auto bytes = encoded(world, checked(default_rules_manifest()));
for (std::size_t length = 0; length < bytes.size(); ++length) {
require(!decode_checkpoint(std::string_view(bytes).substr(0, length), catalog), "truncated frame was accepted");
}
rejected(bytes + "x", catalog, CheckpointError::InvalidFrame, "lengths");
for (std::size_t offset : {std::size_t{24}, std::size_t{40}, std::size_t{48}, std::size_t{56},
layout(bytes).packages.front().begin + 2, layout(bytes).body_begin, bytes.size() - 1}) {
auto corrupt = bytes;
corrupt[offset] ^= 1;
rejected(corrupt, catalog, CheckpointError::IntegrityMismatch, "sha256");
}
auto unsupported = bytes;
change(unsupported, 8, checkpoint_version + 1);
rejected(unsupported, catalog, CheckpointError::UnsupportedVersion, "version");
auto wrong_magic = bytes;
wrong_magic[0] = 'X';
rejected(wrong_magic, catalog, CheckpointError::InvalidFrame, "magic");
}
Test CheckpointTests::test_bounded_metadata_and_complete_dependency_closure() {
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
const auto catalog = checked(builtin_rule_packages());
const auto bytes = encoded(world, checked(default_rules_manifest()));
const auto wire = layout(bytes);
auto huge_body = bytes;
change(huge_body, 16, std::numeric_limits<std::uint64_t>::max());
rejected(huge_body, catalog, CheckpointError::LimitExceeded, "lengths");
auto huge_metadata = bytes;
change(huge_metadata, 12, static_cast<std::uint32_t>(max_checkpoint_metadata_bytes + 1));
rejected(huge_metadata, catalog, CheckpointError::LimitExceeded, "lengths");
for (std::uint32_t count : {0U, 129U}) {
auto invalid = bytes;
change(invalid, 88, count);
rehash(invalid);
rejected(invalid, catalog, CheckpointError::LimitExceeded, "rules.packages");
}
for (std::uint16_t count : {std::uint16_t{0}, std::uint16_t{129}}) {
auto invalid = bytes;
change(invalid, wire.packages.front().begin, count);
rehash(invalid);
rejected(invalid, catalog, CheckpointError::LimitExceeded, "rules.id");
}
auto long_version = bytes;
change(long_version, wire.packages.front().version_length, std::uint16_t{257});
rehash(long_version);
rejected(long_version, catalog, CheckpointError::LimitExceeded, "rules.version");
const auto first = wire.packages.front();
const auto last = wire.packages.back();
auto duplicate = bytes;
const auto record = bytes.substr(first.begin, first.end - first.begin);
duplicate.replace(last.begin, last.end - last.begin, record);
change(duplicate, 12, static_cast<std::uint32_t>(wire.metadata_size + record.size() - (last.end - last.begin)));
rehash(duplicate);
rejected(duplicate, catalog, CheckpointError::RulesMismatch, "rules.packages", "settlement.colony");
auto missing_dependency = bytes;
missing_dependency.erase(last.begin, last.end - last.begin);
change(missing_dependency, 12, static_cast<std::uint32_t>(wire.metadata_size - (last.end - last.begin)));
change(missing_dependency, 88, std::uint32_t{1});
rehash(missing_dependency);
rejected(missing_dependency, catalog, CheckpointError::RulesMismatch, "rules.packages", "settlement.core");
auto bad_fingerprint = bytes;
bad_fingerprint[56] ^= 1;
rehash(bad_fingerprint);
rejected(bad_fingerprint, catalog, CheckpointError::RulesMismatch, "rules.fingerprint");
}
Test CheckpointTests::test_valid_checksum_still_requires_valid_identity_and_world() {
World world(4, 5, 5, 1, ExecutionMode::SerialReference);
const auto before = saved_state(world);
const auto catalog = checked(builtin_rule_packages());
const auto bytes = encoded(world, checked(default_rules_manifest()));
const auto wire = layout(bytes);
auto nil = bytes;
std::fill_n(nil.begin() + 24, 16, '\0');
rehash(nil);
rejected(nil, catalog, CheckpointError::InvalidIdentity, "world_id");
auto no_city = bytes;
change(no_city, 40, std::uint64_t{0});
rehash(no_city);
rejected(no_city, catalog, CheckpointError::InvalidIdentity, "city");
auto wrong_tick = bytes;
change(wrong_tick, 48, std::uint64_t{1});
rehash(wrong_tick);
rejected(wrong_tick, catalog, CheckpointError::InvalidWorld, "tick");
auto invalid_dimensions = bytes;
change(invalid_dimensions, wire.body_begin + 20, std::int32_t{0});
rehash(invalid_dimensions);
rejected(invalid_dimensions, catalog, CheckpointError::InvalidWorld, "world");
auto invalid_counter = bytes;
// The existing save13 header places next_agent_id after tick, four counters and hunger.
change(invalid_counter, wire.body_begin + 69, std::uint64_t{0});
rehash(invalid_counter);
rejected(invalid_counter, catalog, CheckpointError::InvalidWorld, "world");
auto inner_trailing = bytes;
inner_trailing.insert(wire.body_begin + static_cast<std::size_t>(wire.body_size), 1, 'x');
change(inner_trailing, 16, wire.body_size + 1);
rehash(inner_trailing);
rejected(inner_trailing, catalog, CheckpointError::InvalidWorld, "world");
require(saved_state(world) == before, "failed checkpoint preparation changed the live world");
}
Test CheckpointTests::test_world_body_larger_than_one_shot_hash_limit() {
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
for (int i = 0; i < 700'000; ++i) static_cast<void>(world.add_job({1, 1}, 1));
const auto rules = checked(default_rules_manifest());
const auto catalog = checked(builtin_rule_packages());
const auto bytes = encoded(world, rules);
require(layout(bytes).body_size > 16 * 1024 * 1024, "fixture did not exceed the one-shot hash limit");
auto restored = decoded(bytes, catalog);
require(restored.world->jobs().size() == world.jobs().size() &&
restored.world->jobs().back().id == world.jobs().back().id &&
saved_state(*restored.world) == saved_state(world),
"incremental checkpoint hash lost a large supported world");
}
} // namespace