Transfer reserved meal and construction pickups as one checked operation
This commit is contained in:
1 parent
a8cd7bb415
commit
3c997ed236
7 files changed
+595
-11
No files matched your search
@@ -44,6 +44,7 @@ add_library(settlement_core
|
||||
engine/src/colony_profile.cpp
|
||||
engine/src/command_dispatcher.cpp
|
||||
engine/src/first_colony.cpp
|
||||
engine/src/inventory_transaction.cpp
|
||||
engine/src/rules_manifest.cpp
|
||||
engine/src/save_service_win32.cpp
|
||||
engine/src/simulation_runtime.cpp
|
||||
@@ -120,6 +121,7 @@ if(BUILD_TESTING)
|
||||
tests/identity_tests.cpp
|
||||
tests/production_identity_tests.cpp
|
||||
tests/profile_tests.cpp
|
||||
tests/quantity_transaction_tests.cpp
|
||||
tests/replay_tests.cpp
|
||||
tests/rules_tests.cpp
|
||||
tests/runtime_tests.cpp
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# Apply a complete reserved pickup to one resident atomically
|
||||
|
||||
Task ID: S06-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated system/s06-logistics worktree s06 at a8cd7bb (S04 ProductionId/current14, S19 selectable rules, S06 stable StorageId). Meals and construction stops call take_reserved_material then Inventory::add, and a carpentry output reserves a new storage slot at its first ingredient pickup. Earlier M01-P5/F7 require whole-stop preflight. Existing finish_production also calls take_reserved_material for direct storage→recipe consumption, a different operation.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement checked all-or-nothing physical pickup in both real meal and construction stop paths, including a carpentry output slot when applicable. Retain normal simulation bytes/timing. Cover overflows, split duplicate material entries and late failure before mutation.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
No save version, StackId, worksite ownership, reservation ID, journal, general-purpose database or protocol change in this slice. Keep existing direct recipe consumption in finish_production. Stage only future work in appropriate system notes.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read engine/include/settlement/core/world.hpp Inventory/Storage/ItemStack/MaterialReservation, engine/src/world.cpp named consumers, world_save.cpp validation/legacy split records, tests identity/production_identity/core/replay, and S06 documentation/linked Void #8. Consult pin include/Void/Math/Numeric.hpp checked_add/sub. Root baseline cumulative a8cd7bb.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/src/world.cpp (narrow meal/construction stop pickup and related local helper); NEW engine/include/settlement/core/inventory_transaction.hpp and engine/src/inventory_transaction.cpp if needed for a shared testable operation; NEW tests/quantity_transaction_tests.cpp; CMakeLists.txt only source and test entries; docs/plan/systems/S06.md
|
||||
Exclusive to your isolated s06 worktree. Others work in sibling worktrees. Do not revert others' changes or edit unrelated methods/world_save/UI or shared Serena state. Root owns Git and remote.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Use one bounded operation over a single Storage and resident Inventory, evaluating present source/reserved counts, aggregate duplicate participating lines per type, and checked destination increments. If using the whole order span, choose only lines at the current storage; a missing/zero/invalid selection fails. Reject invalid types/None, zero amount, overflows, insufficient reserved or count and reserved>physical. Preserve source stack order, prune zero stacks without allocation; prevent throws between first and last logical writes. Use the existing checked Numeric API. For carpentry precompute reserved_slots successor and ensure post-withdrawal total_items+reserved_slots<=capacity before any quantity write; move commit/route/cursor only after success. No per-line mutating call before complete preflight. Failures observed by the owner must preserve last healthy publication. Avoid needless repeated lookup/allocations.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Prefer one simple domain function returning std::expected<void,typed quantity diagnostic>; exact type and header naming locally flexible. Application entry precondition is pickup-function entry: World::step may already advance walking position/route_cursor earlier in the tick. On pickup rejection, no additional stop, inventory, reserved slots/stock, route replacement or state transition; never publish partial transfer. Cover zero/foreign-only or out-of-range data; existing legitimate repeated material entries aggregate. Raw13/LAN11 layout stays byte exact and modern Current14 shape stays the same.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns merging this branch to milestone/integration and cross-branch checks. P5 future durable IDs and reservations will consume this operation. S04-01 and S19-02 are already present; S18 UI can proceed independently.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Data bounds as provided by old loader; max distinct types item_type_count, avoid allocating proportional to a user-provided count. Do not wrap at uint32 max on destination, source/slot arithmetic or sum. Source storage count/metadata may be inconsistent on direct test input; fail safely. No total mutable parallel ledger. Minimize impact on World::step hot path.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Source/dest byte-equivalent on success for valid meal and multi-material/multistop/carpentry paths, tested from production code. 2. A two-item stop late failure plus cumulative duplicate and destination overflow leaves all stock/reserved/capacity/inventory unchanged. 3. Successful exact depletion removes zero stack, respects source order and reserve slot. 4. Replay serial/2/6/12 modern checks and both old byte corpora unchanged. 5. Document limits separately from future custody and link Void #8 replacement.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/quantity-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 <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Use --tag quantity-transfer on new tests, CTest -V, git diff --check; /tmp/stoneheart-milestones.xprJ2SVp/old-trajectory.bin and identity-compat-old.bin old golden outputs were checked by s04 (portable projection probe sources in same directory). Keep verification logs quantity-* in that temp root.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not fake output inventories for finish_production or weaken legacy validity, add unrelated changes or use unbounded copies. Alert root if actual code contradicts the contract. Root owns commit/push/MRs/upstream issues. After two failed same-cause repairs escalate; no children.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Approved M01 item conservation and per-system development. F7 corrective terms are included above. Conditional batch issue Void/Library #8 already registered; parent owns external tracking.
|
||||
|
||||
## 14. Return format
|
||||
Return S06-02 READY or PARTIAL, owned files, exact tradeoffs/failure boundary, actual tests/golden output, any native and deferred full-custody limitations. No Git/remote operations.
|
||||
|
||||
F7 corrections are binding. Item indices are checked against 1..item_type_count before using type−1. Aggregate nonadjacent duplicate lines, handle an absent stack, and preserve the original first material's storage as the output source even when it is visited after another stop. No stale iterators may survive zero-stack removal. Include valid exact UINT32_MAX destination count, multiple erasures with unrelated surviving stacks, full storage freeing exactly one carpentry output slot, invalid slot/capacity state rejected before physical transfer, and direct storage→output production compatibility.
|
||||
@@ -66,6 +66,14 @@ S06 владеет фактическими количествами, содер
|
||||
|
||||
Семь проверок `--tag identity` под Wine покрывают удаление более ранних объектов при переноске, доставку с двух складов, кладовую, засев без склада, готовую продукцию плотника, границы счётчиков и недопустимые старые ссылки. Загруженные копии продолжают совпадать потактно в последовательном режиме и на 2/6/12 потоках, включая контрольную точку с правилами и удерживаемый снимок. Постоянные ID производственных заказов, стеков, резервов и передач входят в последующие срезы. Для общего резервирования и переноса количеств зарегистрирован [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8). [Исполняемые проверки](../../../tests/identity_tests.cpp)
|
||||
|
||||
Срез S06-02 переводит физическое получение еды и материалов одной остановки на `withdraw_reserved_materials`. Операция объединяет все строки текущего склада по типу, включая несмежные повторы; строки остальных остановок не участвуют. До первого изменения проверяются ненулевой ID склада, выбранные типы и положительные количества, существование отсортированных уникальных стеков, `reserved <= count`, достаточность резерва, вместимость и проверяемые суммы источника и личного инвентаря. Счётчик назначения может достичь ровно `UINT32_MAX`. Фиксированные массивы ограничены числом типов; получение не выделяет память, удаление нескольких опустевших стеков сохраняет порядок остальных. [Контракт операции](../../../engine/include/settlement/core/inventory_transaction.hpp) · [Реализация](../../../engine/src/inventory_transaction.cpp)
|
||||
|
||||
Плотник в той же операции резервирует место для результата на складе **первого ингредиента**, даже если этот склад посещается позже другой остановки. Проверка учитывает освобождающееся место; полный склад может обменять последнюю единицу сырья на одно зарезервированное место. При отказе не меняются количества, резерв места, остановка, маршрут и состояние жителя относительно входа в получение. Перед ним `World::step` уже мог продвинуть движение или потребности. Ошибка нарушенного предусловия поднимается владельцу симуляции; runtime сохраняет последнюю здоровую публикацию и блокирует сохранение повреждённого кандидата. Прямое преобразование сырья в продукт в `finish_production` остаётся отдельной операцией и не получает гарантию атомарного преобразования рецепта. Форматы 13, LAN 11 и Current14 не меняются. [Вызовы получения](../../../engine/src/world.cpp) · [Проверки `quantity-transfer`](../../../tests/quantity_transaction_tests.cpp)
|
||||
|
||||
В закреплённом Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` используется платформенно независимая `Void::Numeric::checked_add/checked_sub`; `Storage::Batch` относится к ключам движка хранения и не меняет игровые структуры в памяти. Локальный перенос связан с [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8). Условие замены — повторить проверки позднего отказа всего набора, несмежных повторов, пределов арифметики, полного склада плотника и реальных еды/доставки/публикации на Windows x64, затем сравнить продолжения и старые байтовые эталоны. Этот срез не вводит ID стеков, резервов и передач, журнал или идемпотентность: повторное получение отсеивает существующий курсор остановки, а долговременный учёт владельца груза остаётся будущей работой S06-A/S04.
|
||||
|
||||
Проверка S06-02: сборка GCC 16.2 Windows x64 Release и запуск под Wine; 14/14 проверок `quantity-transfer`, полный CTest — 136/136 core и 9/9 LAN, включая современные сохранения и повтор на 1/2/6/12 исполнителях. Оба старых байтовых корпуса (`old-trajectory.bin`, `identity-compat-old.bin`) совпали с проекцией формата 13 на всех четырёх режимах. Нативный запуск Windows и MSVC отдельно не проверялись.
|
||||
|
||||
Применять существующие подходящие средства контейнеров, проверяемой арифметики, сериализации и результатов из [VoidLibrary](../void-library.md). Для отсутствующей возможности перед локальной реализацией найти либо создать issue в `Void/Library` и указать ссылку в задаче и коде.
|
||||
|
||||
- Два заказа запрашивают последнюю единицу ресурса. Только один получает резерв, свободный запас остаётся неотрицательным.
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <expected>
|
||||
#include <span>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
enum class QuantityTransferError {
|
||||
InvalidStorage,
|
||||
InvalidMaterial,
|
||||
MissingSelection,
|
||||
InvalidStock,
|
||||
InsufficientStock,
|
||||
Overflow,
|
||||
Capacity,
|
||||
};
|
||||
|
||||
// Pick up all lines for source.id; other delivery stops are left alone. Failure
|
||||
// leaves both owners unchanged. Optional output capacity is reserved in the same
|
||||
// commit, after accounting for the space freed by the pickup. No allocation.
|
||||
// This is one physical pickup, not an idempotent transfer or recipe conversion.
|
||||
[[nodiscard]] std::expected<void, QuantityTransferError> withdraw_reserved_materials(
|
||||
Storage& source, Inventory& destination, std::span<const MaterialReservation> materials,
|
||||
bool reserve_output_slot = false) noexcept;
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,88 @@
|
||||
#include "settlement/core/inventory_transaction.hpp"
|
||||
|
||||
#include <Void/Math/Numeric.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <type_traits>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
// Replace the conditional in-memory batch when Void/Library #8 supplies this
|
||||
// contract: https://git.faumaray.com/Void/Library/issues/8
|
||||
std::expected<void, QuantityTransferError> withdraw_reserved_materials(
|
||||
Storage& source, Inventory& destination, std::span<const MaterialReservation> materials,
|
||||
bool reserve_output_slot) noexcept {
|
||||
using Error = QuantityTransferError;
|
||||
if (source.id == 0 || source.kind > StorageKind::Pantry) return std::unexpected(Error::InvalidStorage);
|
||||
|
||||
std::array<std::uint32_t, item_type_count> amounts{};
|
||||
bool selected = false;
|
||||
std::uint64_t withdrawn = 0;
|
||||
for (const auto& material : materials) {
|
||||
if (material.storage_id != source.id) continue;
|
||||
const auto type = static_cast<std::size_t>(material.type);
|
||||
if (type == 0 || type > item_type_count || material.count == 0) {
|
||||
return std::unexpected(Error::InvalidMaterial);
|
||||
}
|
||||
const auto amount = Void::Numeric::checked_add(amounts[type - 1], material.count);
|
||||
const auto total = Void::Numeric::checked_add(withdrawn, std::uint64_t{material.count});
|
||||
if (!amount || !total) return std::unexpected(Error::Overflow);
|
||||
amounts[type - 1] = *amount;
|
||||
withdrawn = *total;
|
||||
selected = true;
|
||||
}
|
||||
if (!selected) return std::unexpected(Error::MissingSelection);
|
||||
|
||||
// Validate the entire source before indexing or changing any stack. Its
|
||||
// sorted unique representation bounds all subsequent work by item_type_count.
|
||||
auto previous = ItemType::None;
|
||||
std::uint64_t total_items = 0;
|
||||
std::array<bool, item_type_count> present{};
|
||||
for (const auto& stack : source.items) {
|
||||
const auto type = static_cast<std::size_t>(stack.type);
|
||||
if (type == 0 || type > item_type_count || stack.type <= previous ||
|
||||
!source.accepts(stack.type) || stack.count == 0 || stack.reserved > stack.count) {
|
||||
return std::unexpected(Error::InvalidStock);
|
||||
}
|
||||
previous = stack.type;
|
||||
present[type - 1] = true;
|
||||
const auto total = Void::Numeric::checked_add(total_items, std::uint64_t{stack.count});
|
||||
if (!total) return std::unexpected(Error::Overflow);
|
||||
total_items = *total;
|
||||
if (amounts[type - 1] > stack.reserved || amounts[type - 1] > stack.count) {
|
||||
return std::unexpected(Error::InsufficientStock);
|
||||
}
|
||||
}
|
||||
for (std::size_t i = 0; i < amounts.size(); ++i) {
|
||||
if (amounts[i] == 0) continue;
|
||||
if (!present[i]) return std::unexpected(Error::InsufficientStock);
|
||||
if (!Void::Numeric::checked_add(destination.item_count(static_cast<ItemType>(i + 1)), amounts[i])) {
|
||||
return std::unexpected(Error::Overflow);
|
||||
}
|
||||
}
|
||||
|
||||
const auto occupied = Void::Numeric::checked_add(total_items, std::uint64_t{source.reserved_slots});
|
||||
if (!occupied || source.capacity == 0 || *occupied > source.capacity) return std::unexpected(Error::Capacity);
|
||||
const auto slots = Void::Numeric::checked_add(source.reserved_slots, std::uint32_t{reserve_output_slot});
|
||||
if (!slots) return std::unexpected(Error::Overflow);
|
||||
const auto remaining = Void::Numeric::checked_sub(total_items, withdrawn);
|
||||
if (!remaining) return std::unexpected(Error::InsufficientStock);
|
||||
const auto final_occupied = Void::Numeric::checked_add(*remaining, std::uint64_t{*slots});
|
||||
if (!final_occupied || *final_occupied > source.capacity) return std::unexpected(Error::Capacity);
|
||||
|
||||
// All operations after this point are nonthrowing. No stack iterator survives
|
||||
// compaction, which removes every depleted stack while retaining source order.
|
||||
static_assert(std::is_nothrow_move_assignable_v<ItemStack> && std::is_nothrow_destructible_v<ItemStack>);
|
||||
for (auto& stack : source.items) {
|
||||
const auto amount = amounts[static_cast<std::size_t>(stack.type) - 1];
|
||||
stack.count -= amount;
|
||||
stack.reserved -= amount;
|
||||
if (amount != 0) destination.add(stack.type, amount);
|
||||
}
|
||||
std::erase_if(source.items, [](const ItemStack& stack) noexcept { return stack.count == 0; });
|
||||
source.reserved_slots = *slots;
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace settlement
|
||||
+12
-11
@@ -1,4 +1,5 @@
|
||||
#include "settlement/core/world.hpp"
|
||||
#include "settlement/core/inventory_transaction.hpp"
|
||||
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Math/Numeric.hpp>
|
||||
@@ -1511,8 +1512,10 @@ void World::assign_meals() {
|
||||
void World::finish_meal_step(Agent& agent) {
|
||||
if (agent.state == AgentState::GoingToEat) {
|
||||
if (agent.route_cursor != agent.route.size()) return;
|
||||
take_reserved_material(storage_by_id(agent.storage_id), {agent.storage_id, ItemType::Berries, 1});
|
||||
agent.inventory.add(ItemType::Berries);
|
||||
const std::array meal{MaterialReservation{agent.storage_id, ItemType::Berries, 1}};
|
||||
if (!withdraw_reserved_materials(storage_by_id(agent.storage_id), agent.inventory, meal)) {
|
||||
throw std::logic_error("invalid reserved meal pickup");
|
||||
}
|
||||
agent.storage_id = 0;
|
||||
agent.route.clear();
|
||||
agent.route_cursor = 0;
|
||||
@@ -1593,16 +1596,14 @@ void World::advance_construction_delivery(Agent& agent) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto& stop = order.delivery_stops[order.collected_stops];
|
||||
for (const auto& material : order.materials) {
|
||||
if (material.storage_id == stop.storage_id) {
|
||||
take_reserved_material(storage_by_id(stop.storage_id), material);
|
||||
agent.inventory.add(material.type, material.count);
|
||||
}
|
||||
if (order.collected_stops > order.delivery_stops.size() || order.materials.empty()) {
|
||||
throw std::logic_error("invalid construction pickup stop");
|
||||
}
|
||||
if (is_carpentry_recipe(order.recipe) && stop.storage_id == order.materials.front().storage_id) {
|
||||
// Collecting the first ingredient frees a slot for the finished item.
|
||||
++storage_by_id(stop.storage_id).reserved_slots;
|
||||
auto& stop = order.delivery_stops[order.collected_stops];
|
||||
const bool reserve_output = is_carpentry_recipe(order.recipe) &&
|
||||
stop.storage_id == order.materials.front().storage_id;
|
||||
if (!withdraw_reserved_materials(storage_by_id(stop.storage_id), agent.inventory, order.materials, reserve_output)) {
|
||||
throw std::logic_error("invalid reserved construction pickup");
|
||||
}
|
||||
++order.collected_stops;
|
||||
agent.route = std::move(stop.route_to_next);
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
#include "settlement/core/inventory_transaction.hpp"
|
||||
#include "settlement/core/simulation_runtime.hpp"
|
||||
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
using namespace settlement;
|
||||
using Void::Testing::Test;
|
||||
constexpr auto maximum = std::numeric_limits<std::uint32_t>::max();
|
||||
|
||||
void require(bool condition, const char* message = "quantity transfer invariant failed") {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
Storage source() {
|
||||
return {7, {3, 3}, 20, 0, {{ItemType::Wood, 4, 3}, {ItemType::Stone, 3, 2}}};
|
||||
}
|
||||
|
||||
void same_inventory(const Inventory& actual, const Inventory& expected) {
|
||||
for (std::size_t i = 1; i <= item_type_count; ++i) {
|
||||
require(actual.item_count(static_cast<ItemType>(i)) == expected.item_count(static_cast<ItemType>(i)),
|
||||
"failed pickup changed destination");
|
||||
}
|
||||
}
|
||||
|
||||
void same_storage(const Storage& actual, const Storage& expected) {
|
||||
require(actual.id == expected.id && actual.position == expected.position && actual.capacity == expected.capacity &&
|
||||
actual.reserved_slots == expected.reserved_slots && actual.kind == expected.kind &&
|
||||
actual.items.size() == expected.items.size(), "failed pickup changed storage metadata");
|
||||
for (std::size_t i = 0; i < actual.items.size(); ++i) {
|
||||
require(actual.items[i].type == expected.items[i].type && actual.items[i].count == expected.items[i].count &&
|
||||
actual.items[i].reserved == expected.items[i].reserved, "failed pickup changed source quantities/order");
|
||||
}
|
||||
}
|
||||
|
||||
void rejected(Storage& storage, Inventory& inventory, std::span<const MaterialReservation> materials,
|
||||
QuantityTransferError error, bool slot = false) {
|
||||
const auto before = storage;
|
||||
const auto cargo = inventory;
|
||||
const auto result = withdraw_reserved_materials(storage, inventory, materials, slot);
|
||||
require(!result && result.error() == error, "pickup accepted bad input or returned the wrong diagnostic");
|
||||
same_storage(storage, before);
|
||||
same_inventory(inventory, cargo);
|
||||
}
|
||||
|
||||
std::string bytes(const World& world) {
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream, WorldSaveFormat::Current14);
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
void same_pickup_actor(const Agent& actual, const Agent& expected) {
|
||||
same_inventory(actual.inventory, expected.inventory);
|
||||
require(actual.position == expected.position && actual.route == expected.route &&
|
||||
actual.route_cursor == expected.route_cursor && actual.haul_route == expected.haul_route &&
|
||||
actual.state == expected.state && actual.storage_id == expected.storage_id &&
|
||||
actual.production_id == expected.production_id && actual.work_remaining == expected.work_remaining,
|
||||
"rejected pickup changed actor/route state");
|
||||
}
|
||||
|
||||
std::unique_ptr<World> cabin() {
|
||||
auto world = std::make_unique<World>(43, 32, 32, 1, ExecutionMode::SerialReference);
|
||||
const auto store = world->add_storage({3, 3}, 20);
|
||||
world->stock_storage(store, ItemType::Plank, 3);
|
||||
world->stock_storage(store, ItemType::StoneBlock, 2);
|
||||
static_cast<void>(world->spawn_agent({1, 3}));
|
||||
world->queue_production({14, 3}, RecipeId::BuildCabin);
|
||||
world->step();
|
||||
require(world->agents().front().state == AgentState::FetchingMaterials, "fixture already picked up materials");
|
||||
return world;
|
||||
}
|
||||
|
||||
// Test-only corruption uses public read views of a nonconst fixture. Production
|
||||
// code cannot create these malformed sources through the checked save loader.
|
||||
void at_pickup(World& world) {
|
||||
auto& agent = const_cast<Agent&>(world.agents().front());
|
||||
agent.position = world.storages().front().position;
|
||||
agent.route.clear();
|
||||
agent.route_cursor = 0;
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("QuantityTransactionTests")]] QuantityTransactionTests
|
||||
: Void::Testing::Suite<QuantityTransactionTests> {
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test late_failure_is_atomic();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test nonadjacent_duplicates_and_foreign_stops();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test invalid_selection_and_item_bounds();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test source_invariants_and_underflow();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test cumulative_and_destination_boundaries();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test stable_multiple_erasure_and_output_capacity();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test invalid_capacity_and_slot_overflow_are_atomic();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test real_construction_rejection_keeps_stop_actor_and_routes();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test real_split_lines_and_invalid_storage_selection();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test real_carpentry_invalid_capacity_keeps_pickup_untouched();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test real_meal_pickup_and_overflow_rejection();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test real_multistop_carpentry_reserves_first_ingredient_store();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test direct_crafting_stays_in_storage();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test owner_fault_preserves_last_healthy_publication();
|
||||
};
|
||||
|
||||
Test QuantityTransactionTests::late_failure_is_atomic() {
|
||||
auto storage = source();
|
||||
Inventory inventory;
|
||||
inventory.add(ItemType::Wood, 9);
|
||||
const std::array materials{MaterialReservation{7, ItemType::Wood, 2}, MaterialReservation{7, ItemType::Stone, 3}};
|
||||
rejected(storage, inventory, materials, QuantityTransferError::InsufficientStock);
|
||||
inventory.add(ItemType::Stone, maximum);
|
||||
auto valid = materials;
|
||||
valid[1].count = 1;
|
||||
rejected(storage, inventory, valid, QuantityTransferError::Overflow, true);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::nonadjacent_duplicates_and_foreign_stops() {
|
||||
auto storage = source();
|
||||
Inventory inventory;
|
||||
const std::array materials{MaterialReservation{7, ItemType::Wood, 1}, MaterialReservation{9, ItemType::Wood, 5},
|
||||
MaterialReservation{7, ItemType::Stone, 2}, MaterialReservation{7, ItemType::Wood, 2}};
|
||||
require(withdraw_reserved_materials(storage, inventory, materials).has_value());
|
||||
require(inventory.item_count(ItemType::Wood) == 3 && inventory.item_count(ItemType::Stone) == 2);
|
||||
require(storage.items[0].count == 1 && storage.items[0].reserved == 0 && storage.items[1].count == 1 &&
|
||||
storage.items[1].reserved == 0);
|
||||
auto insufficient = source();
|
||||
const std::array duplicates{MaterialReservation{7, ItemType::Wood, 2}, MaterialReservation{7, ItemType::Stone, 1},
|
||||
MaterialReservation{7, ItemType::Wood, 2}};
|
||||
rejected(insufficient, inventory, duplicates, QuantityTransferError::InsufficientStock);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::invalid_selection_and_item_bounds() {
|
||||
auto storage = source();
|
||||
Inventory inventory;
|
||||
const std::array valid{MaterialReservation{7, ItemType::Wood, 1}};
|
||||
rejected(storage, inventory, {}, QuantityTransferError::MissingSelection);
|
||||
const std::array foreign{MaterialReservation{8, ItemType::Wood, 1}};
|
||||
rejected(storage, inventory, foreign, QuantityTransferError::MissingSelection);
|
||||
const std::array zero_id{MaterialReservation{0, ItemType::Wood, 1}};
|
||||
rejected(storage, inventory, zero_id, QuantityTransferError::MissingSelection);
|
||||
for (const auto type : {ItemType::None, static_cast<ItemType>(item_type_count + 1), static_cast<ItemType>(255)}) {
|
||||
const std::array bad{MaterialReservation{7, type, 1}};
|
||||
rejected(storage, inventory, bad, QuantityTransferError::InvalidMaterial);
|
||||
}
|
||||
const std::array zero{MaterialReservation{7, ItemType::Wood, 0}};
|
||||
rejected(storage, inventory, zero, QuantityTransferError::InvalidMaterial);
|
||||
storage.id = 0;
|
||||
rejected(storage, inventory, zero_id, QuantityTransferError::InvalidStorage);
|
||||
storage = source();
|
||||
storage.kind = static_cast<StorageKind>(255);
|
||||
rejected(storage, inventory, valid, QuantityTransferError::InvalidStorage);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::source_invariants_and_underflow() {
|
||||
Inventory inventory;
|
||||
const std::array materials{MaterialReservation{7, ItemType::Wood, 1}};
|
||||
const std::array missing{MaterialReservation{7, ItemType::Plank, 1}};
|
||||
auto storage = source();
|
||||
rejected(storage, inventory, missing, QuantityTransferError::InsufficientStock);
|
||||
for (int fault = 0; fault < 8; ++fault) {
|
||||
storage = source();
|
||||
switch (fault) {
|
||||
case 0: storage.items[0].reserved = 5; break;
|
||||
case 1: storage.items[0].count = 0; break;
|
||||
case 2: storage.items[0].type = ItemType::None; break;
|
||||
case 3: storage.items[0].type = static_cast<ItemType>(item_type_count + 1); break;
|
||||
case 4: storage.items[1].type = ItemType::Wood; break;
|
||||
case 5: std::swap(storage.items[0], storage.items[1]); break;
|
||||
case 6: storage.kind = StorageKind::Pantry; break;
|
||||
case 7: storage.items[1].reserved = 4; break;
|
||||
}
|
||||
rejected(storage, inventory, materials, QuantityTransferError::InvalidStock);
|
||||
}
|
||||
storage = source();
|
||||
storage.items[0].reserved = 0;
|
||||
rejected(storage, inventory, materials, QuantityTransferError::InsufficientStock);
|
||||
storage.items[0].reserved = storage.items[0].count = 1;
|
||||
const std::array too_many{MaterialReservation{7, ItemType::Wood, 2}};
|
||||
rejected(storage, inventory, too_many, QuantityTransferError::InsufficientStock);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::cumulative_and_destination_boundaries() {
|
||||
Storage storage{7, {}, maximum, 0, {{ItemType::Wood, maximum, maximum}}};
|
||||
Inventory inventory;
|
||||
const std::array overflow{MaterialReservation{7, ItemType::Wood, maximum},
|
||||
MaterialReservation{8, ItemType::Stone, 1}, MaterialReservation{7, ItemType::Wood, 1}};
|
||||
rejected(storage, inventory, overflow, QuantityTransferError::Overflow);
|
||||
const std::array exact{MaterialReservation{7, ItemType::Wood, maximum - 1}, MaterialReservation{7, ItemType::Wood, 1}};
|
||||
require(withdraw_reserved_materials(storage, inventory, exact).has_value());
|
||||
require(storage.items.empty() && inventory.item_count(ItemType::Wood) == maximum);
|
||||
storage = source();
|
||||
const std::array one{MaterialReservation{7, ItemType::Wood, 1}};
|
||||
rejected(storage, inventory, one, QuantityTransferError::Overflow);
|
||||
Inventory boundary;
|
||||
boundary.add(ItemType::Wood, maximum - 1);
|
||||
require(withdraw_reserved_materials(storage, boundary, one).has_value());
|
||||
require(boundary.item_count(ItemType::Wood) == maximum);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::stable_multiple_erasure_and_output_capacity() {
|
||||
Storage storage{7, {}, 10, 0, {{ItemType::Wood, 2, 2}, {ItemType::Stone, 3, 1},
|
||||
{ItemType::Plank, 1, 1}, {ItemType::StoneBlock, 4, 0}}};
|
||||
Inventory inventory;
|
||||
const std::array materials{MaterialReservation{7, ItemType::Plank, 1}, MaterialReservation{7, ItemType::Wood, 2}};
|
||||
require(withdraw_reserved_materials(storage, inventory, materials, true).has_value());
|
||||
require(storage.reserved_slots == 1 && storage.items.size() == 2 &&
|
||||
storage.items[0].type == ItemType::Stone && storage.items[0].count == 3 && storage.items[0].reserved == 1 &&
|
||||
storage.items[1].type == ItemType::StoneBlock && storage.items[1].count == 4 && storage.items[1].reserved == 0);
|
||||
Storage full{7, {}, 1, 0, {{ItemType::Wood, 1, 1}}};
|
||||
const std::array one{MaterialReservation{7, ItemType::Wood, 1}};
|
||||
require(withdraw_reserved_materials(full, inventory, one, true).has_value());
|
||||
require(full.items.empty() && full.reserved_slots == 1 && full.total_items() + full.reserved_slots == full.capacity);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::invalid_capacity_and_slot_overflow_are_atomic() {
|
||||
Inventory inventory;
|
||||
const std::array materials{MaterialReservation{7, ItemType::Wood, 1}};
|
||||
for (int fault = 0; fault < 4; ++fault) {
|
||||
auto storage = source();
|
||||
switch (fault) {
|
||||
case 0: storage.capacity = 0; break;
|
||||
case 1: storage.capacity = 6; break;
|
||||
case 2: storage.reserved_slots = maximum; break;
|
||||
case 3: storage.capacity = 7; storage.reserved_slots = 1; break;
|
||||
}
|
||||
rejected(storage, inventory, materials, QuantityTransferError::Capacity, true);
|
||||
}
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::real_construction_rejection_keeps_stop_actor_and_routes() {
|
||||
auto world = cabin();
|
||||
at_pickup(*world);
|
||||
auto& storage = const_cast<Storage&>(world->storages().front());
|
||||
storage.items.back().reserved = 1; // The first item is valid; the second fails.
|
||||
const auto before = storage;
|
||||
const auto actor = world->agents().front();
|
||||
const auto order = world->production_orders().front();
|
||||
bool failed = false;
|
||||
try { world->step(); } catch (const std::logic_error&) { failed = true; }
|
||||
require(failed);
|
||||
same_storage(storage, before);
|
||||
same_pickup_actor(world->agents().front(), actor);
|
||||
const auto& after = world->production_orders().front();
|
||||
require(after.collected_stops == order.collected_stops && after.delivery_stops.size() == order.delivery_stops.size());
|
||||
require(after.delivery_stops.front().route_to_next == order.delivery_stops.front().route_to_next);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::real_split_lines_and_invalid_storage_selection() {
|
||||
auto world = cabin();
|
||||
at_pickup(*world);
|
||||
auto& order = const_cast<ProductionOrder&>(world->production_orders().front());
|
||||
const auto id = world->storages().front().id;
|
||||
order.materials = {{id, ItemType::Plank, 1}, {id, ItemType::StoneBlock, 2}, {id, ItemType::Plank, 2}};
|
||||
for (const auto invalid : {StorageId{0}, StorageId{123}, id}) {
|
||||
order.delivery_stops.front().storage_id = invalid;
|
||||
if (invalid == id) { // A real storage, but no selected reservation.
|
||||
for (auto& material : order.materials) material.storage_id = 123;
|
||||
}
|
||||
const auto before = world->storages().front();
|
||||
const auto actor = world->agents().front();
|
||||
const auto route = order.delivery_stops.front().route_to_next;
|
||||
bool failed = false;
|
||||
try { world->step(); } catch (const std::logic_error&) { failed = true; }
|
||||
require(failed && order.collected_stops == 0 && order.delivery_stops.front().route_to_next == route);
|
||||
same_pickup_actor(world->agents().front(), actor);
|
||||
same_storage(world->storages().front(), before);
|
||||
}
|
||||
for (auto& material : order.materials) material.storage_id = id;
|
||||
world->step();
|
||||
require(order.collected_stops == 1 && world->storages().front().items.empty());
|
||||
require(world->agents().front().inventory.item_count(ItemType::Plank) == 3 &&
|
||||
world->agents().front().inventory.item_count(ItemType::StoneBlock) == 2);
|
||||
for (int i = 0; i < 80 && order.state != JobState::Completed; ++i) world->step();
|
||||
require(order.state == JobState::Completed && world->agents().front().inventory.empty());
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::real_carpentry_invalid_capacity_keeps_pickup_untouched() {
|
||||
World world(49, 32, 32, 1, ExecutionMode::SerialReference);
|
||||
const auto store = world.add_storage({3, 3}, 1);
|
||||
world.stock_storage(store, ItemType::Wood, 1);
|
||||
const auto carpenter = world.spawn_agent({1, 3});
|
||||
world.start_scenario({8, 3});
|
||||
require(world.apply_command({1, 1, CommandKind::AssignProfession, {},
|
||||
static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter}).status == CommandStatus::Accepted);
|
||||
world.queue_production({8, 3}, RecipeId::CraftMedicineCabinet);
|
||||
world.step();
|
||||
require(world.agents().front().state == AgentState::FetchingMaterials);
|
||||
at_pickup(world);
|
||||
auto& storage = const_cast<Storage&>(world.storages().front());
|
||||
storage.reserved_slots = 1; // Already over capacity before this pickup.
|
||||
const auto before = storage;
|
||||
const auto actor = world.agents().front();
|
||||
const auto order = world.production_orders().front();
|
||||
bool failed = false;
|
||||
try { world.step(); } catch (const std::logic_error&) { failed = true; }
|
||||
require(failed && world.production_orders().front().collected_stops == 0);
|
||||
same_storage(storage, before);
|
||||
same_pickup_actor(world.agents().front(), actor);
|
||||
require(world.production_orders().front().delivery_stops.front().route_to_next == order.delivery_stops.front().route_to_next);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::real_meal_pickup_and_overflow_rejection() {
|
||||
World world(44, 32, 32, 1, ExecutionMode::SerialReference);
|
||||
const auto pantry = world.add_storage({28, 4}, 50, StorageKind::Pantry);
|
||||
world.stock_storage(pantry, ItemType::Berries, 40);
|
||||
static_cast<void>(world.spawn_agent({4, 4}));
|
||||
world.enable_hunger();
|
||||
for (int i = 0; i < 500 && world.agents().front().state != AgentState::GoingToEat; ++i) world.step();
|
||||
require(world.agents().front().state == AgentState::GoingToEat);
|
||||
auto& actor = const_cast<Agent&>(world.agents().front());
|
||||
at_pickup(world);
|
||||
actor.inventory.add(ItemType::Berries, maximum);
|
||||
const auto agent_before = actor;
|
||||
const auto storage_before = world.storages().front();
|
||||
bool failed = false;
|
||||
try { world.step(); } catch (const std::logic_error&) { failed = true; }
|
||||
require(failed);
|
||||
same_pickup_actor(actor, agent_before);
|
||||
same_storage(world.storages().front(), storage_before);
|
||||
actor.inventory.remove(ItemType::Berries, maximum);
|
||||
world.step();
|
||||
require(actor.state == AgentState::Eating && actor.inventory.item_count(ItemType::Berries) == 1 && actor.storage_id == 0);
|
||||
require(world.storages().front().item_count(ItemType::Berries) == 39);
|
||||
for (int i = 0; i < 5; ++i) world.step();
|
||||
require(world.meals_eaten() == 1 && actor.inventory.empty() && actor.hunger == 0);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::real_multistop_carpentry_reserves_first_ingredient_store() {
|
||||
World world(49, 32, 32, 1, ExecutionMode::SerialReference);
|
||||
const auto stone = world.add_storage({3, 3}, 1);
|
||||
const auto wood = world.add_storage({6, 3}, 1);
|
||||
world.stock_storage(stone, ItemType::Stone, 1);
|
||||
world.stock_storage(wood, ItemType::Wood, 1);
|
||||
const auto carpenter = world.spawn_agent({2, 3});
|
||||
world.start_scenario({8, 3});
|
||||
require(world.apply_command({1, 1, CommandKind::AssignProfession, {},
|
||||
static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter}).status == CommandStatus::Accepted);
|
||||
world.queue_production({8, 3}, RecipeId::CraftMiningRack);
|
||||
world.step();
|
||||
const auto& order = world.production_orders().front();
|
||||
require(order.materials.front().storage_id == wood && order.delivery_stops.front().storage_id == stone);
|
||||
for (int i = 0; i < 20 && order.collected_stops == 0; ++i) world.step();
|
||||
require(order.collected_stops == 1 && world.find_storage(stone)->reserved_slots == 0 &&
|
||||
world.find_storage(wood)->reserved_slots == 0);
|
||||
for (int i = 0; i < 20 && order.collected_stops == 1; ++i) world.step();
|
||||
require(order.collected_stops == 2 && world.find_storage(wood)->items.empty() &&
|
||||
world.find_storage(wood)->reserved_slots == 1);
|
||||
for (int i = 0; i < 80 && world.find_storage(wood)->item_count(ItemType::MiningRack) == 0; ++i) world.step();
|
||||
require(world.find_storage(wood)->item_count(ItemType::MiningRack) == 1 &&
|
||||
world.find_storage(wood)->reserved_slots == 0 && world.find_storage(stone)->items.empty());
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::direct_crafting_stays_in_storage() {
|
||||
World world(51, 24, 24, 1, ExecutionMode::SerialReference);
|
||||
const auto store = world.add_storage({3, 3}, 2);
|
||||
world.stock_storage(store, ItemType::Wood, 1);
|
||||
world.stock_storage(store, ItemType::Stone, 1);
|
||||
static_cast<void>(world.spawn_agent({2, 3}));
|
||||
world.queue_production({5, 3}, RecipeId::SawPlank);
|
||||
world.queue_production({7, 3}, RecipeId::CutStoneBlock);
|
||||
for (int i = 0; i < 80; ++i) {
|
||||
world.step();
|
||||
require(world.agents().front().inventory.empty(), "direct recipe created physical carrier cargo");
|
||||
}
|
||||
const auto* storage = world.find_storage(store);
|
||||
require(storage->item_count(ItemType::Wood) == 0 && storage->item_count(ItemType::Stone) == 0 &&
|
||||
storage->item_count(ItemType::Plank) == 1 && storage->item_count(ItemType::StoneBlock) == 1 &&
|
||||
storage->reserved_slots == 0);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::owner_fault_preserves_last_healthy_publication() {
|
||||
using namespace std::chrono_literals;
|
||||
auto world = cabin();
|
||||
at_pickup(*world);
|
||||
auto* fixture = world.get();
|
||||
auto clock = std::make_shared<Void::Time::ManualClock>();
|
||||
RuntimeOptions options{.clock = clock};
|
||||
options.observer = [fixture](RuntimePhase phase) {
|
||||
if (phase == RuntimePhase::BeforeTick) {
|
||||
const_cast<Storage&>(fixture->storages().front()).items.back().reserved = 1;
|
||||
}
|
||||
};
|
||||
auto rules = default_rules_manifest();
|
||||
require(rules.has_value());
|
||||
Void::Uuid::Uuid id;
|
||||
id.bytes.back() = 71;
|
||||
SimulationRuntime runtime({std::move(world), id, 1, std::move(*rules)}, std::move(options));
|
||||
const auto previous = runtime.latest();
|
||||
const auto healthy = bytes(*previous->world);
|
||||
require(clock->advance(50ms).has_value());
|
||||
RuntimeSubmission fence;
|
||||
const auto limit = std::chrono::steady_clock::now() + 5s;
|
||||
do {
|
||||
fence = runtime.synchronize();
|
||||
if (fence.admission != RuntimeAdmission::Busy) break;
|
||||
require(std::chrono::steady_clock::now() < limit, "runtime fence admission timed out");
|
||||
std::this_thread::yield();
|
||||
} while (true);
|
||||
require(fence.admission == RuntimeAdmission::Accepted && fence.completion.wait_for(5s) == std::future_status::ready);
|
||||
require(fence.completion.get().outcome == RuntimeOutcome::Faulted && runtime.view().state == RuntimeState::Faulted &&
|
||||
runtime.view().failure && !runtime.snapshot_for_save());
|
||||
require(runtime.latest() == previous && bytes(*runtime.latest()->world) == healthy,
|
||||
"owner published the rejected pickup candidate");
|
||||
}
|
||||
} // namespace
|
||||
Reference in new issue
Block a user