Connect legacy admission to the validated custody state
This commit is contained in:
commit
c183de1952
8 files changed
+445
-25
No files matched your search
@@ -84,3 +84,22 @@ S06 владеет фактическими количествами, содер
|
|||||||
- Разделить и снова объединить стек с активным резервом. Количество и свойства сохраняются, ссылка остаётся разрешимой.
|
- Разделить и снова объединить стек с активным резервом. Количество и свойства сохраняются, ссылка остаётся разрешимой.
|
||||||
- Повторить подтверждение торговли и прибытия в регион. История содержит одну завершённую операцию.
|
- Повторить подтверждение торговли и прибытия в регион. История содержит одну завершённую операцию.
|
||||||
- На контрольных 10 000 стеках и 2 000 работах измерить поиск поставщика, стоимость операций и объём сохранения через [S21](S21.md). Варианты предметов и логистики связать с [реестром паритета](../parity.md).
|
- На контрольных 10 000 стеках и 2 000 работах измерить поиск поставщика, стоимость операций и объём сохранения через [S21](S21.md). Варианты предметов и логистики связать с [реестром паритета](../parity.md).
|
||||||
|
|
||||||
|
|
||||||
|
## Срез S06-03: владение грузом и восстановление исполнения
|
||||||
|
|
||||||
|
Кандидат M01 хранит единственное количество у склада, жителя либо входного запаса `ProductionId`. `StackId` встроен в эту запись; требования рецепта используют отдельный `ItemAmount`. Получение целого стека в пустой слот сохраняет ID, разделение выдаёт ID новой части, объединение сохраняет ID получателя. Вместе с количеством меняются ссылки резервов; исторический исходный склад остаётся в материалах заказа до завершения. [Типы](../../../engine/include/settlement/core/custody.hpp) · [Реальные операции мира](../../../engine/src/custody.cpp)
|
||||||
|
|
||||||
|
Обычные начисления, добыча, все существующие рецепты, монтаж, еда и разбор склада учитывают источники и расходы. На стройке материалы действительно принадлежат входу заказа до завершения стадии. Перед изменением количества готовятся ограниченные копии затронутых владельцев, арифметика, ID и место для квитанции; после проверки выполняется не бросающий commit. Используются `Void::Numeric` закреплённого `7b0fea6`; локальные счётчики и условные операции связаны с [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7) и [#8](https://git.faumaray.com/Void/Library/issues/8). Условие замены — повторить проверки исчерпания, целого/частичного переноса, последней единицы, отмены и продолжения после загрузки на Windows x64.
|
||||||
|
|
||||||
|
Назначение использует ключ `(AgentId, next_admission)`, дальнейший шаг — отдельное пространство `(TransferId, next_operation)`. Планировщик выдаёт ключ и применяет операцию; `custody_request` восстанавливает результат уже выданного запроса и отказывает неизвестному будущему ключу. Сохраняются последние 4096 квитанций в порядке применения с точными типизированными полями, результатами и выданными ID. Снимки разделяют только неизменяемые объекты квитанций; массив указателей и остальные данные копируются. Длина материалов ограничена пятью реальными единицами крупнейшего рецепта, включая пять разных складов. Этот локальный повтор также связан с [Void/Library #6](https://git.faumaray.com/Void/Library/issues/6).
|
||||||
|
|
||||||
|
`cancel_production` освобождает неполученные резервы, возвращает вход площадки жителю и удерживает исполнителя в `Returning` до сдачи всех видов груза. Частичная сдача и отсутствие свободного склада не уничтожают остаток. Уже смонтированное основание кровати или существующий ткацкий станок сохраняют ID и приостанавливаются; `resume_production` продолжает оставшуюся стадию. Завершённые конечные объекты не отменяются. При отказе завершения нулевой таймер остаётся нулевым; следующая проверка получает новый номер операции. `legacy_representable` не изменяет мир и запрещает экспорт несовместимых фаз до записи первого байта. Сериализацию Current15, миграцию старых тел и контрольную точку схемы 3 реализует связанный S15.
|
||||||
|
|
||||||
|
Проверки `custody` охватывают реальный вход стройки, баланс расхода, разделение/объединение, пять источников, смешанный частичный возврат, приостановку/возобновление, неизменность снимка и истории, точный повтор/конфликт/будущий запрос/вытеснение, неверные ссылки и фазы, нулевые и максимальные счётчики, ожидающее завершение после загрузки. Отдельная проверка `custody-metrics` строит мир 512×512 с 500 жителями, 10 000 стеками в 1000 складах и 2000 заказами на распределённых площадках; второй вариант дополнительно создаёт 4096 квитанций реальными циклами ткачества. Измеряются 101 захват снимка и 21 последовательный такт с полной проверкой и кодированием Current15. Это синтетический сценарий, а не измерение рендеринга или сети. [Исполняемые проверки](../../../tests/custody_tests.cpp)
|
||||||
|
|
||||||
|
Нативный Windows, MSVC и отказ системного аллокатора не проверялись. Числовые отказы и отказы вставки из-за неверных аргументов проверяются без изменения сериализуемого состояния. Готовность к публикации зависит от независимой проверки интегрированного M01; локальные изменения и измерения не означают разрешение на выпуск.
|
||||||
|
|
||||||
|
Проверка интегрированного кандидата: GCC 16.2, Windows x64 Release, Wine 11; полный `ctest --output-on-failure -V` прошёл 3/3 исполняемых набора (162 core, 9 LAN, 10 viewer). Включены 14 проверок `custody`, отдельная метрика и исторические/повреждённые контрольные точки S15. Оба обычных старых корпуса повторно совпали побайтово на 1/2/6/12 исполнителях: 738386 и 393857 байт.
|
||||||
|
|
||||||
|
В описанном синтетическом сценарии без квитанций захват снимка занял p50/p95 0,036/0,049 мс; с 4096 квитанциями — 0,046/0,053 мс. Полная проверка: 0,784/0,922 и 1,301/1,664 мс; кодирование Current15 с проверкой: 9,357/9,583 и 11,881/12,025 мс; 21 последовательный такт: 0,010/0,032 и 0,010/4,728 мс. Кодирование выполнялось в памяти без записи на диск. Размер Current15 — 924042 и 1335950 байт; исходное число стеков второго варианта — 10002 из-за ткацкого запаса. Один неизменяемый объект квитанции занимает 584 байта на проверенном ABI; 4096 объектов — 2392064 байта без служебных данных аллокатора и массива указателей. Измерения зависят от прогрева и нагрузки Wine; p95 снимка укладывается в исходный ориентир 5 мс, кодирование всего мира выполняется отдельно. Локальные журналы: `/tmp/stoneheart-milestones.xprJ2SVp/s06-custody-build-final.log`, `s06-custody-ctest-final.log` и `s06-custody-{trajectory,identity-compat}-compare.log`.
|
||||||
@@ -37,6 +37,24 @@ Windows-адаптер чтения связан с [Void/Library #9](https://gi
|
|||||||
|
|
||||||
При каждом успешном открытии файла создаётся новый экземпляр сетевой сессии, в том числе при откате того же мира на ранний такт. Запоздалый результат рабочего потока и команда клиента относятся к старому экземпляру и отбрасываются. Состояние переносимых резервов определяется сохранением, а права подключений проверяются заново. [Контракт сессии](S16.md)
|
При каждом успешном открытии файла создаётся новый экземпляр сетевой сессии, в том числе при откате того же мира на ранний такт. Запоздалый результат рабочего потока и команда клиента относятся к старому экземпляру и отбрасываются. Состояние переносимых резервов определяется сохранением, а права подключений проверяются заново. [Контракт сессии](S16.md)
|
||||||
|
|
||||||
|
## Владение имуществом в версии 15
|
||||||
|
|
||||||
|
`encode_checkpoint` записывает схему 3 и тело 15. Декодер проверяет отдельную таблицу пар: схема 1 допускает тела 1–13, схема 2 — только 14, схема 3 — только 15. Проверка внешнего SHA-256 предшествует декодированию мира. Старый FNV-footer тел 1–8 и нормализация сна до версии 5 сохранены.
|
||||||
|
|
||||||
|
Тело 15 сохраняет прежний набор полей тела 14 и добавляет реестр владения: три границы выданных ID, ID складских стеков и инвентарей, номер назначения каждого жителя, действующее исполнение с номерами операций и резервами, входы и приостановку заказов, восемь счётчиков баланса для каждого предмета и журнал результатов. Резервы содержат владельца, конкретный стек, количество, источник обеспечения вместимости и исходный склад. Пустые позиции массивов имеют единственное нулевое представление. Журнал записывается от самого старого результата к самому новому независимо от физической позиции кольца в памяти.
|
||||||
|
|
||||||
|
Запрос и результат имеют собственные 16-битные длины и типизированные поля little-endian. Текущий запрос занимает не более 109 байт, результат — 318 байт; общий предел каждого остаётся 1024 байта. Непустой элемент результата может содержать нулевой остаток уже израсходованного стека. Это историческая ссылка, а не новый пустой стек. Максимум 4096 записей занимает до 1 765 376 байт вместе с длинами. Проверяются точные данные запросов, а не только их хеши.
|
||||||
|
|
||||||
|
Лимит тела 128 МиБ отделён от лимита старого сетевого снимка 4 МиБ и от бюджета декодированной памяти. Число записей каждой исторической коллекции ограничено миллионом. Бюджет памяти учитывает расширенные C++-записи всех ограниченных пулов, вложенные массивы и журнал; арифметика верхней границы проверяется при компиляции. Чтение растит вектор по одному элементу и не резервирует память под объявленное недоверенным файлом число. Маленький обрезанный файл с числом жителей 1 000 000 заканчивается ошибкой после первой незавершённой записи.
|
||||||
|
|
||||||
|
Перенос старого тела начинается только после полной исторической проверки. ID назначаются в порядке вида владельца, ID владельца и предмета. Материалы, уже доставленные на стройку, восстанавливаются во входе заказа без повторного списания склада; у прямых рецептов исходный материал остаётся на складе. Только после этого измеряется начальный баланс. У старого активного задания следующее назначение равно 2, следующая операция — 1; исторические квитанции не создаются. При загрузке тела 15 недостающие данные не достраиваются.
|
||||||
|
|
||||||
|
Экспорт 13 и 14 вызывает чистую проверку представимости до первого байта. `UnsupportedLegacyState` сообщает о возвращаемом несовместимом грузе, приостановленной площадке и нулевом времени ожидающего завершения. Эти состояния полностью сохраняются в современной контрольной точке. Правила собственности и фаз проверяет общий `World::validate_custody`; кодек дополнительно проверяет геометрию, задания, ссылки, размеры и каноничность полей.
|
||||||
|
|
||||||
|
[Исторический корпус](../../../tests/fixtures/custody_v14/README.md) содержит 13 подлинных контрольных точек схемы 2, созданных исходной сборкой `f6493e2`, и ожидаемые хеши 80 последующих тактов. Первый объединённый прогон Windows x64 под Wine подтвердил все такты на последовательном исполнителе и 2/6/12 потоках, точный экспорт 14, канонический цикл схемы 3 и продолжение после загрузки. Отдельно проверены отменённая одиночная доска и каменный блок, смешанный груз без места, частичный возврат, приостановленные кровать и станок, нулевой таймер, старые ссылки квитанций и отказ после аутентифицированного повреждения. [Проверки миграции](../../../tests/custody_migration_tests.cpp) · [Снимки с полной версией 15](../../../tests/snapshot_tests.cpp)
|
||||||
|
|
||||||
|
Универсальные части продолжают использовать закреплённые Void Binary/Core/Crypto. Собственный формат и перенос игровых фаз относятся к S15; проверка замены библиотечным реестром остаётся связана с [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7) и [#8](https://git.faumaray.com/Void/Library/issues/8). Нативная Windows и сохранность после отключения питания остаются отдельными проверками.
|
||||||
|
|
||||||
## Ошибки и восстановление
|
## Ошибки и восстановление
|
||||||
|
|
||||||
| Ситуация | Требуемое поведение |
|
| Ситуация | Требуемое поведение |
|
||||||
|
|||||||
+122
-8
@@ -4,6 +4,7 @@
|
|||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <limits>
|
#include <limits>
|
||||||
#include <set>
|
#include <set>
|
||||||
|
#include <map>
|
||||||
#include <tuple>
|
#include <tuple>
|
||||||
|
|
||||||
namespace settlement {
|
namespace settlement {
|
||||||
@@ -257,26 +258,31 @@ bool World::deposit_custody(Agent& agent, Storage& destination, ItemType type, s
|
|||||||
receipt->request.line_count = 1;
|
receipt->request.line_count = 1;
|
||||||
receipt->result = {CustodyStatus::Accepted, execution.id};
|
receipt->result = {CustodyStatus::Accepted, execution.id};
|
||||||
if (!room(execution.next_operation, 1)) return false;
|
if (!room(execution.next_operation, 1)) return false;
|
||||||
|
const auto fail = [&](CustodyStatus status) {
|
||||||
|
receipt->result.status = status;
|
||||||
|
commit_custody(agent, receipt);
|
||||||
|
return false;
|
||||||
|
};
|
||||||
auto slots = planned.reserved_slots;
|
auto slots = planned.reserved_slots;
|
||||||
for (auto& claim : execution.reservations) {
|
for (auto& claim : execution.reservations) {
|
||||||
if (claim.id && claim.kind == ReservationKind::Capacity && claim.owner.id == destination.id && !claim.backing) {
|
if (claim.id && claim.kind == ReservationKind::Capacity && claim.owner.id == destination.id && !claim.backing) {
|
||||||
if (slots < claim.count) return false;
|
if (slots < claim.count) return fail(CustodyStatus::Invalid);
|
||||||
slots -= claim.count;
|
slots -= claim.count;
|
||||||
claim = {};
|
claim = {};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (planned.total_items() + slots + count > planned.capacity) return false;
|
if (planned.total_items() + slots + count > planned.capacity) return fail(CustodyStatus::Capacity);
|
||||||
auto target = stock(planned, type);
|
auto target = stock(planned, type);
|
||||||
StackId id = 0;
|
StackId id = 0;
|
||||||
if (target != planned.items.end()) {
|
if (target != planned.items.end()) {
|
||||||
const auto amount = Void::Numeric::checked_add(target->count, count);
|
const auto amount = Void::Numeric::checked_add(target->count, count);
|
||||||
if (!amount) return false;
|
if (!amount) return fail(CustodyStatus::Overflow);
|
||||||
target->count = *amount;
|
target->count = *amount;
|
||||||
id = target->id;
|
id = target->id;
|
||||||
} else {
|
} else {
|
||||||
id = inventory.stack_id(type);
|
id = inventory.stack_id(type);
|
||||||
if (count < inventory.item_count(type)) {
|
if (count < inventory.item_count(type)) {
|
||||||
if (!room(next, 1)) return false;
|
if (!room(next, 1)) return fail(CustodyStatus::Exhausted);
|
||||||
id = next++;
|
id = next++;
|
||||||
}
|
}
|
||||||
planned.items.push_back({type, count, 0, id});
|
planned.items.push_back({type, count, 0, id});
|
||||||
@@ -448,6 +454,9 @@ void World::validate_custody() const {
|
|||||||
}
|
}
|
||||||
for (const auto& actor : agents_) add_inventory(actor.inventory, {OwnerKind::Resident, actor.id});
|
for (const auto& actor : agents_) add_inventory(actor.inventory, {OwnerKind::Resident, actor.id});
|
||||||
for (const auto& order : production_orders_) add_inventory(order.input, {OwnerKind::Production, order.id});
|
for (const auto& order : production_orders_) add_inventory(order.input, {OwnerKind::Production, order.id});
|
||||||
|
std::unordered_map<JobId, const WorkJob*> work_jobs;
|
||||||
|
std::set<JobId> assigned_jobs;
|
||||||
|
for (const auto& job : jobs_) require(work_jobs.emplace(job.id, &job).second);
|
||||||
std::unordered_map<AgentId, const Agent*> actors;
|
std::unordered_map<AgentId, const Agent*> actors;
|
||||||
std::unordered_map<ProductionId, const Agent*> producers;
|
std::unordered_map<ProductionId, const Agent*> producers;
|
||||||
for (const auto& actor : agents_) {
|
for (const auto& actor : agents_) {
|
||||||
@@ -455,6 +464,7 @@ void World::validate_custody() const {
|
|||||||
if (actor.production_id) require(producers.emplace(actor.production_id, &actor).second);
|
if (actor.production_id) require(producers.emplace(actor.production_id, &actor).second);
|
||||||
}
|
}
|
||||||
std::set<TransferId> transfers;
|
std::set<TransferId> transfers;
|
||||||
|
std::unordered_map<TransferId, std::uint64_t> active_ordinals;
|
||||||
std::set<ReservationId> reservation_ids;
|
std::set<ReservationId> reservation_ids;
|
||||||
std::set<ProductionId> work_sites;
|
std::set<ProductionId> work_sites;
|
||||||
std::set<ReservationId> backed;
|
std::set<ReservationId> backed;
|
||||||
@@ -463,13 +473,26 @@ void World::validate_custody() const {
|
|||||||
if (!actor.execution) {
|
if (!actor.execution) {
|
||||||
require(actor.inventory.empty() && actor.production_id == 0 && actor.resource_node_id == 0 &&
|
require(actor.inventory.empty() && actor.production_id == 0 && actor.resource_node_id == 0 &&
|
||||||
actor.state != AgentState::Returning && actor.state != AgentState::Hauling &&
|
actor.state != AgentState::Returning && actor.state != AgentState::Hauling &&
|
||||||
actor.state != AgentState::Eating && actor.state != AgentState::GoingToEat);
|
actor.state != AgentState::Eating && actor.state != AgentState::GoingToEat &&
|
||||||
|
actor.state != AgentState::Gathering && actor.state != AgentState::FetchingMaterials &&
|
||||||
|
(actor.state != AgentState::Working || actor.current_job != 0));
|
||||||
|
require(actor.storage_id == 0 && actor.haul_route.empty());
|
||||||
|
if (actor.state == AgentState::Working || actor.state == AgentState::Travelling) {
|
||||||
|
const auto job = work_jobs.find(actor.current_job);
|
||||||
|
require(job != work_jobs.end() && job->second->state == JobState::InProgress &&
|
||||||
|
assigned_jobs.insert(actor.current_job).second && actor.work_remaining > 0 && actor.work_remaining <= job->second->work_required);
|
||||||
|
if (actor.state == AgentState::Working) require(actor.position == job->second->position && actor.route_cursor == actor.route.size());
|
||||||
|
else require(actor.route_cursor < actor.route.size() && actor.route.back() == job->second->position);
|
||||||
|
} else require(actor.current_job == 0 && actor.work_remaining == 0 &&
|
||||||
|
(actor.state == AgentState::Idle || actor.state == AgentState::GoingToSleep || actor.state == AgentState::Sleeping));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const auto& execution = *actor.execution;
|
const auto& execution = *actor.execution;
|
||||||
|
require(actor.current_job == 0 && !actor.resting_on_ground);
|
||||||
require(execution.id && execution.id < next_transfer_id_ && transfers.insert(execution.id).second &&
|
require(execution.id && execution.id < next_transfer_id_ && transfers.insert(execution.id).second &&
|
||||||
execution.kind <= TransferKind::Return && execution.next_operation && actor.next_admission >= 2 &&
|
execution.kind <= TransferKind::Return && execution.next_operation && actor.next_admission >= 2 &&
|
||||||
execution.reservation_count <= custody_reservation_limit && execution.blocked <= CustodyStatus::NoDestination);
|
execution.reservation_count <= custody_reservation_limit && execution.blocked <= CustodyStatus::NoDestination);
|
||||||
|
active_ordinals.emplace(execution.id, execution.next_operation);
|
||||||
require(execution.production == actor.production_id && execution.source == actor.resource_node_id);
|
require(execution.production == actor.production_id && execution.source == actor.resource_node_id);
|
||||||
if (execution.kind == TransferKind::Return) {
|
if (execution.kind == TransferKind::Return) {
|
||||||
require(!actor.inventory.empty() && !actor.production_id && !actor.resource_node_id && actor.work_remaining == 0);
|
require(!actor.inventory.empty() && !actor.production_id && !actor.resource_node_id && actor.work_remaining == 0);
|
||||||
@@ -488,12 +511,17 @@ void World::validate_custody() const {
|
|||||||
if (execution.production) require(find_production(execution.production) != nullptr);
|
if (execution.production) require(find_production(execution.production) != nullptr);
|
||||||
else require(actor.state == AgentState::Hauling && is_carpentry_item(actor.inventory.first_item()));
|
else require(actor.state == AgentState::Hauling && is_carpentry_item(actor.inventory.first_item()));
|
||||||
}
|
}
|
||||||
|
std::array<unsigned, 5> claim_kinds{};
|
||||||
|
std::array<std::uint64_t, item_type_count> resident_claims{};
|
||||||
for (std::size_t index = 0; index < custody_reservation_limit; ++index) {
|
for (std::size_t index = 0; index < custody_reservation_limit; ++index) {
|
||||||
const auto& claim = execution.reservations[index];
|
const auto& claim = execution.reservations[index];
|
||||||
if (claim.id == 0) { require(claim == Reservation{}); continue; }
|
if (claim.id == 0) { require(claim == Reservation{}); continue; }
|
||||||
require(index < execution.reservation_count && claim.id < next_reservation_id_ &&
|
require(index < execution.reservation_count && claim.id < next_reservation_id_ &&
|
||||||
reservation_ids.insert(claim.id).second && claim.kind <= ReservationKind::Tending && claim.count);
|
reservation_ids.insert(claim.id).second && claim.kind <= ReservationKind::Tending && claim.count);
|
||||||
|
++claim_kinds[static_cast<std::size_t>(claim.kind)];
|
||||||
if (claim.kind == ReservationKind::Item) {
|
if (claim.kind == ReservationKind::Item) {
|
||||||
|
if (claim.owner.kind == OwnerKind::Resident && claim.item > ItemType::None && claim.item <= ItemType::Loom)
|
||||||
|
resident_claims[static_cast<std::size_t>(claim.item) - 1] += claim.count;
|
||||||
auto entry = physical.find(claim.stack);
|
auto entry = physical.find(claim.stack);
|
||||||
require(entry != physical.end() && entry->second.owner == claim.owner && entry->second.item == claim.item);
|
require(entry != physical.end() && entry->second.owner == claim.owner && entry->second.item == claim.item);
|
||||||
require(!claim.backing);
|
require(!claim.backing);
|
||||||
@@ -526,14 +554,43 @@ void World::validate_custody() const {
|
|||||||
require(claim.owner == StockOwner{} && !claim.stack && claim.item == ItemType::None &&
|
require(claim.owner == StockOwner{} && !claim.stack && claim.item == ItemType::None &&
|
||||||
claim.count == 1 && !claim.backing && !claim.origin_storage && execution.source && find_resource_node(execution.source));
|
claim.count == 1 && !claim.backing && !claim.origin_storage && execution.source && find_resource_node(execution.source));
|
||||||
workers[execution.source] += claim.count;
|
workers[execution.source] += claim.count;
|
||||||
|
require((claim.kind == ReservationKind::Tending) == (execution.kind == TransferKind::Tending));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
require(claim_kinds[static_cast<std::size_t>(ReservationKind::Worksite)] == (execution.production ? 1U : 0U));
|
||||||
|
require(claim_kinds[static_cast<std::size_t>(ReservationKind::Capacity)] == (execution.destination ? 1U : 0U));
|
||||||
|
require(claim_kinds[static_cast<std::size_t>(ReservationKind::Harvest)] ==
|
||||||
|
(execution.kind == TransferKind::Harvest && execution.source ? 1U : 0U));
|
||||||
|
require(claim_kinds[static_cast<std::size_t>(ReservationKind::Tending)] == (execution.kind == TransferKind::Tending ? 1U : 0U));
|
||||||
|
if (execution.kind == TransferKind::Meal) {
|
||||||
|
require(claim_kinds[0] == 1);
|
||||||
|
for (const auto& claim : execution.reservations) if (claim.id && claim.kind == ReservationKind::Item) {
|
||||||
|
require(claim.item == ItemType::Berries && claim.count == 1 && claim.owner ==
|
||||||
|
(actor.state == AgentState::Eating ? StockOwner{OwnerKind::Resident, actor.id} : StockOwner{OwnerKind::Storage, actor.storage_id}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (actor.state == AgentState::Eating || (execution.kind == TransferKind::Return && actor.state == AgentState::Hauling)) {
|
||||||
|
for (std::size_t i = 0; i < item_type_count; ++i) require(resident_claims[i] == actor.inventory.item_count(static_cast<ItemType>(i + 1)));
|
||||||
|
}
|
||||||
|
if (execution.source) {
|
||||||
|
const auto* node = find_resource_node(execution.source);
|
||||||
|
require(node && actor.inventory.empty() && (actor.state == AgentState::Gathering || actor.state == AgentState::Travelling));
|
||||||
|
require(execution.kind != TransferKind::Tending || node->needs_tending());
|
||||||
|
require(execution.kind != TransferKind::Harvest || (node->quantity && execution.destination && actor.storage_id == execution.destination));
|
||||||
|
}
|
||||||
|
if (actor.state == AgentState::Hauling && !execution.production) {
|
||||||
|
require(actor.storage_id == execution.destination && execution.destination && actor.work_remaining == 0);
|
||||||
|
std::uint64_t carried = 0;
|
||||||
|
for (std::size_t i = 1; i <= item_type_count; ++i) carried += actor.inventory.item_count(static_cast<ItemType>(i));
|
||||||
|
require(carried == 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for (const auto& store : storages_) {
|
for (const auto& store : storages_) {
|
||||||
require(slots[store.id] == store.reserved_slots);
|
require(slots[store.id] == store.reserved_slots);
|
||||||
for (const auto& stack : store.items) require(reserved[store.id][static_cast<std::size_t>(stack.type) - 1] == stack.reserved);
|
for (const auto& stack : store.items) require(reserved[store.id][static_cast<std::size_t>(stack.type) - 1] == stack.reserved);
|
||||||
}
|
}
|
||||||
for (const auto& node : resource_nodes_) require(workers[node.id] == node.reserved_workers);
|
for (const auto& node : resource_nodes_) require(workers[node.id] == node.reserved_workers);
|
||||||
|
for (const auto& job : jobs_) require((job.state == JobState::InProgress) == assigned_jobs.contains(job.id));
|
||||||
for (const auto& order : production_orders_) {
|
for (const auto& order : production_orders_) {
|
||||||
require(order.state <= JobState::Completed);
|
require(order.state <= JobState::Completed);
|
||||||
if (order.state == JobState::InProgress) {
|
if (order.state == JobState::InProgress) {
|
||||||
@@ -541,6 +598,45 @@ void World::validate_custody() const {
|
|||||||
const auto found_actor = producers.find(order.id);
|
const auto found_actor = producers.find(order.id);
|
||||||
require(found_actor != producers.end());
|
require(found_actor != producers.end());
|
||||||
const auto actor = found_actor->second;
|
const auto actor = found_actor->second;
|
||||||
|
require(order.materials.size() <= custody_material_limit && order.collected_stops <= order.delivery_stops.size());
|
||||||
|
const bool delivery = delivers_materials(order.recipe);
|
||||||
|
require(delivery || order.delivery_stops.empty());
|
||||||
|
std::array<std::uint64_t, item_type_count> required{}, planned{}, claimed{}, cargo{};
|
||||||
|
const auto need = [&](ItemType item, std::uint32_t count) { if (count) required[static_cast<std::size_t>(item) - 1] += count; };
|
||||||
|
if (order.recipe == RecipeId::SawPlank) need(ItemType::Wood, 1);
|
||||||
|
else if (order.recipe == RecipeId::CutStoneBlock) need(ItemType::Stone, 1);
|
||||||
|
else if (order.recipe == RecipeId::WeaveCloth) need(ItemType::Flax, 1);
|
||||||
|
else if (order.recipe == RecipeId::BuildBed) need(order.bed_material(), 1);
|
||||||
|
else for (const auto& item : is_carpentry_recipe(order.recipe) ? carpentry_materials(order.recipe) :
|
||||||
|
construction_materials(order.recipe, order.bed_base)) need(item.type, item.count);
|
||||||
|
StorageId previous_stop = 0;
|
||||||
|
for (const auto& stop : order.delivery_stops) {
|
||||||
|
require(stop.storage_id > previous_stop && find_storage(stop.storage_id)); previous_stop = stop.storage_id;
|
||||||
|
require(std::any_of(order.materials.begin(), order.materials.end(), [&](const auto& m) { return m.storage_id == stop.storage_id; }));
|
||||||
|
}
|
||||||
|
for (const auto& line : order.materials) {
|
||||||
|
require(line.type > ItemType::None && line.type <= ItemType::Loom && line.count && find_storage(line.storage_id));
|
||||||
|
planned[static_cast<std::size_t>(line.type) - 1] += line.count;
|
||||||
|
StockOwner expected{OwnerKind::Storage, line.storage_id};
|
||||||
|
if (delivery) {
|
||||||
|
if (actor->state == AgentState::Working) expected = {OwnerKind::Production, order.id};
|
||||||
|
else {
|
||||||
|
const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(), [&](const auto& e) { return e.storage_id == line.storage_id; });
|
||||||
|
require(stop != order.delivery_stops.end());
|
||||||
|
if (static_cast<std::size_t>(stop - order.delivery_stops.begin()) < order.collected_stops) expected = {OwnerKind::Resident, actor->id};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::uint64_t line_claims = 0;
|
||||||
|
for (const auto& claim : actor->execution->reservations) if (claim.id && claim.kind == ReservationKind::Item &&
|
||||||
|
claim.item == line.type && claim.origin_storage == line.storage_id) { require(claim.owner == expected); line_claims += claim.count; }
|
||||||
|
require(line_claims == line.count);
|
||||||
|
if (expected.kind == OwnerKind::Resident) cargo[static_cast<std::size_t>(line.type) - 1] += line.count;
|
||||||
|
}
|
||||||
|
for (const auto& claim : actor->execution->reservations) if (claim.id && claim.kind == ReservationKind::Item)
|
||||||
|
claimed[static_cast<std::size_t>(claim.item) - 1] += claim.count;
|
||||||
|
require(planned == required && claimed == required);
|
||||||
|
for (std::size_t i = 0; i < item_type_count; ++i) require(cargo[i] == actor->inventory.item_count(static_cast<ItemType>(i + 1)));
|
||||||
|
if (actor->state == AgentState::Working) require(actor->route_cursor == actor->route.size() && order.delivery_stops.empty());
|
||||||
if (delivers_materials(order.recipe) && actor->state == AgentState::Working) {
|
if (delivers_materials(order.recipe) && actor->state == AgentState::Working) {
|
||||||
std::array<std::uint32_t, item_type_count> expected{};
|
std::array<std::uint32_t, item_type_count> expected{};
|
||||||
for (const auto& line : order.materials) {
|
for (const auto& line : order.materials) {
|
||||||
@@ -571,7 +667,11 @@ void World::validate_custody() const {
|
|||||||
require(custody_receipts_.size() <= custody_receipt_limit &&
|
require(custody_receipts_.size() <= custody_receipt_limit &&
|
||||||
(custody_receipts_.size() == custody_receipt_limit ? custody_receipt_cursor_ < custody_receipt_limit : custody_receipt_cursor_ == 0));
|
(custody_receipts_.size() == custody_receipt_limit ? custody_receipt_cursor_ < custody_receipt_limit : custody_receipt_cursor_ == 0));
|
||||||
std::set<std::tuple<CustodyKeyKind, std::uint64_t, std::uint64_t>> keys;
|
std::set<std::tuple<CustodyKeyKind, std::uint64_t, std::uint64_t>> keys;
|
||||||
for (const auto& receipt : custody_receipts_) {
|
std::map<std::pair<CustodyKeyKind, std::uint64_t>, std::uint64_t> last_ordinals;
|
||||||
|
TransferId last_admission = 0;
|
||||||
|
std::set<TransferId> terminal_transfers;
|
||||||
|
for (std::size_t receipt_index = 0; receipt_index < custody_receipts_.size(); ++receipt_index) {
|
||||||
|
const auto& receipt = custody_receipts_[(receipt_index + custody_receipt_cursor_) % custody_receipts_.size()];
|
||||||
require(static_cast<bool>(receipt));
|
require(static_cast<bool>(receipt));
|
||||||
const auto& request = receipt->request;
|
const auto& request = receipt->request;
|
||||||
const auto& result = receipt->result;
|
const auto& result = receipt->result;
|
||||||
@@ -579,11 +679,25 @@ void World::validate_custody() const {
|
|||||||
request.kind <= TransferKind::Return && request.operation <= CustodyOperation::Tend &&
|
request.kind <= TransferKind::Return && request.operation <= CustodyOperation::Tend &&
|
||||||
request.line_count <= custody_material_limit && request.production < next_production_id_ &&
|
request.line_count <= custody_material_limit && request.production < next_production_id_ &&
|
||||||
request.destination < next_storage_id_ && keys.emplace(request.key.kind, request.key.id, request.key.ordinal).second);
|
request.destination < next_storage_id_ && keys.emplace(request.key.kind, request.key.id, request.key.ordinal).second);
|
||||||
|
auto& last_ordinal = last_ordinals[{request.key.kind, request.key.id}];
|
||||||
|
require(last_ordinal == 0 || (last_ordinal != maximum && request.key.ordinal == last_ordinal + 1));
|
||||||
|
last_ordinal = request.key.ordinal;
|
||||||
|
require(!terminal_transfers.contains(result.transfer));
|
||||||
|
if (result.terminal) { require(result.status == CustodyStatus::Accepted); terminal_transfers.insert(result.transfer); }
|
||||||
|
require(request.source < (((request.operation == CustodyOperation::Admit &&
|
||||||
|
(request.kind == TransferKind::Harvest || request.kind == TransferKind::Tending)) ||
|
||||||
|
request.operation == CustodyOperation::Harvest || request.operation == CustodyOperation::Tend) ? next_resource_node_id_ : next_storage_id_));
|
||||||
if (request.key.kind == CustodyKeyKind::Admission) {
|
if (request.key.kind == CustodyKeyKind::Admission) {
|
||||||
require(request.key.id < next_agent_id_ && request.operation == CustodyOperation::Admit);
|
require(result.transfer > last_admission && !result.terminal);
|
||||||
|
last_admission = result.transfer;
|
||||||
|
require(result.status == CustodyStatus::Accepted && request.key.id < next_agent_id_ && request.operation == CustodyOperation::Admit);
|
||||||
const auto actor = actors.find(request.key.id);
|
const auto actor = actors.find(request.key.id);
|
||||||
if (actor != actors.end()) require(request.key.ordinal < actor->second->next_admission);
|
if (actor != actors.end()) require(request.key.ordinal < actor->second->next_admission);
|
||||||
} else require(request.key.id < next_transfer_id_ && request.operation != CustodyOperation::Admit);
|
} else {
|
||||||
|
require(request.key.id < next_transfer_id_ && request.operation != CustodyOperation::Admit && result.transfer == request.key.id);
|
||||||
|
const auto active = active_ordinals.find(request.key.id);
|
||||||
|
if (active != active_ordinals.end()) require(request.key.ordinal < active->second);
|
||||||
|
}
|
||||||
for (std::size_t i = 0; i < custody_material_limit; ++i) {
|
for (std::size_t i = 0; i < custody_material_limit; ++i) {
|
||||||
const auto& line = request.lines[i];
|
const auto& line = request.lines[i];
|
||||||
if (i >= request.line_count) require(line == CustodyLine{});
|
if (i >= request.line_count) require(line == CustodyLine{});
|
||||||
|
|||||||
+31
-8
@@ -429,12 +429,15 @@ AgentId World::spawn_agent(GridPosition position) {
|
|||||||
if (!is_walkable(position)) {
|
if (!is_walkable(position)) {
|
||||||
throw std::invalid_argument("agent spawn cell is not walkable");
|
throw std::invalid_argument("agent spawn cell is not walkable");
|
||||||
}
|
}
|
||||||
const AgentId id = next_agent_id_++;
|
const AgentId id = next_agent_id_;
|
||||||
|
const auto successor = Void::Numeric::checked_add(id, AgentId{1});
|
||||||
|
if (id == 0 || !successor) throw std::overflow_error("resident identities exhausted");
|
||||||
Agent agent;
|
Agent agent;
|
||||||
agent.id = id;
|
agent.id = id;
|
||||||
agent.position = position;
|
agent.position = position;
|
||||||
if (hunger_enabled_) agent.hunger = initial_hunger(id);
|
if (hunger_enabled_) agent.hunger = initial_hunger(id);
|
||||||
agents_.push_back(std::move(agent));
|
agents_.push_back(std::move(agent));
|
||||||
|
next_agent_id_ = *successor;
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -445,8 +448,11 @@ JobId World::add_job(GridPosition position, std::uint32_t work_required) {
|
|||||||
if (work_required == 0) {
|
if (work_required == 0) {
|
||||||
throw std::invalid_argument("work duration must be greater than zero");
|
throw std::invalid_argument("work duration must be greater than zero");
|
||||||
}
|
}
|
||||||
const JobId id = next_job_id_++;
|
const JobId id = next_job_id_;
|
||||||
|
const auto successor = Void::Numeric::checked_add(id, JobId{1});
|
||||||
|
if (id == 0 || !successor) throw std::overflow_error("job identities exhausted");
|
||||||
jobs_.push_back(WorkJob{id, position, work_required, work_required, JobState::Available});
|
jobs_.push_back(WorkJob{id, position, work_required, work_required, JobState::Available});
|
||||||
|
next_job_id_ = *successor;
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1544,9 +1550,13 @@ void World::finish_meal_step(Agent& agent) {
|
|||||||
auto& sink = item_balances_[static_cast<std::size_t>(ItemType::Berries) - 1].meal;
|
auto& sink = item_balances_[static_cast<std::size_t>(ItemType::Berries) - 1].meal;
|
||||||
const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{1});
|
const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{1});
|
||||||
const auto meals = Void::Numeric::checked_add(meals_eaten_, std::uint64_t{1});
|
const auto meals = Void::Numeric::checked_add(meals_eaten_, std::uint64_t{1});
|
||||||
auto receipt = prepare_custody(agent, CustodyOperation::Eat,
|
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Eat,
|
||||||
amount && meals ? CustodyStatus::Accepted : CustodyStatus::Overflow);
|
amount && meals ? CustodyStatus::Accepted : CustodyStatus::Overflow));
|
||||||
if (!receipt) return;
|
if (!receipt) return;
|
||||||
|
receipt->result.terminal = amount && meals;
|
||||||
|
receipt->result.effects[0] = {{OwnerKind::Resident, agent.id}, agent.inventory.stack_id(ItemType::Berries), ItemType::Berries,
|
||||||
|
amount && meals ? 0U : 1U};
|
||||||
|
receipt->result.effect_count = 1;
|
||||||
commit_custody(agent, receipt);
|
commit_custody(agent, receipt);
|
||||||
if (!amount || !meals) return;
|
if (!amount || !meals) return;
|
||||||
sink = *amount;
|
sink = *amount;
|
||||||
@@ -1690,11 +1700,23 @@ void World::finish_production(Agent& agent) {
|
|||||||
if (!receipt) return;
|
if (!receipt) return;
|
||||||
if (status == CustodyStatus::Accepted) {
|
if (status == CustodyStatus::Accepted) {
|
||||||
receipt->result.terminal = !carpentry;
|
receipt->result.terminal = !carpentry;
|
||||||
|
for (const auto& material : order.materials) {
|
||||||
|
const auto& original_store = storage_by_id(material.storage_id);
|
||||||
|
StackId consumed_id = 0;
|
||||||
|
std::uint32_t remaining = 0;
|
||||||
|
StockOwner owner{OwnerKind::Production, order.id};
|
||||||
|
if (delivered) { consumed_id = order.input.stack_id(material.type); remaining = input.item_count(material.type); }
|
||||||
|
else {
|
||||||
|
owner = {OwnerKind::Storage, material.storage_id};
|
||||||
|
for (const auto& stack : original_store.items) if (stack.type == material.type) consumed_id = stack.id;
|
||||||
|
for (const auto& store : stores) if (store.id == material.storage_id) remaining = store.item_count(material.type);
|
||||||
|
}
|
||||||
|
receipt->result.effects[receipt->result.effect_count++] = {owner, consumed_id, material.type, remaining};
|
||||||
|
}
|
||||||
if (output_id) {
|
if (output_id) {
|
||||||
receipt->result.effects[0] = {carpentry ? StockOwner{OwnerKind::Resident, agent.id} :
|
receipt->result.effects[receipt->result.effect_count++] = {carpentry ? StockOwner{OwnerKind::Resident, agent.id} :
|
||||||
StockOwner{OwnerKind::Storage, stores.front().id}, output_id, recipe.output,
|
StockOwner{OwnerKind::Storage, stores.front().id}, output_id, recipe.output,
|
||||||
carpentry ? inventory.item_count(recipe.output) : stores.front().item_count(recipe.output)};
|
carpentry ? inventory.item_count(recipe.output) : stores.front().item_count(recipe.output)};
|
||||||
receipt->result.effect_count = 1;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
commit_custody(agent, receipt);
|
commit_custody(agent, receipt);
|
||||||
@@ -1867,8 +1889,9 @@ void World::step(TickProfile* profile) {
|
|||||||
ResourceNode& node = resource_node_by_id(agent.resource_node_id);
|
ResourceNode& node = resource_node_by_id(agent.resource_node_id);
|
||||||
if (agent.storage_id == 0) {
|
if (agent.storage_id == 0) {
|
||||||
const auto growth = Void::Numeric::checked_add(tick_, growing_time(node.site));
|
const auto growth = Void::Numeric::checked_add(tick_, growing_time(node.site));
|
||||||
auto receipt = prepare_custody(agent, CustodyOperation::Tend, growth ? CustodyStatus::Accepted : CustodyStatus::Overflow);
|
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Tend, growth ? CustodyStatus::Accepted : CustodyStatus::Overflow, node.id));
|
||||||
if (!receipt) continue;
|
if (!receipt) continue;
|
||||||
|
receipt->result.terminal = growth.has_value();
|
||||||
commit_custody(agent, receipt);
|
commit_custody(agent, receipt);
|
||||||
if (!growth) continue;
|
if (!growth) continue;
|
||||||
node.growth_at = *growth;
|
node.growth_at = *growth;
|
||||||
@@ -1884,7 +1907,7 @@ void World::step(TickProfile* profile) {
|
|||||||
const auto amount = Void::Numeric::checked_add(balance, std::uint64_t{1});
|
const auto amount = Void::Numeric::checked_add(balance, std::uint64_t{1});
|
||||||
const auto next = Void::Numeric::checked_add(next_stack_id_, std::uint64_t{1});
|
const auto next = Void::Numeric::checked_add(next_stack_id_, std::uint64_t{1});
|
||||||
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Harvest,
|
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Harvest,
|
||||||
!next ? CustodyStatus::Exhausted : !amount ? CustodyStatus::Overflow : CustodyStatus::Accepted));
|
!next ? CustodyStatus::Exhausted : !amount ? CustodyStatus::Overflow : CustodyStatus::Accepted, node.id));
|
||||||
if (!receipt) continue;
|
if (!receipt) continue;
|
||||||
if (next && amount) {
|
if (next && amount) {
|
||||||
receipt->result.effects[0] = {{OwnerKind::Resident, agent.id}, next_stack_id_, node.type, 1};
|
receipt->result.effects[0] = {{OwnerKind::Resident, agent.id}, next_stack_id_, node.type, 1};
|
||||||
|
|||||||
@@ -22,6 +22,16 @@ constexpr std::uint32_t save_version = 15;
|
|||||||
constexpr std::uint32_t last_legacy_footer_version = 8;
|
constexpr std::uint32_t last_legacy_footer_version = 8;
|
||||||
constexpr std::size_t max_records = 1'000'000;
|
constexpr std::size_t max_records = 1'000'000;
|
||||||
constexpr std::size_t max_save_bytes = 128 * 1024 * 1024;
|
constexpr std::size_t max_save_bytes = 128 * 1024 * 1024;
|
||||||
|
// The wire limit is independent of decoded C++ layout: an old byte-light agent
|
||||||
|
// now includes an execution/claim array. Cover every bounded top-level pool,
|
||||||
|
// nested vectors (maximum element expansion <4x wire), and the receipt ring.
|
||||||
|
// This is an accounting ceiling, never a reserve() request from untrusted input.
|
||||||
|
constexpr std::size_t record_pool_bytes = sizeof(Agent) + sizeof(WorkJob) +
|
||||||
|
sizeof(ResourceNode) + sizeof(Storage) + sizeof(ProductionOrder);
|
||||||
|
static_assert(record_pool_bytes <= (std::numeric_limits<std::size_t>::max() -
|
||||||
|
4 * max_save_bytes - custody_receipt_limit * (sizeof(CustodyReceipt) + 32)) / max_records);
|
||||||
|
constexpr std::size_t max_decode_allocation_bytes = max_records * record_pool_bytes +
|
||||||
|
4 * max_save_bytes + custody_receipt_limit * (sizeof(CustodyReceipt) + 32);
|
||||||
|
|
||||||
void require_save(bool condition, const char* error) {
|
void require_save(bool condition, const char* error) {
|
||||||
if (!condition) throw std::runtime_error(error);
|
if (!condition) throw std::runtime_error(error);
|
||||||
@@ -87,7 +97,7 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
void allocate(std::size_t count, std::size_t size) {
|
void allocate(std::size_t count, std::size_t size) {
|
||||||
require_save(count <= max_save_bytes / size &&
|
require_save(count <= max_decode_allocation_bytes / size &&
|
||||||
allocations_.consume_field(count * size).has_value(), "Save allocation budget exceeded.");
|
allocations_.consume_field(count * size).has_value(), "Save allocation budget exceeded.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,7 +119,7 @@ private:
|
|||||||
std::istream& stream_;
|
std::istream& stream_;
|
||||||
std::size_t bytes_ = 0;
|
std::size_t bytes_ = 0;
|
||||||
// Legacy footers cover the signature and version, which are read first.
|
// Legacy footers cover the signature and version, which are read first.
|
||||||
Void::Binary::DecodeBudget allocations_{{max_save_bytes, max_save_bytes, 64}};
|
Void::Binary::DecodeBudget allocations_{{max_decode_allocation_bytes, max_decode_allocation_bytes, 64}};
|
||||||
bool legacy_footer_ = true;
|
bool legacy_footer_ = true;
|
||||||
std::uint64_t legacy_digest_ = Void::Hash::fnv1a64_offset_basis;
|
std::uint64_t legacy_digest_ = Void::Hash::fnv1a64_offset_basis;
|
||||||
};
|
};
|
||||||
@@ -467,7 +477,7 @@ void result_fields(Archive& archive, Result& result) {
|
|||||||
archive.field(effect.item);
|
archive.field(effect.item);
|
||||||
archive.field(effect.count);
|
archive.field(effect.count);
|
||||||
require_save(effect.owner.kind != OwnerKind::None && effect.stack != 0 &&
|
require_save(effect.owner.kind != OwnerKind::None && effect.stack != 0 &&
|
||||||
effect.item > ItemType::None && effect.item <= ItemType::Loom && effect.count != 0,
|
effect.item > ItemType::None && effect.item <= ItemType::Loom,
|
||||||
"Invalid custody result effect.");
|
"Invalid custody result effect.");
|
||||||
}
|
}
|
||||||
for (std::size_t i = result.effect_count; i < result.effects.size(); ++i) {
|
for (std::size_t i = result.effect_count; i < result.effects.size(); ++i) {
|
||||||
@@ -634,8 +644,8 @@ void WorldSaveCodec::validate(const World& world, bool modern) {
|
|||||||
|
|
||||||
const auto storage_index = [&](StorageId id) { return record_index(world.storages_, id); };
|
const auto storage_index = [&](StorageId id) { return record_index(world.storages_, id); };
|
||||||
const auto node_index = [&](ResourceNodeId id) { return record_index(world.resource_nodes_, id); };
|
const auto node_index = [&](ResourceNodeId id) { return record_index(world.resource_nodes_, id); };
|
||||||
std::vector<ItemCounts> reserved_items(world.storages_.size());
|
std::vector<ItemCounts> reserved_items(modern ? 0 : world.storages_.size());
|
||||||
std::vector<ItemCounts> expected_cargo(world.production_orders_.size());
|
std::vector<ItemCounts> expected_cargo(modern ? 0 : world.production_orders_.size());
|
||||||
std::vector<AgentId> bed_owners;
|
std::vector<AgentId> bed_owners;
|
||||||
for (std::size_t i = 0; i < world.production_orders_.size(); ++i) {
|
for (std::size_t i = 0; i < world.production_orders_.size(); ++i) {
|
||||||
const auto& order = world.production_orders_[i];
|
const auto& order = world.production_orders_[i];
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
|
#include <limits>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
|
|
||||||
@@ -49,7 +50,8 @@ std::size_t body_begin(std::string_view bytes) {
|
|||||||
}
|
}
|
||||||
template<class T> void change(std::string& bytes, std::size_t offset, T value) {
|
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));
|
Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}).subspan(offset));
|
||||||
require(writer.writeLittle(value).has_value(), "mutation exceeded frame");
|
if constexpr(std::is_enum_v<T>) require(writer.writeLittle(static_cast<std::underlying_type_t<T>>(value)).has_value(), "mutation exceeded frame");
|
||||||
|
else require(writer.writeLittle(value).has_value(), "mutation exceeded frame");
|
||||||
}
|
}
|
||||||
void rehash(std::string& bytes) {
|
void rehash(std::string& bytes) {
|
||||||
auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
|
auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
|
||||||
@@ -62,6 +64,37 @@ void reject(std::string bytes) {
|
|||||||
auto catalog = builtin_rule_packages();
|
auto catalog = builtin_rule_packages();
|
||||||
require(!decode_checkpoint(bytes,*catalog,1,ExecutionMode::SerialReference), "authenticated malformed custody was accepted");
|
require(!decode_checkpoint(bytes,*catalog,1,ExecutionMode::SerialReference), "authenticated malformed custody was accepted");
|
||||||
}
|
}
|
||||||
|
struct CustodyOffsets {
|
||||||
|
std::size_t extension, agent_state, agent_timer, receipts;
|
||||||
|
std::vector<std::pair<std::size_t,std::size_t>> entries;
|
||||||
|
};
|
||||||
|
CustodyOffsets offsets(const World& world, const std::string& bytes) {
|
||||||
|
CustodyOffsets result{};
|
||||||
|
const auto body=body_begin(bytes);
|
||||||
|
result.extension=body+raw(world,WorldSaveFormat::Current14).size();
|
||||||
|
Void::Binary::Reader reader(std::as_bytes(std::span{bytes.data(),bytes.size()}));
|
||||||
|
require(reader.skip(body+109+static_cast<std::size_t>(world.width())*world.height()+4+16).has_value(),"missing agent state");
|
||||||
|
result.agent_state=reader.position();
|
||||||
|
require(reader.skip(9).has_value(),"missing agent route");
|
||||||
|
const auto route=reader.readLittle<std::uint32_t>().value();
|
||||||
|
require(reader.skip(static_cast<std::size_t>(route)*8+8).has_value(),"missing agent timer");
|
||||||
|
result.agent_timer=reader.position();
|
||||||
|
std::size_t extension_size=24+world.production_orders().size()*(12*item_type_count+1)+64*item_type_count;
|
||||||
|
for(const auto& store:world.storages()) extension_size+=store.items.size()*8;
|
||||||
|
for(const auto& agent:world.agents()) extension_size+=8*item_type_count+9+
|
||||||
|
(agent.execution?43+47*agent.execution->reservation_count:0);
|
||||||
|
result.receipts=result.extension+extension_size;
|
||||||
|
Void::Binary::Reader receipts(std::as_bytes(std::span{bytes.data(),bytes.size()}).subspan(result.receipts));
|
||||||
|
const auto count=receipts.readLittle<std::uint32_t>().value();
|
||||||
|
for(std::uint32_t i=0;i<count;++i){
|
||||||
|
const auto request=result.receipts+receipts.position();
|
||||||
|
const auto request_size=receipts.readLittle<std::uint16_t>().value();require(receipts.skip(request_size).has_value(),"bad request fixture");
|
||||||
|
const auto response=result.receipts+receipts.position();
|
||||||
|
const auto result_size=receipts.readLittle<std::uint16_t>().value();require(receipts.skip(result_size).has_value(),"bad result fixture");
|
||||||
|
result.entries.emplace_back(request,response);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
void legacy_reject(const World& world) {
|
void legacy_reject(const World& world) {
|
||||||
for (auto format : {WorldSaveFormat::Legacy13, WorldSaveFormat::Current14}) {
|
for (auto format : {WorldSaveFormat::Legacy13, WorldSaveFormat::Current14}) {
|
||||||
std::ostringstream out(std::ios::binary);
|
std::ostringstream out(std::ios::binary);
|
||||||
@@ -78,6 +111,10 @@ struct [[= Void::Testing::name("CustodyMigrationTests")]] CustodyMigrationTests
|
|||||||
[[= Void::Testing::tag("custody-migration")]] Test completed_receipts_keep_retired_stock_and_order_references();
|
[[= Void::Testing::tag("custody-migration")]] Test completed_receipts_keep_retired_stock_and_order_references();
|
||||||
[[= Void::Testing::tag("custody-migration")]] Test single_finished_material_and_partial_return_use_modern_format();
|
[[= Void::Testing::tag("custody-migration")]] Test single_finished_material_and_partial_return_use_modern_format();
|
||||||
[[= Void::Testing::tag("custody-migration")]] Test suspended_sites_and_zero_completion_use_modern_format();
|
[[= Void::Testing::tag("custody-migration")]] Test suspended_sites_and_zero_completion_use_modern_format();
|
||||||
|
[[= Void::Testing::tag("custody-mutation")]] Test authenticated_phase_and_receipt_mutations_are_rejected();
|
||||||
|
[[= Void::Testing::tag("custody-mutation")]] Test retired_zero_effect_and_bounded_receipt_fields();
|
||||||
|
[[= Void::Testing::tag("custody-migration")]] Test truncated_collection_counts_allocate_incrementally();
|
||||||
|
[[= Void::Testing::tag("custody-mutation")]] Test full_receipt_ring_preserves_exact_results_and_evicts_old_ordinals();
|
||||||
};
|
};
|
||||||
Test CustodyMigrationTests::authentic_historical_phases_keep_eighty_tick_projection() {
|
Test CustodyMigrationTests::authentic_historical_phases_keep_eighty_tick_projection() {
|
||||||
for (const auto& original : custody_v14::fixtures) {
|
for (const auto& original : custody_v14::fixtures) {
|
||||||
@@ -211,4 +248,84 @@ Test CustodyMigrationTests::suspended_sites_and_zero_completion_use_modern_forma
|
|||||||
require(save(pending)==encoded,"pending zero timer did not roundtrip");
|
require(save(pending)==encoded,"pending zero timer did not roundtrip");
|
||||||
pending.world->step();pending.world->validate_custody();
|
pending.world->step();pending.world->validate_custody();
|
||||||
}
|
}
|
||||||
|
Test CustodyMigrationTests::authenticated_phase_and_receipt_mutations_are_rejected() {
|
||||||
|
auto metadata=load(unhex(fixture("cabin-before-pickup").checkpoint));
|
||||||
|
metadata.world->step();
|
||||||
|
const auto good=save(metadata); const auto location=offsets(*metadata.world,good);
|
||||||
|
require(location.entries.size()==1,"pickup should produce one retained operation");
|
||||||
|
const auto [request,result]=location.entries.front();
|
||||||
|
auto wrong_transfer=good;
|
||||||
|
change(wrong_transfer,location.extension+16,std::uint64_t{3});
|
||||||
|
change(wrong_transfer,result+3,std::uint64_t{2});reject(std::move(wrong_transfer));
|
||||||
|
auto future=good;change(future,request+11,std::numeric_limits<std::uint64_t>::max());reject(std::move(future));
|
||||||
|
auto source=good;change(source,request+29,std::numeric_limits<std::uint64_t>::max());reject(std::move(source));
|
||||||
|
metadata.world=std::make_unique<World>(43,20,8,1,ExecutionMode::SerialReference);
|
||||||
|
static_cast<void>(metadata.world->spawn_agent({1,3}));
|
||||||
|
const auto idle=save(metadata); const auto idle_locations=offsets(*metadata.world,idle);
|
||||||
|
for(auto state:{AgentState::Working,AgentState::Gathering,AgentState::FetchingMaterials}) {
|
||||||
|
auto bad=idle;change(bad,idle_locations.agent_state,state);reject(std::move(bad));
|
||||||
|
}
|
||||||
|
auto timer=idle;change(timer,idle_locations.agent_timer,std::uint32_t{1});reject(std::move(timer));
|
||||||
|
}
|
||||||
|
Test CustodyMigrationTests::retired_zero_effect_and_bounded_receipt_fields() {
|
||||||
|
auto metadata=load(unhex(fixture("meal-eating").checkpoint));
|
||||||
|
for(int tick=0;tick<8;++tick)metadata.world->step();
|
||||||
|
const auto good=save(metadata); const auto location=offsets(*metadata.world,good);
|
||||||
|
require(!location.entries.empty(),"meal did not produce historical result");
|
||||||
|
const auto [request,result]=location.entries.back();
|
||||||
|
auto loaded=load(good);
|
||||||
|
const auto receipt=metadata.world->custody_receipts().back();
|
||||||
|
require(receipt->result.effect_count==1&&receipt->result.effects[0].count==0,"terminal consumption lost retired zero-count effect");
|
||||||
|
require(loaded.world->custody_request(receipt->request)==receipt->result,"zero-count historical effect changed after restore");
|
||||||
|
auto oversized=good;change(oversized,request,std::uint16_t{1025});reject(std::move(oversized));
|
||||||
|
auto too_many=good;change(too_many,location.receipts,std::uint32_t{4097});reject(std::move(too_many));
|
||||||
|
auto bad_item=good;change(bad_item,result+2+12+17,ItemType::None);reject(std::move(bad_item));
|
||||||
|
auto bad_owner=good;change(bad_owner,result+2+12,OwnerKind::None);reject(std::move(bad_owner));
|
||||||
|
auto count=good;change(count,result+2+10,std::uint8_t{12});reject(std::move(count));
|
||||||
|
}
|
||||||
|
Test CustodyMigrationTests::truncated_collection_counts_allocate_incrementally() {
|
||||||
|
auto original=unhex(fixture("cabin-before-pickup").checkpoint);
|
||||||
|
const auto begin=body_begin(original);
|
||||||
|
std::string body=original.substr(begin,original.size()-begin-32);
|
||||||
|
constexpr std::size_t agents_count=109+20*8;
|
||||||
|
body.resize(agents_count+4);
|
||||||
|
for(auto count:{1'000'000U,1'000'001U}) {
|
||||||
|
change(body,agents_count,count);
|
||||||
|
std::istringstream input(body,std::ios::binary);
|
||||||
|
bool failed=false;
|
||||||
|
try{static_cast<void>(World::read_save(input,1,ExecutionMode::SerialReference));}
|
||||||
|
catch(const std::runtime_error&){failed=true;}
|
||||||
|
require(failed,"truncated huge agent declaration was accepted");
|
||||||
|
}
|
||||||
|
// Many byte-light historical agents remain valid despite larger modern
|
||||||
|
// in-memory Agent records; the wire ceiling does not become a sizeof cap.
|
||||||
|
World world(43,3,3,1,ExecutionMode::SerialReference);
|
||||||
|
for(int i=0;i<2000;++i)static_cast<void>(world.spawn_agent({1,1}));
|
||||||
|
const auto bytes=raw(world,WorldSaveFormat::Current14);
|
||||||
|
std::istringstream input(bytes,std::ios::binary);
|
||||||
|
auto loaded=World::read_save(input,1,ExecutionMode::SerialReference);
|
||||||
|
require(loaded->agents().size()==2000&&raw(*loaded,WorldSaveFormat::Current14)==bytes,"byte-light history failed migration");
|
||||||
|
}
|
||||||
|
Test CustodyMigrationTests::full_receipt_ring_preserves_exact_results_and_evicts_old_ordinals() {
|
||||||
|
auto metadata=load(unhex(fixture("meal-eating").checkpoint));
|
||||||
|
metadata.world=std::make_unique<World>(43,20,8,1,ExecutionMode::SerialReference);
|
||||||
|
const auto storage=metadata.world->add_storage({3,3},2050);
|
||||||
|
metadata.world->stock_storage(storage,ItemType::Wood,2050);
|
||||||
|
static_cast<void>(metadata.world->spawn_agent({3,3}));
|
||||||
|
for(int i=0;i<2050;++i)metadata.world->queue_production({3,3},RecipeId::SawPlank);
|
||||||
|
for(int tick=0;tick<30000&&metadata.world->custody_receipts().size()<4096;++tick)metadata.world->step();
|
||||||
|
require(metadata.world->custody_receipts().size()==4096,"real production did not fill global receipt ring");
|
||||||
|
const auto remembered=metadata.world->custody_receipts().front();
|
||||||
|
const auto full=save(metadata);auto loaded=load(full);
|
||||||
|
require(save(loaded)==full&&loaded.world->custody_receipts().size()==4096,"full receipt ring was truncated or reordered");
|
||||||
|
require(full.size()<2*1024*1024,"typed receipt ring exceeded its proven wire budget");
|
||||||
|
require(loaded.world->custody_request(remembered->request)==remembered->result,"full ring lost exact replay");
|
||||||
|
auto conflicting=remembered->request;conflicting.destination=0;
|
||||||
|
require(loaded.world->custody_request(conflicting).status==CustodyStatus::Conflict,"exact request conflict was not detected");
|
||||||
|
for(int tick=0;tick<30;++tick)loaded.world->step();
|
||||||
|
require(loaded.world->custody_request(remembered->request).status==CustodyStatus::Stale,"evicted admission was eligible for replay");
|
||||||
|
const auto wrapped=save(loaded);auto copy=load(wrapped);
|
||||||
|
require(save(copy)==wrapped&©.world->custody_request(remembered->request).status==CustodyStatus::Stale,"wrapped ring changed order or stale fence on restore");
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace
|
} // namespace
|
||||||
+121
-2
@@ -32,6 +32,10 @@ struct [[= Void::Testing::name("CustodyTests")]] CustodyTests : Void::Testing::S
|
|||||||
[[= Void::Testing::tag("custody")]] Test suspended_bed_and_loom_resume();
|
[[= Void::Testing::tag("custody")]] Test suspended_bed_and_loom_resume();
|
||||||
[[= Void::Testing::tag("custody")]] Test admission_exhaustion_and_receipt_eviction();
|
[[= Void::Testing::tag("custody")]] Test admission_exhaustion_and_receipt_eviction();
|
||||||
[[= Void::Testing::tag("custody")]] Test recipes_meals_and_harvest_balance();
|
[[= Void::Testing::tag("custody")]] Test recipes_meals_and_harvest_balance();
|
||||||
|
[[= Void::Testing::tag("custody")]] Test rejects_missing_execution_and_claims();
|
||||||
|
[[= Void::Testing::tag("custody")]] Test persistent_counter_boundaries_and_pending_completion();
|
||||||
|
[[= Void::Testing::tag("custody")]] Test resident_and_job_id_allocation_is_checked();
|
||||||
|
[[= Void::Testing::tag("custody")]] Test modern_roundtrip_cancel_and_exact_retry();
|
||||||
[[= Void::Testing::tag("custody-metrics")]] Test snapshot_metrics();
|
[[= Void::Testing::tag("custody-metrics")]] Test snapshot_metrics();
|
||||||
};
|
};
|
||||||
Test CustodyTests::ownership_delivery_and_consumption() {
|
Test CustodyTests::ownership_delivery_and_consumption() {
|
||||||
@@ -172,7 +176,10 @@ Test CustodyTests::snapshot_metrics() {
|
|||||||
for (std::size_t j = 1; j <= item_type_count; ++j) if (static_cast<ItemType>(j) != ItemType::Berries)
|
for (std::size_t j = 1; j <= item_type_count; ++j) if (static_cast<ItemType>(j) != ItemType::Berries)
|
||||||
w.stock_storage(store, static_cast<ItemType>(j), 1);
|
w.stock_storage(store, static_cast<ItemType>(j), 1);
|
||||||
}
|
}
|
||||||
while (w.production_orders().size() < 2000) w.queue_production({3, 3}, RecipeId::SawPlank);
|
while (w.production_orders().size() < 2000) {
|
||||||
|
const auto i = static_cast<std::int32_t>(w.production_orders().size());
|
||||||
|
w.queue_production({i % 100 + 3, i / 100 + 10}, RecipeId::SawPlank);
|
||||||
|
}
|
||||||
w.validate_custody();
|
w.validate_custody();
|
||||||
std::vector<double> samples;
|
std::vector<double> samples;
|
||||||
for (int i = 0; i < 101; ++i) {
|
for (int i = 0; i < 101; ++i) {
|
||||||
@@ -180,8 +187,120 @@ Test CustodyTests::snapshot_metrics() {
|
|||||||
samples.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
|
samples.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
|
||||||
}
|
}
|
||||||
std::sort(samples.begin(), samples.end()); std::ostringstream bytes; w.write_save(bytes);
|
std::sort(samples.begin(), samples.end()); std::ostringstream bytes; w.write_save(bytes);
|
||||||
|
std::ostringstream modern; w.write_save(modern, WorldSaveFormat::Current15);
|
||||||
std::cout << "custody metrics residents=500 stacks=" << (full ? 10002 : 10000) << " orders=2000 receipts=" << w.custody_receipts().size()
|
std::cout << "custody metrics residents=500 stacks=" << (full ? 10002 : 10000) << " orders=2000 receipts=" << w.custody_receipts().size()
|
||||||
<< " capture_ms_p50=" << samples[50] << " p95=" << samples[95] << " raw13_bytes=" << bytes.str().size() << '\n';
|
<< " capture_ms_p50=" << samples[50] << " p95=" << samples[95] << " raw13_bytes=" << bytes.str().size() << " raw15_bytes=" << modern.str().size()
|
||||||
|
<< " receipt_object_bytes=" << sizeof(CustodyReceipt) << '\n';
|
||||||
|
std::vector<double> validation, serialization, advancement;
|
||||||
|
for (int i = 0; i < 21; ++i) {
|
||||||
|
auto begin = std::chrono::steady_clock::now(); w.validate_custody();
|
||||||
|
validation.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
|
||||||
|
begin = std::chrono::steady_clock::now(); std::ostringstream encoded; w.write_save(encoded, WorldSaveFormat::Current15);
|
||||||
|
serialization.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
|
||||||
|
begin = std::chrono::steady_clock::now(); w.step();
|
||||||
|
advancement.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
|
||||||
|
}
|
||||||
|
w.validate_custody();
|
||||||
|
for (auto pair : {std::pair{"validate", &validation}, std::pair{"serialize15", &serialization}, std::pair{"step", &advancement}}) {
|
||||||
|
std::sort(pair.second->begin(), pair.second->end());
|
||||||
|
std::cout << "custody metrics initial_receipts=" << (full ? 4096 : 0) << ' ' << pair.first
|
||||||
|
<< "_ms_p50=" << (*pair.second)[10] << " p95=" << (*pair.second)[19] << '\n';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Test CustodyTests::rejects_missing_execution_and_claims() {
|
||||||
|
auto w = cabin(); ticks(*w, 1);
|
||||||
|
const auto rejects = [&] { try { w->validate_custody(); } catch (const std::runtime_error&) { return true; } return false; };
|
||||||
|
auto& actor = const_cast<Agent&>(w->agents()[0]); auto execution = actor.execution;
|
||||||
|
actor.execution.reset(); require(rejects(), "active actor without execution accepted"); actor.execution = execution;
|
||||||
|
actor.execution->reservations[0] = {}; require(rejects(), "missing material reservation accepted"); actor.execution = execution;
|
||||||
|
actor.execution->reservations[1].id = actor.execution->reservations[0].id;
|
||||||
|
require(rejects(), "duplicate claim ID accepted"); actor.execution = execution;
|
||||||
|
auto& order = const_cast<ProductionOrder&>(w->production_orders()[0]); ++order.materials[0].count;
|
||||||
|
require(rejects(), "different recipe quantity accepted"); --order.materials[0].count;
|
||||||
|
w->validate_custody();
|
||||||
|
}
|
||||||
|
Test CustodyTests::modern_roundtrip_cancel_and_exact_retry() {
|
||||||
|
auto w = cabin(); ticks(*w, 16);
|
||||||
|
require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused");
|
||||||
|
std::ostringstream encoded; w->write_save(encoded, WorldSaveFormat::Current15);
|
||||||
|
std::istringstream input(encoded.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference);
|
||||||
|
for (const auto& receipt : w->custody_receipts()) require(resumed->custody_request(receipt->request) == receipt->result, "restored exact receipt differed");
|
||||||
|
std::ostringstream legacy;
|
||||||
|
bool refused = false; try { w->write_save(legacy); } catch (const UnsupportedLegacyState&) { refused = true; }
|
||||||
|
require(refused && legacy.str().empty(), "legacy refusal wrote bytes");
|
||||||
|
for (int i = 0; i < 40; ++i) {
|
||||||
|
ticks(*w, 1); ticks(*resumed, 1);
|
||||||
|
std::ostringstream a,b; w->write_save(a, WorldSaveFormat::Current15); resumed->write_save(b, WorldSaveFormat::Current15);
|
||||||
|
require(a.str() == b.str(), "modern return continuation changed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Test CustodyTests::persistent_counter_boundaries_and_pending_completion() {
|
||||||
|
const auto restored_counter = [](const World& world, std::size_t counter, std::uint64_t value) {
|
||||||
|
std::ostringstream old, modern;
|
||||||
|
world.write_save(old, WorldSaveFormat::Current14); world.write_save(modern, WorldSaveFormat::Current15);
|
||||||
|
auto bytes = modern.str(); const auto offset = old.str().size() + counter * 8;
|
||||||
|
require(offset + 8 <= bytes.size(), "custody extension missing");
|
||||||
|
for (std::size_t i = 0; i < 8; ++i) bytes[offset + i] = static_cast<char>((value >> (i * 8)) & 255U);
|
||||||
|
std::istringstream input(bytes); return World::read_save(input, 1, ExecutionMode::SerialReference);
|
||||||
|
};
|
||||||
|
auto initial = cabin();
|
||||||
|
for (std::size_t counter = 0; counter < 3; ++counter) {
|
||||||
|
bool invalid = false; try { auto ignored = restored_counter(*initial, counter, 0); } catch (const std::runtime_error&) { invalid = true; }
|
||||||
|
require(invalid, "zero durable highwater accepted");
|
||||||
|
if (counter == 0) continue;
|
||||||
|
auto exhausted = restored_counter(*initial, counter, std::numeric_limits<std::uint64_t>::max());
|
||||||
|
ticks(*exhausted, 3);
|
||||||
|
require(!exhausted->agents()[0].execution && exhausted->custody_receipts().empty() &&
|
||||||
|
exhausted->storages()[0].items[0].reserved == 0, "exhausted admission acquired claims");
|
||||||
|
}
|
||||||
|
World saw(1, 10, 10, 1, ExecutionMode::SerialReference);
|
||||||
|
const auto store = saw.add_storage({2, 2}, 10); saw.stock_storage(store, ItemType::Wood, 1);
|
||||||
|
(void)saw.spawn_agent({3, 2}); saw.queue_production({3, 2}, RecipeId::SawPlank);
|
||||||
|
auto exhausted = restored_counter(saw, 0, std::numeric_limits<std::uint64_t>::max());
|
||||||
|
ticks(*exhausted, 12);
|
||||||
|
const auto& actor = exhausted->agents()[0];
|
||||||
|
require(actor.state == AgentState::Working && actor.work_remaining == 0 && actor.execution->blocked == CustodyStatus::Exhausted,
|
||||||
|
"completion did not preserve pending zero timer");
|
||||||
|
require(exhausted->storages()[0].item_count(ItemType::Wood) == 1 && exhausted->storages()[0].item_count(ItemType::Plank) == 0,
|
||||||
|
"refused completion partially consumed input");
|
||||||
|
const auto ordinal = actor.execution->next_operation;
|
||||||
|
ticks(*exhausted, 3);
|
||||||
|
require(actor.work_remaining == 0 && actor.execution->next_operation == ordinal + 3 && !exhausted->legacy_representable(),
|
||||||
|
"pending retry underflowed timer or reused ordinal");
|
||||||
|
std::ostringstream saved; exhausted->write_save(saved, WorldSaveFormat::Current15);
|
||||||
|
std::istringstream input(saved.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference);
|
||||||
|
ticks(*resumed, 1); require(resumed->agents()[0].work_remaining == 0, "restored pending completion decremented zero");
|
||||||
|
}
|
||||||
|
|
||||||
|
Test CustodyTests::resident_and_job_id_allocation_is_checked() {
|
||||||
|
const auto bytes = [](const World& world) { std::ostringstream stream; world.write_save(stream, WorldSaveFormat::Current15); return stream.str(); };
|
||||||
|
for (std::size_t kind = 0; kind < 2; ++kind) {
|
||||||
|
World empty(1, 10, 10, 1, ExecutionMode::SerialReference);
|
||||||
|
auto encoded = bytes(empty);
|
||||||
|
// Signature/version/seed/dimensions, five u64 counters, hunger flag.
|
||||||
|
const std::size_t offset = 28 + 5 * 8 + 1 + kind * 8;
|
||||||
|
for (std::size_t i = 0; i < 8; ++i) encoded[offset + i] = static_cast<char>(255);
|
||||||
|
std::istringstream input(encoded); auto restored = World::read_save(input, 1, ExecutionMode::SerialReference);
|
||||||
|
const auto before = bytes(*restored);
|
||||||
|
bool exhausted = false;
|
||||||
|
try { if (kind == 0) (void)restored->spawn_agent({1,1}); else (void)restored->add_job({1,1}, 1); }
|
||||||
|
catch (const std::overflow_error&) { exhausted = true; }
|
||||||
|
require(exhausted && bytes(*restored) == before, "exhausted resident/job allocation changed state");
|
||||||
|
for (std::size_t i = 0; i < 8; ++i) encoded[offset + i] = 0;
|
||||||
|
bool rejected = false; try { std::istringstream zero(encoded); auto ignored = World::read_save(zero,1,ExecutionMode::SerialReference); }
|
||||||
|
catch (const std::runtime_error&) { rejected = true; }
|
||||||
|
require(rejected, "zero resident/job counter accepted");
|
||||||
|
const auto valid_before = bytes(empty);
|
||||||
|
try { if (kind == 0) (void)empty.spawn_agent({-1,-1}); else (void)empty.add_job({1,1}, 0); }
|
||||||
|
catch (const std::invalid_argument&) {}
|
||||||
|
require(bytes(empty) == valid_before, "invalid insertion consumed ID");
|
||||||
|
}
|
||||||
|
World idle(1, 10, 10, 1, ExecutionMode::SerialReference); (void)idle.spawn_agent({1,1});
|
||||||
|
const_cast<Agent&>(idle.agents()[0]).work_remaining = 1;
|
||||||
|
bool rejected = false; try { idle.validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
|
||||||
|
require(rejected, "idle timer escaped phase validation");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -28,7 +28,7 @@ static_assert(!std::is_copy_constructible_v<World>);
|
|||||||
|
|
||||||
std::string bytes(const World& world) {
|
std::string bytes(const World& world) {
|
||||||
std::ostringstream stream(std::ios::binary);
|
std::ostringstream stream(std::ios::binary);
|
||||||
world.write_save(stream);
|
world.write_save(stream, WorldSaveFormat::Current15);
|
||||||
return stream.str();
|
return stream.str();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user