diff --git a/docs/agent-workflow/tasks/S21-02.md b/docs/agent-workflow/tasks/S21-02.md new file mode 100644 index 0000000..781d945 --- /dev/null +++ b/docs/agent-workflow/tasks/S21-02.md @@ -0,0 +1,50 @@ +# Compare authoritative custody state in journal and runtime replay + +Task ID: S21-02 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +S21 sibling at 3c7cc3c merges approved replay ef980af with provisional live World/codec 539cea0, later partner fixes will be included. tests/replay_diagnostics.hpp canonical and tests/replay_tests.cpp saved_state still choose Current14, tests/runtime_tests.cpp bytes currently defaults to Legacy13. Both projections drop custody15. S15 owns tests/snapshot_tests.cpp. Released S21 real opposite-order tests and prior hashes must still pass. + +## 2. Objective and deliverables +Use current complete raw15 state for replay/owner snapshots and identify divergent item owner, stack/reservation/transfer/receipt/balance when those facts change. Exercise retained cancel/retry and continuation on 1/2/6/12. Keep intentional legacy13/14 compatibility fixtures and golden outputs as separate existing coverage. + +## 3. Scope and non-goals +Only test replay/diagnostics and their S21 explanation. No changes to application World, protocol/codec, CMake unless unavoidable for existing registered suites, generator/M02 or unrelated tests. This is a contracted validation extension of S21-01 (M01-F8/F9). + +## 4. Files to inspect +Inspect tests/replay_tests.cpp, replay_diagnostics.hpp, runtime_tests.cpp, tests/custody_tests.cpp and custody_migration_tests.cpp, engine/include/settlement/core/{world,custody,simulation_runtime}.hpp, custody.cpp, world_save.cpp, S06-03/S15-04/docs/plan/custody.md and S21. Read surrounding domain projections and fallback. + +## 5. Write ownership and coordination +Write scope: tests/replay_tests.cpp; tests/replay_diagnostics.hpp; tests/runtime_tests.cpp; docs/plan/systems/S21.md +Isolated s21 only. You share checkout state with others in separate working directories; do not revert others or change other WTs/branches, shared Serena or any Git/Gitea state. Parent handles schema source seals. + +## 6. Implementation or investigation approach +Centralize canonical save selection in the test helper to Current15 and apply it to current replay & runtime owner world equality paths, preserving any explicit legacy compatibility expectations. Extend first-difference report from real public immutable facts with stable entity/owner IDs: resident/storage/order input stack quantities/IDs, execution and active claims, admission/operation receipt keys and result outcome, material balance. Compare canonical bytes first and retain unknown/opaque byte fallback. Organize human-readable distinctions so stock change still reports stock, before a secondary balance if relevant. Do not construct huge diagnostic maps on equality. + +## 7. Interfaces and data contracts +Consume Inventory::stack_id, Agent.execution and next_admission, ProductionOrder.input and suspended, World::item_balances(), custody_receipts() and public receipt/request/result. A public vector is a ring backing store; use key and true order only when authoritative, avoid exposing physical ring layout as game identity. No modifying private counters nor pointers into mutable shared data for assertions. Use a valid game action/migrated world with same historical projection but differing modern owner/receipts if possible (old projected world loaded vs originating modern). + +## 8. Dependencies and integration +Real source base includes custody and codec; parent will furnish final stricter validation and zero-count terminal semantics as local commits. S06 owns normal domain fixtures S15 authenticated raw15/history; S21 owns comparison and divergent-entity diagnostics, runtime stale/reload, not another codec test. External library support references existing issue #15 real execution, #7 ids/#8 transfer only if relevant. No request creation. + +## 9. Edge cases security and performance +Only derive proof from real accepted actions with invariant-valid states. Catch first divergence when original legacy projection matches despite changed durable facts; do not falsely flag a different ring backing index as a logical change. Preserve old positive-negative receipt/stale owner and reproducible opposing completion trace. Keep replay test runtime bounded (first compare bytes and build facts on mismatch only). Notify root early of genuine production defects. + +## 10. Acceptance criteria +1. Current canonical captures include all custody state on real replay and after load; regression makes prior projection blind yet new one finds named entity/step. 2. Existing identity/stock/job/context and byte fallback still work. 3. Continue canceled in-flight durable cargo through checkpoint on serial/2/6/12, retained replay/conflict without physical duplicate. 4. Root can integrate while all registered tests, 24 actual completion traces and historical golden checks remain intact. + +## 11. Verification commands and evidence +Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s21-replay-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build --parallel 6, run ctest --test-dir --output-on-failure and your targeted tests. Evidence required. Focus --tag replay and --tag runtime after build, full CTest -V, named /tmp/stoneheart-milestones.xprJ2SVp/s21-custody-*.log and git diff --check. Authentic raw13 corpora old-trajectory.bin + identity-compat-old.bin independently validated by S06; compare if behavior or underlying partner revisions change. + +## 12. Constraints and stop conditions +No application edits, publishing, shared source checkout switch, new helper API into World or script internals just for diagnostics. If blocked by partner fix, obtain it through root while implementing independent diagnostics; report exact evidence. Review independent via root. + +## 13. Authorization and decisions +Approved milestone/system work plus explicit exact-state replay and ID diagnostics from M01. Root keeps transient cross-branch commits local pending package acceptance. + +## 14. Return format +Return S21-02 READY or PARTIAL with real base, owned diff, command results, source domain/id and regression observations, test runtime and external dependencies. + +Worktree now at `e26b9c2` includes the stricter S06 validator and S15 zero-count terminal effects, count budgets and authentic migration/ring tests from `ccd50ec`. Begin on this combined source. diff --git a/docs/plan/systems/S21.md b/docs/plan/systems/S21.md index 0cbe411..6a403bf 100644 --- a/docs/plan/systems/S21.md +++ b/docs/plan/systems/S21.md @@ -111,7 +111,7 @@ Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` предоставляет `Futu координатора, который при переполнении сам может ждать в inline callable. Ожидания ограничены пятью секундами; scope guard всегда открывает ворота до ожидания координатора или разрушения пула. Каждая из 24 конфигураций сравнивает -все 40 тактов с последовательным эталоном через настоящий `Current14` writer. +все 40 тактов с последовательным эталоном через настоящий `Current15` writer. Лог содержит фактическую последовательность завершений каждой конфигурации. [RuntimeTests](../../../tests/runtime_tests.cpp) удерживает старую задачу во время @@ -124,8 +124,9 @@ Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` предоставляет `Futu [Test-local диагностика](../../../tests/replay_diagnostics.hpp) сначала сравнивает канонические байты. Только при несовпадении она показывает первый различающийся -публичный факт: ID жителя/задания/производства, поле, expected/actual; для запасов — -владельца и тип предмета; для команд — игрока и следующую последовательность. +публичный факт с ID жителя, задания или производства, именем поля и значениями +expected/actual. Для запасов указываются владелец, тип предмета и ID стека, +для команд — игрок и следующий номер. Сравнение квитанций содержит игрока, номер команды, статус, tick и revision. Контекст включает первый обнаруженный tick/attempt, seed мира, число потоков, расписание, состояние загрузки и предел допуска. Непокрытое публичной проекцией @@ -150,3 +151,38 @@ Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` предоставляет `Futu Физическая Windows, длительная нагрузка и производительность GPU здесь не проверялись. Serena/граф были связаны с основным checkout; для изолированного worktree использована прямая проверка исходников без переключения общего проекта и без заявления о покрытии графом. + +## Полное состояние владения грузом + +Потактный эталон и сравнение публикаций владельца используют `Current15`. +Сравнение включает имущество у производства, приостановку заказа, следующий +номер назначения, действующее исполнение и его резервы, результаты передач +и баланс каждого предмета. При расхождении диагностика показывает сначала +видимое изменение запасов или задания, затем постоянные ID и шаги исполнения, +сохранённые результаты и счётчики баланса. Ключ квитанции состоит из вида, +ID и номера операции. Положение квитанции в кольцевом буфере не служит её ID. +Если публичные факты совпали, сравнение сообщает первое различие байтов. + +Проверка загрузки прежнего формата создаёт корректные миры с одинаковыми +байтами `Current14` и разными данными `Current15`. Она выявляет восстановленный +ID стека, различие начального остатка и начисления и отсутствие квитанции +назначения в историческом сохранении. Диагностический пример сообщает +`stock owner=storage:1 item=3 field=stack_id expected=2 actual=1`. + +Отдельный сценарий отменяет настоящую стройку после доставки, заполняет +исходный склад и возвращает одну доску в склад вместимостью один предмет. +Оставшиеся две доски и два каменных блока ждут места у того же исполнителя +с тем же ID передачи. Контрольная точка восстанавливается на 1/2/6/12 +исполнителях. После появления свободного склада каждый такт совпадает +с непрерывной партией. Точные и конфликтующие повторы квитанций назначения +и отмены проверяются до и после загрузки и после возврата груза. + +Windows x64 Release GCC 16.2 под Wine 11 выполнил 10 проверок `replay` за 2,71 с +и 11 проверок `runtime` за 30 мс на рабочем срезе `e26b9c2` с этой проверкой. +Все 24 расписания завершения настоящих задач сохранились. Сценарий частичного +возврата занял 19,1 мс. Логи находятся в +`/tmp/stoneheart-milestones.xprJ2SVp/s21-custody-{configure,build-final,replay,runtime}.log`. +После объединения с исправлением проверки времени и ссылок S06 в `8522f91` +повторная сборка и CTest завершились с кодом 0. Все три цели прошли за 26,91 с, +включая 169 проверок ядра, 9 LAN и 10 клиента. Журналы этой сборки и запуска — +`s21-custody-build-validated.log` и `s21-custody-ctest-validated.log`. diff --git a/tests/replay_diagnostics.hpp b/tests/replay_diagnostics.hpp index 326f624..fd8863d 100644 --- a/tests/replay_diagnostics.hpp +++ b/tests/replay_diagnostics.hpp @@ -20,7 +20,7 @@ struct Context { inline std::string canonical(const World& world) { std::ostringstream stream(std::ios::binary); - world.write_save(stream, WorldSaveFormat::Current14); + world.write_save(stream, WorldSaveFormat::Current15); return stream.str(); } @@ -29,6 +29,7 @@ template std::string value(T item) { else return std::to_string(item); } inline std::string value(GridPosition p) { return "(" + value(p.x) + "," + value(p.y) + ")"; } +inline std::string value(StockOwner owner) { return value(owner.kind) + ":" + value(owner.id); } inline std::string value(const std::vector& route) { std::string text = "["; for (auto p : route) text += value(p) + ","; @@ -37,11 +38,13 @@ inline std::string value(const std::vector& route) { // Diagnostic projection of public domain objects, never a save parser or an // alternate equality oracle. Unknown/private fields retain the byte fallback. -using Facts = std::map; +// Prefer visible stock/job changes, then durable identities, retained results +// and accounting. A secondary balance change must not hide the changed stock. +using Facts = std::map, std::string>; inline Facts facts(const World& world) { Facts out; - const auto put = [&](const std::string& owner, const char* field, const auto& item) { - out[owner + " field=" + field] = value(item); + const auto put = [&](const std::string& owner, const char* field, const auto& item, unsigned priority = 0) { + out[{priority, owner + " field=" + field}] = value(item); }; for (const auto& a : world.agents()) { const auto key = "agent id=" + value(a.id); @@ -52,9 +55,35 @@ inline Facts facts(const World& world) { AGENT_FIELD(production_id); AGENT_FIELD(hunger); AGENT_FIELD(fatigue); AGENT_FIELD(resting_on_ground); AGENT_FIELD(profession); #undef AGENT_FIELD + put(key, "next_admission", a.next_admission, 1); + put(key, "transfer_id", a.execution ? a.execution->id : 0, 1); for (std::size_t item = 1; item <= item_type_count; ++item) { - put("stock owner=agent:" + value(a.id) + " item=" + value(item), "count", + const auto stock = "stock owner=agent:" + value(a.id) + " item=" + value(item); + put(stock, "count", a.inventory.item_count(static_cast(item))); + put(stock, "stack_id", a.inventory.stack_id(static_cast(item)), 1); + } + if (a.execution) { + const auto& transfer = *a.execution; + const auto transfer_key = "transfer id=" + value(transfer.id) + " owner=agent:" + value(a.id); + put(transfer_key, "kind", transfer.kind, 1); + put(transfer_key, "production", transfer.production, 1); + put(transfer_key, "source", transfer.source, 1); + put(transfer_key, "destination", transfer.destination, 1); + put(transfer_key, "next_operation", transfer.next_operation, 1); + put(transfer_key, "blocked", transfer.blocked, 1); + put(transfer_key, "reservation_count", transfer.reservation_count, 1); + for (const auto& claim : transfer.reservations) { + if (!claim.id) continue; + const auto claim_key = "reservation id=" + value(claim.id) + " transfer=" + value(transfer.id); + put(claim_key, "kind", claim.kind, 1); + put(claim_key, "owner", claim.owner, 1); + put(claim_key, "stack_id", claim.stack, 1); + put(claim_key, "item", claim.item, 1); + put(claim_key, "count", claim.count, 1); + put(claim_key, "backing", claim.backing, 1); + put(claim_key, "origin_storage", claim.origin_storage, 1); + } } } for (const auto& j : world.jobs()) { @@ -67,6 +96,12 @@ inline Facts facts(const World& world) { put(key, "position", p.position); put(key, "recipe", p.recipe); put(key, "state", p.state); put(key, "collected_stops", p.collected_stops); put(key, "bed_owner", p.bed_owner); put(key, "bed_base", p.bed_base); put(key, "bed_stage", p.bed_stage); + put(key, "suspended", p.suspended, 1); + for (std::size_t item = 1; item <= item_type_count; ++item) { + const auto stock = "stock owner=production:" + value(p.id) + " item=" + value(item); + put(stock, "count", p.input.item_count(static_cast(item))); + put(stock, "stack_id", p.input.stack_id(static_cast(item)), 1); + } for (const auto& m : p.materials) { put(key + " material owner=storage:" + value(m.storage_id) + " item=" + value(m.type), "count", m.count); @@ -84,8 +119,56 @@ inline Facts facts(const World& world) { for (const auto& stack : s.items) { const auto stock = "stock owner=storage:" + value(s.id) + " item=" + value(stack.type); put(stock, "count", stack.count); put(stock, "reserved", stack.reserved); + put(stock, "stack_id", stack.id, 1); } } + // Keys identify logical results independently of the ring's backing slots. + for (const auto& receipt : world.custody_receipts()) { + const auto& request = receipt->request; + const auto& result = receipt->result; + const auto key = "custody receipt kind=" + value(request.key.kind) + " id=" + value(request.key.id) + + " ordinal=" + value(request.key.ordinal); + put(key, "operation", request.operation, 2); + put(key, "kind", request.kind, 2); + put(key, "production", request.production, 2); + put(key, "source", request.source, 2); + put(key, "destination", request.destination, 2); + put(key, "line_count", request.line_count, 2); + for (std::size_t i = 0; i < request.line_count; ++i) { + const auto line_key = key + " line=" + value(i); + put(line_key, "storage", request.lines[i].storage, 2); + put(line_key, "item", request.lines[i].item, 2); + put(line_key, "count", request.lines[i].count, 2); + } + put(key, "status", result.status, 2); + put(key, "transfer_id", result.transfer, 2); + put(key, "terminal", result.terminal, 2); + put(key, "reservation_count", result.reservation_count, 2); + put(key, "effect_count", result.effect_count, 2); + for (std::size_t i = 0; i < result.reservation_count; ++i) { + put(key + " reservation=" + value(i), "id", result.reservations[i], 2); + } + for (std::size_t i = 0; i < result.effect_count; ++i) { + const auto effect_key = key + " effect=" + value(i); + const auto& effect = result.effects[i]; + put(effect_key, "owner", effect.owner, 2); + put(effect_key, "stack_id", effect.stack, 2); + put(effect_key, "item", effect.item, 2); + put(effect_key, "count", effect.count, 2); + } + } + for (std::size_t item = 1; item <= item_type_count; ++item) { + const auto key = "balance item=" + value(item); + const auto& balance = world.item_balances()[item - 1]; + put(key, "opening", balance.opening, 3); + put(key, "grant", balance.grant, 3); + put(key, "harvest", balance.harvest, 3); + put(key, "recipe_output", balance.recipe_output, 3); + put(key, "recipe_input", balance.recipe_input, 3); + put(key, "meal", balance.meal, 3); + put(key, "installation", balance.installation, 3); + put(key, "demolition", balance.demolition, 3); + } for (std::uint8_t player = 1; player <= colony_player_slots; ++player) { put("command player=" + value(player), "next_sequence", world.next_command_sequence(player)); } @@ -105,13 +188,13 @@ inline std::string difference(const World& expected, const World& actual, const auto ai = a.begin(), bi = b.begin(); while (ai != a.end() || bi != b.end()) { if (bi == b.end() || (ai != a.end() && ai->first < bi->first)) { - return context(expected, c) + ai->first + " expected=" + ai->second + " actual="; + return context(expected, c) + ai->first.second + " expected=" + ai->second + " actual="; } if (ai == a.end() || bi->first < ai->first) { - return context(expected, c) + bi->first + " expected= actual=" + bi->second; + return context(expected, c) + bi->first.second + " expected= actual=" + bi->second; } if (ai->second != bi->second) { - return context(expected, c) + ai->first + " expected=" + ai->second + " actual=" + bi->second; + return context(expected, c) + ai->first.second + " expected=" + ai->second + " actual=" + bi->second; } ++ai; ++bi; } diff --git a/tests/replay_tests.cpp b/tests/replay_tests.cpp index 1deea2d..2252f6a 100644 --- a/tests/replay_tests.cpp +++ b/tests/replay_tests.cpp @@ -1,4 +1,5 @@ #include "settlement/core/world.hpp" +#include "settlement/core/checkpoint.hpp" #include "replay_diagnostics.hpp" #include @@ -44,9 +45,7 @@ void require(bool condition, std::string_view message) { } std::string saved_state(const World& world) { - std::ostringstream stream(std::ios::binary); - world.write_save(stream, WorldSaveFormat::Current14); - return stream.str(); + return replay_diagnostics::canonical(world); } std::unique_ptr load_state(const std::string& bytes, ExecutionConfig config, @@ -128,6 +127,8 @@ private: struct [[= Void::Testing::name("ReplayTests")]] ReplayTests : Void::Testing::Suite { [[= Void::Testing::tag("replay")]] Test test_opposite_real_completion_orders(); [[= Void::Testing::tag("replay")]] Test test_semantic_divergence_diagnostics(); + [[= Void::Testing::tag("replay")]] Test test_modern_custody_exposes_legacy_projection_blindness(); + [[= Void::Testing::tag("replay")]] Test test_cancelled_partial_cargo_checkpoint_replay(); [[= Void::Testing::tag("replay")]] Test test_execution_configuration_and_empty_world(); [[= Void::Testing::tag("replay")]] Test test_one_resident_completes_work(); [[= Void::Testing::tag("replay")]] Test test_competing_jobs_retry_unreachable_routes(); @@ -294,6 +295,137 @@ Test ReplayTests::test_semantic_divergence_diagnostics() { "unprojected canonical field lost byte fallback"); } +Test ReplayTests::test_modern_custody_exposes_legacy_projection_blindness() { + const auto legacy = [](const World& world) { + std::ostringstream stream(std::ios::binary); + world.write_save(stream, WorldSaveFormat::Current14); + return stream.str(); + }; + const replay_diagnostics::Context context{2, 1, "custody", "legacy-import", 4096}; + World stock(107, 12, 12, 1, ExecutionMode::SerialReference); + const auto storage = stock.add_storage({2, 2}, 10); + // Issued identities follow grants, while historical migration reconstructs + // them from the canonically sorted item rows. + stock.stock_storage(storage, ItemType::StoneBlock, 2); + stock.stock_storage(storage, ItemType::Plank, 3); + auto imported = load_state(legacy(stock), execution_configs.front()); + require(legacy(stock) == legacy(*imported), "legacy stock projection changed on import"); + auto report = replay_diagnostics::difference(stock, *imported, context); + require(report.find("stock owner=storage:" + std::to_string(storage)) != std::string::npos && + report.find("field=stack_id expected=2 actual=1") != std::string::npos, + "modern comparison missed reconstructed stack identity: " + report); + std::cout << report << '\n'; + + World accounting(108, 12, 12, 1, ExecutionMode::SerialReference); + const auto store = accounting.add_storage({2, 2}, 10); + accounting.stock_storage(store, ItemType::Wood, 2); + imported = load_state(legacy(accounting), execution_configs.front()); + require(legacy(accounting) == legacy(*imported), "legacy accounting projection changed on import"); + report = replay_diagnostics::difference(accounting, *imported, context); + require(report.find("balance item=1 field=grant expected=2 actual=0") != std::string::npos, + "modern comparison missed opening/grant distinction: " + report); + + World active(109, 32, 32, 1, ExecutionMode::SerialReference); + const auto materials = active.add_storage({3, 3}, 5); + active.stock_storage(materials, ItemType::Plank, 3); + active.stock_storage(materials, ItemType::StoneBlock, 2); + static_cast(active.spawn_agent({1, 3})); + active.queue_production({16, 3}, RecipeId::BuildCabin); + active.step(); + imported = load_state(legacy(active), execution_configs.front()); + require(legacy(active) == legacy(*imported), "legacy active projection changed on import"); + require(!active.custody_receipts().empty() && imported->custody_receipts().empty(), + "fixture did not distinguish real and reconstructed history"); + report = replay_diagnostics::difference(active, *imported, context); + require(report.find("custody receipt kind=0 id=1 ordinal=1") != std::string::npos && + report.find("actual=") != std::string::npos, + "modern comparison missed retained admission result: " + report); + std::cout << report << '\n'; + const auto facts = replay_diagnostics::facts(active); + const auto& transfer = *active.agents().front().execution; + const auto& reservation = transfer.reservations.front(); + require(facts.at({1, "transfer id=" + std::to_string(transfer.id) + " owner=agent:1 field=next_operation"}) == "1" && + facts.at({1, "reservation id=" + std::to_string(reservation.id) + " transfer=" + + std::to_string(transfer.id) + " field=stack_id"}) == std::to_string(reservation.stack), + "active transfer/reservation diagnostics lost durable identities"); +} + +Test ReplayTests::test_cancelled_partial_cargo_checkpoint_replay() { + World reference(113, 32, 32, 1, ExecutionMode::SerialReference); + const auto source = reference.add_storage({3, 3}, 5); + reference.stock_storage(source, ItemType::Plank, 3); + reference.stock_storage(source, ItemType::StoneBlock, 2); + static_cast(reference.spawn_agent({1, 3})); + reference.queue_production({16, 3}, RecipeId::BuildCabin); + const auto order = reference.production_orders().front().id; + for (int tick = 0; tick < 30 && reference.agents().front().state != AgentState::Working; ++tick) reference.step(); + require(reference.agents().front().state == AgentState::Working, "cabin delivery did not reach the site"); + const auto transfer = reference.agents().front().execution->id; + require(reference.cancel_production(order) == CommandStatus::Accepted, "live construction cancellation failed"); + reference.stock_storage(source, ItemType::Wood, 5); + const auto partial = reference.add_storage({4, 3}, 1); + for (int tick = 0; tick < 40; ++tick) reference.step(); + const auto& actor = reference.agents().front(); + require(actor.state == AgentState::Returning && actor.execution && actor.execution->id == transfer && + actor.execution->blocked == CustodyStatus::NoDestination && + actor.inventory.item_count(ItemType::Plank) == 2 && actor.inventory.item_count(ItemType::StoneBlock) == 2 && + reference.find_storage(partial)->item_count(ItemType::Plank) == 1, + "partial return did not retain the same transfer and remaining cargo"); + + const auto admission = *reference.custody_receipts().front(); + const auto cancelled = std::find_if(reference.custody_receipts().begin(), reference.custody_receipts().end(), + [](const auto& receipt) { return receipt->request.operation == CustodyOperation::Cancel; }); + require(cancelled != reference.custody_receipts().end(), "cancel result was not retained"); + const std::array retained{admission, **cancelled}; + Void::Uuid::Uuid world_id; + world_id.bytes.back() = 113; + const auto rules = default_rules_manifest(); + const auto catalog = builtin_rule_packages(); + require(rules.has_value() && catalog.has_value(), "default rules unavailable"); + const auto checkpoint = encode_checkpoint(reference, world_id, 7, *rules); + require(checkpoint.has_value(), "partial cargo checkpoint failed"); + std::vector> candidates; + for (const auto config : execution_configs) { + auto loaded = decode_checkpoint(*checkpoint, *catalog, config.workers, config.mode); + require(loaded.has_value(), "partial cargo checkpoint was not decoded"); + require(loaded->world_id == world_id && loaded->city == 7, "checkpoint identity changed"); + const auto repeated = encode_checkpoint(*loaded->world, loaded->world_id, loaded->city, loaded->rules); + require(repeated.has_value() && *repeated == *checkpoint, "partial checkpoint roundtrip changed bytes"); + candidates.push_back(std::move(loaded->world)); + } + const auto repeat_without_effect = [&](World& world) { + const auto before = saved_state(world); + for (const auto& receipt : retained) { + require(world.custody_request(receipt.request) == receipt.result, "retained result changed after reload"); + auto conflict = receipt.request; + ++conflict.destination; + require(world.custody_request(conflict).status == CustodyStatus::Conflict, + "changed payload reused an accepted transfer step"); + } + require(saved_state(world) == before, "retry repeated a physical transfer or consumed an ordinal"); + }; + repeat_without_effect(reference); + for (auto& world : candidates) repeat_without_effect(*world); + for (std::uint64_t attempt = 0; attempt < 40; ++attempt) { + if (attempt == 5) { + static_cast(reference.add_storage({6, 3}, 20)); + for (auto& world : candidates) static_cast(world->add_storage({6, 3}, 20)); + } + reference.step(); + for (std::size_t i = 0; i < candidates.size(); ++i) { + candidates[i]->step(); + const auto report = replay_diagnostics::difference(reference, *candidates[i], + {attempt, execution_configs[i].workers, "cancel-return", "checkpoint", 4096}); + require(report.empty(), report); + repeat_without_effect(*candidates[i]); + } + } + require(reference.agents().front().inventory.empty() && !reference.agents().front().execution && + reference.item_balances()[2].installation == 0 && reference.item_balances()[3].installation == 0, + "return duplicated consumption or retained finished cargo"); + repeat_without_effect(reference); +} + Test ReplayTests::test_execution_configuration_and_empty_world() { World initial(20261202, 5, 5); const auto bytes = saved_state(initial); diff --git a/tests/runtime_tests.cpp b/tests/runtime_tests.cpp index 5059ab9..22baa51 100644 --- a/tests/runtime_tests.cpp +++ b/tests/runtime_tests.cpp @@ -21,9 +21,7 @@ constexpr TrustedClient host{1}; constexpr TrustedClient guest{2}; std::string bytes(const World& world) { - std::ostringstream stream(std::ios::binary); - world.write_save(stream); - return stream.str(); + return replay_diagnostics::canonical(world); } WorldCheckpoint colony(std::size_t workers = 2, WorkerPoolOptions options = {}) {