diff --git a/docs/agent-workflow/tasks/S03-01.md b/docs/agent-workflow/tasks/S03-01.md index 5213831..9d61e12 100644 --- a/docs/agent-workflow/tasks/S03-01.md +++ b/docs/agent-workflow/tasks/S03-01.md @@ -47,3 +47,5 @@ User requested all milestone/system coding, actual upstream library gaps and per ## 14. Return format Return S03-01 READY or PARTIAL, early stable interface for M02 owner, actual code/test limits, work bounds and cross-branch evidence including cross-boundary route/invalidation and distinct failure outcomes. + +Review at `7a7ff32` found a confirmed negative-result bug. On a solid, loaded z=0 floor a downward candidate may sample an unloaded z=-1 support while the known solid destination foot conclusively forbids the transition. A two-high closed wall then appears to be waiting for unrelated activation. Retain the actual sampled stamps but classify missing data as a potential frontier only if the corresponding transition, standing goal or reachable continuation cannot already be ruled out. Add the walled-floor regression and a positive genuinely unavailable frontier. Check analogous search-boundary handling and real interaction targets. Keep the existing signature and scoped files. diff --git a/docs/plan/systems/S03.md b/docs/plan/systems/S03.md index df172c6..0cd158f 100644 --- a/docs/plan/systems/S03.md +++ b/docs/plan/systems/S03.md @@ -20,12 +20,18 @@ Найденный путь является кратчайшим среди известных переходов в заданном окне. Отрицательный ответ различает доказанную недоступность, недостающие данные и возможность выхода за границу окна. Отдельные результаты обозначают исчерпание бюджета, отмену, неверный запрос и отказ выделения памяти. До быстрого случая совпавших старта и цели проверяется геометрия тела. Применяющий результат код должен проверять и его статус, и актуальность набора чтений. +Недостающие данные требуют ожидания, когда они могут продолжить путь из уже достигнутой позиции. Известная сплошная стена или занятая клетка ног окончательно запрещает переход, даже если его проверка прочитала недоступную опору. Прочитанные ревизии сохраняются в ответе. Недоступная цель за доказанно непроходимой стеной сама по себе не создаёт достижимый проход. Выход за окно учитывается после проверки допустимого перехода через его границу. + Пределы по умолчанию составляют 65 536 вершин, 1 000 000 шагов алгоритма, 4 000 000 чтений клеток, 64 цели, 4096 ревизий и 8 МиБ рабочих данных. Бюджет учитывает четыре массива `size_t` и посещённость из Void BFS, собираемый маршрут и зарезервированный набор ревизий. Список соседей из 12 элементов находится в стеке. Владелец сохраняет входные данные запроса и страницы мира отдельно. Измерение памяти распределителя и принудительный отказ системного распределителя остаются отдельными проверками. +Ёмкости проверяются также против `vector::max_size()`. Непредставимая ёмкость возвращает `LimitExceeded` через каждую из четырёх публичных операций. Проверка с `max_dependencies = max_size() + 1` и максимальным байтовым бюджетом воспроизводит этот отказ без выделения указанной памяти. + Селектор `--tag voxel-navigation` проверяет двухклеточную дверь, ступени на границе `x=31/32` и работу наверху, удаление следующей опоры, прежний неизменяемый снимок, место для головы, недоступную опору через отрицательную границу по высоте, постороннюю правку, смену сеанса и предельные координаты. Стоимости сравниваются с независимым полным обходом 16 малых плоских карт. Запросы в настоящем пуле с 2, 6 и 12 потоками дают те же маршруты и ревизии. [Проверки](../../../tests/voxel_navigation_tests.cpp) На совместной базе S02 `e7046a9` сборка Windows x64 GCC 16.2 и все десять проверок навигации прошли под Wine 11. Полный `ctest -V` прошёл четыре набора с 165 случаями ядра, 9 LAN, 14 клиента и испытанием кадра с видимой цепочкой D3D11 и WARP. Проверка заняла 4,66 с. Нативная Windows и связь навигации с исполнением работ в `World` проверяются при последующей интеграции M02. +Проверка замечаний к `7a7ff32` воспроизвела ожидание отсутствующей страницы под сплошным полом и исключение `vector::reserve` при непредставимой ёмкости. После исправления прошли 13 проверок навигации и четыре полных набора с 168 случаями ядра, 9 LAN, 14 клиента и испытанием кадра за 4,61 с. Отдельно проверены недоступная цель за известной стеной, загруженная цель взаимодействия за ней, запрещённый переход за границу окна и настоящий ожидающий загрузки проход. Один предыдущий полный прогон встретил прежнюю проверку немедленного допуска при восстановлении клиента после сбоя, `viewer_session_tests.cpp:363`. Повтор этого набора и итоговый полный прогон прошли. Проверяемый файл клиента в этом срезе не изменялся. + ## Пространственная модель Позицию и материал предоставляет [S02](S02.md). Профиль движения определяет объём тела, высоту шага и разрешённые переходы. Для M02 нужен профиль обычного поселенца, движение по опоре, ступеням и лестницам. Особые способы движения добавляются вместе с соответствующими животными и боевыми участниками. diff --git a/engine/src/voxel_navigation.cpp b/engine/src/voxel_navigation.cpp index cd7bf0f..b958e6d 100644 --- a/engine/src/voxel_navigation.cpp +++ b/engine/src/voxel_navigation.cpp @@ -6,6 +6,7 @@ #include #include #include +#include namespace settlement { namespace { @@ -32,6 +33,7 @@ public: VoxelNavigationLimits limits, std::stop_token stop) : world_(world), limits_(limits), stop_(stop), reads{world.descriptor().id, session, {}} { if (session.is_nil()) throw NavigationFailure{Status::InvalidInput}; + if (limits.max_dependencies > reads.chunks.max_size()) throw NavigationFailure{Status::LimitExceeded}; const auto bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp)); if (!bytes || *bytes > limits.max_scratch_bytes) throw NavigationFailure{Status::LimitExceeded}; reads.chunks.reserve(limits.max_dependencies); @@ -48,7 +50,6 @@ public: if (reads.chunks.size() == limits_.max_dependencies) throw NavigationFailure{Status::LimitExceeded}; reads.chunks.insert(at, value.stamp); } - unavailable = unavailable || value.availability == VoxelAvailability::Unavailable; return value; } @@ -91,7 +92,6 @@ public: VoxelNavigationLimits limits_; std::stop_token stop_; VoxelReadSet reads; - bool unavailable = false; private: std::size_t samples_ = 0; }; @@ -127,6 +127,10 @@ public: const auto to = offset(from, direction[0], direction[1], dz); if (!to) continue; const auto state = queries_.transition(from, *to); + // Only inconclusive edges out of reached vertices can extend the + // search into missing data. Raw reads may already have been ruled + // out by a known wall, floor or obstructed swept body volume. + if (state == Status::Unavailable) unavailable = true; if (state != Status::Reachable) continue; if (!bounds_.contains(*to)) { boundary = true; continue; } result.values[result.size++] = index(*to); @@ -134,6 +138,7 @@ public: return result; } mutable bool boundary = false; + mutable bool unavailable = false; private: Queries& queries_; VoxelBounds bounds_; @@ -157,7 +162,10 @@ VoxelPathResult search(Queries& queries, const VoxelPathRequest& request, std::s return Void::Numeric::checked_mul(size, 4 * sizeof(std::size_t) + 1 + sizeof(VoxelPosition)); }); const auto read_bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp)); - if (!count || *count > limits.max_vertices || !vertex_bytes || !read_bytes) { + if (!count || *count > limits.max_vertices || !vertex_bytes || !read_bytes || + *count > std::vector{}.max_size() || + *count > std::vector{}.max_size() || + *count > std::vector{}.max_size()) { result.status = Status::LimitExceeded; return result; } const auto bytes = Void::Numeric::checked_add(*vertex_bytes, *read_bytes); @@ -176,15 +184,22 @@ VoxelPathResult search(Queries& queries, const VoxelPathRequest& request, std::s } result.visited = traversal->order.size(); std::size_t distance = Void::Algorithms::TraversalResult::npos; + bool possible_goal = false; for (auto goal : goals) { // Explicit validation also covers the library's start==target fast path. - if (queries.standing(goal) != Status::Reachable) continue; + const auto standing = queries.standing(goal); + possible_goal = possible_goal || standing != Status::Unreachable; + if (standing != Status::Reachable) continue; const auto cost = traversal->depth[graph.index(goal)]; if (cost < distance || (cost == distance && cost != Void::Algorithms::TraversalResult::npos && (!result.goal || goal < *result.goal))) { distance = cost; result.goal = goal; } } if (!result.goal) { - result.status = queries.unavailable ? Status::Unavailable : (graph.boundary ? Status::SearchBoundary : Status::Unreachable); + result.status = Status::Unreachable; + if (possible_goal) { + if (graph.unavailable) result.status = Status::Unavailable; + else if (graph.boundary) result.status = Status::SearchBoundary; + } return result; } result.status = Status::Reachable; @@ -211,6 +226,7 @@ VoxelTraversalResult check(const VoxelRegion& world, const Void::Uuid::Uuid& ses catch (const NavigationFailure& failure) { result.status = failure.status; } result.consulted = std::move(queries.reads); } catch (const NavigationFailure& failure) { result.status = failure.status; } + catch (const std::length_error&) { result.status = Status::LimitExceeded; } catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; } return result; } @@ -246,6 +262,7 @@ VoxelPathResult path(const VoxelRegion& world, const VoxelPathRequest& request, } catch (const NavigationFailure& failure) { result.status = failure.status; } result.consulted = std::move(queries.reads); } catch (const NavigationFailure& failure) { result.status = failure.status; } + catch (const std::length_error&) { result.status = Status::LimitExceeded; } catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; } return result; } diff --git a/tests/voxel_navigation_tests.cpp b/tests/voxel_navigation_tests.cpp index 3aa0142..901836d 100644 --- a/tests/voxel_navigation_tests.cpp +++ b/tests/voxel_navigation_tests.cpp @@ -79,6 +79,9 @@ struct [[= Void::Testing::name("VoxelNavigationTests")]] VoxelNavigationTests : [[= Void::Testing::tag("voxel-navigation")]] Test support_edit_invalidates_route_before_next_step(); [[= Void::Testing::tag("voxel-navigation")]] Test body_headroom_and_step_sweep_are_required(); [[= Void::Testing::tag("voxel-navigation")]] Test missing_support_page_and_negative_answer_are_dependencies(); + [[= Void::Testing::tag("voxel-navigation")]] Test known_blockers_do_not_require_unrelated_missing_data(); + [[= Void::Testing::tag("voxel-navigation")]] Test reachable_missing_frontier_waits_for_actual_gateway(); + [[= Void::Testing::tag("voxel-navigation")]] Test unrepresentable_vector_capacity_is_a_bounded_refusal(); [[= Void::Testing::tag("voxel-navigation")]] Test unchanged_chunks_and_old_snapshots_remain_usable(); [[= Void::Testing::tag("voxel-navigation")]] Test bounded_search_has_distinct_incomplete_and_error_results(); [[= Void::Testing::tag("voxel-navigation")]] Test invalid_same_goal_and_extreme_coordinate_windows(); @@ -151,6 +154,70 @@ Test VoxelNavigationTests::missing_support_page_and_negative_answer_are_dependen require(!negative.consulted.current(world, epoch()), "negative path omitted queried missing chunk"); require_route(world, query, find_voxel_path(world, query)); } +Test VoxelNavigationTests::known_blockers_do_not_require_unrelated_missing_data() { + VoxelRegion world({1, 42, 1, {{0, 0, -1}, {64, 8, 4}}}); + install(world, {0, 0, 0}, [](auto p) { + return p.z == 0 || (p.x == 2 && p.z <= 2) ? MaterialId::Stone : MaterialId::Air; + }); + auto query = request(world, {1, 1, 1}, {{5, 5, 1}}); + auto result = find_voxel_path(world, query); + require(result.status == Status::Unreachable, "solid floor and closed wall unnecessarily wait for missing lower page"); + require(find_voxel_interaction_path(world, query, {5, 5, 1}).status == Status::Unreachable, + "loaded interaction behind known wall unnecessarily waits for missing lower page"); + require(std::any_of(result.consulted.chunks.begin(), result.consulted.chunks.end(), [](const auto& s) { + return s.coordinate == ChunkCoordinate{0, 0, -1} && s.availability == VoxelAvailability::Unavailable; + }), "conclusively blocked reads lost their actual dependency stamps"); + query.goals = {{35, 5, 1}}; + result = find_voxel_path(world, query); + require(result.status == Status::Unreachable, "disconnected unknown goal manufactured reachable frontier"); + require(std::any_of(result.consulted.chunks.begin(), result.consulted.chunks.end(), [](const auto& s) { + return s.coordinate == ChunkCoordinate{1, 0, 0} && s.availability == VoxelAvailability::Unavailable; + }), "unknown goal reads were not retained"); + query.goals = {{5, 5, 1}}; + query.search_bounds.upper = {8, 6, 4}; + require(find_voxel_path(world, query).status == Status::SearchBoundary, + "actual reachable window exit was replaced by irrelevant missing data"); + install(world, {0, 0, -1}, [](auto) { return MaterialId::Stone; }); + query.search_bounds = world.descriptor().bounds; + require(find_voxel_path(world, query).status == Status::Unreachable, + "lower-page activation changed proven blocked reachability"); + for (int x : {0, 1}) for (int z : {1, 2}) edit(world, {x, 3, z}, MaterialId::Stone); + query.goals = {{1, 5, 1}}; + query.search_bounds.upper.x = 2; + require(find_voxel_path(world, query).status == Status::Unreachable, + "known blocked transitions beyond search window manufactured an exit"); +} +Test VoxelNavigationTests::reachable_missing_frontier_waits_for_actual_gateway() { + VoxelRegion world({1, 42, 1, {{0, 0, -1}, {64, 8, 4}}}); + const auto floor = [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; }; + install(world, {0, 0, 0}, floor); + auto blocked_goal = request(world, {1, 1, 1}, {{5, 5, 1}}); + edit(world, {5, 5, 2}, MaterialId::Stone); + require(find_voxel_path(world, blocked_goal).status == Status::Unreachable, + "missing branch elsewhere manufactured access to conclusively blocked goal"); + edit(world, {5, 5, 2}, MaterialId::Air); + auto query = request(world, {1, 1, 1}, {{35, 5, 1}}); + auto pending = find_voxel_path(world, query); + require(pending.status == Status::Unavailable, "reachable missing gateway was proven unreachable"); + install(world, {1, 0, 0}, floor); + require(!pending.consulted.current(world, epoch()), "gateway activation did not invalidate pending answer"); + auto result = find_voxel_path(world, query); + require_route(world, query, result); + require(result.cost == 38, "loaded gateway changed shortest path cost"); +} +Test VoxelNavigationTests::unrepresentable_vector_capacity_is_a_bounded_refusal() { + auto world = flat(); + auto query = request(world, {1, 1, 1}, {{5, 5, 1}}); + query.limits.max_dependencies = std::vector{}.max_size() + 1; + query.limits.max_scratch_bytes = std::numeric_limits::max(); + require(find_voxel_path(world, query).status == Status::LimitExceeded, "unrepresentable read reserve escaped path API"); + require(find_voxel_interaction_path(world, query, {5, 5, 1}).status == Status::LimitExceeded, + "unrepresentable read reserve escaped interaction API"); + require(voxel_standing(world, epoch(), query.start, query.limits).status == Status::LimitExceeded, + "unrepresentable read reserve escaped stance API"); + require(voxel_transition(world, epoch(), query.start, {2, 1, 1}, query.limits).status == Status::LimitExceeded, + "unrepresentable read reserve escaped transition API"); +} Test VoxelNavigationTests::unchanged_chunks_and_old_snapshots_remain_usable() { auto world = flat({{0, 0, 0}, {100, 8, 4}}); auto query = request(world, {1, 1, 1}, {{5, 5, 1}});