From 2017e5685a55bf6b6410a49f676637e887e3ef82 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Thu, 3 Dec 2026 00:04:09 +0300 Subject: [PATCH] fix(navigation): preserve work contacts beyond the current search window --- docs/agent-workflow/tasks/S03-01.md | 1 + docs/plan/systems/S03.md | 4 +++ engine/src/voxel_navigation.cpp | 32 +++++++++++++++----- tests/voxel_navigation_tests.cpp | 45 +++++++++++++++++++++++++++++ 4 files changed, 74 insertions(+), 8 deletions(-) diff --git a/docs/agent-workflow/tasks/S03-01.md b/docs/agent-workflow/tasks/S03-01.md index 9d61e12..6900e91 100644 --- a/docs/agent-workflow/tasks/S03-01.md +++ b/docs/agent-workflow/tasks/S03-01.md @@ -49,3 +49,4 @@ User requested all milestone/system coding, actual upstream library gaps and per 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. +Independent interaction clipping finding at `17389b2`: a known blocked list of in-window contacts does not prove a global negative when additional valid interaction candidates lie outside the finite window and the reached search frontier can leave it. Reproduce in a flat 8×8×4 fixture, start (1,1,1), search upper.x=4, target stone (3,3,1), blockers (2,3,2), (3,2,2), (3,4,2) and (3,3,3). With a reachable contact at (4,3,1) the narrow search returns SearchBoundary; upper.x=6 must reach it. Preserve all prior fixed direct-goal and unknown-frontier contracts. Include cases without any traversable exit and with an unavailable exit, freeze actual before/after code and run 13 previous focused cases, new regression and full CTest under the shared GUI lock. diff --git a/docs/plan/systems/S03.md b/docs/plan/systems/S03.md index 0cd158f..a747c4f 100644 --- a/docs/plan/systems/S03.md +++ b/docs/plan/systems/S03.md @@ -16,6 +16,8 @@ `find_voxel_interaction_path` строит доступные позиции контакта с указанной клеткой. К ней должна примыкать грань тела жителя. Цель может находиться у ног, у головы, под ногами или непосредственно над головой. Цель должна быть загружена. Право добывать материал, менять дверь и удалять опору проверяет владелец работы. Выбранная позиция взаимодействия и следующий переход доступны для повторной проверки перед действием. +Позиции контакта за пределами окна поиска сохраняются для проверки отрицательного ответа. Если такой контакт допускает размещение жителя, достигнутый допустимый выход из окна даёт `SearchBoundary`, а достигнутый неопределённый переход требует загрузки данных. При известном отсутствии выхода результат остаётся `Unreachable`. Заблокированные контакты внутри окна не доказывают недоступность всех внешних позиций. Общий предел целей учитывает и пропущенные контакты. + Каждый ответ содержит `VoxelReadSet` с ID региона, инкарнацией и упорядоченными уникальными ревизиями прочитанных чанков. В набор входят опора, свободное место над головой, заблокированные соседи и недоступные страницы. `current` проверяет тот же сеанс и все эти ревизии. Загрузка недоступной страницы делает прежний отрицательный ответ устаревшим. Правка непрочитанного чанка сохраняет ответ пригодным. Сам ответ и его маршрут удерживают собственные данные. Для замены локального набора библиотечным повторить проверки опоры через границу чанка, открытия прохода, загрузки страницы и смены инкарнации. [Void/Library #13](https://git.faumaray.com/Void/Library/issues/13) Найденный путь является кратчайшим среди известных переходов в заданном окне. Отрицательный ответ различает доказанную недоступность, недостающие данные и возможность выхода за границу окна. Отдельные результаты обозначают исчерпание бюджета, отмену, неверный запрос и отказ выделения памяти. До быстрого случая совпавших старта и цели проверяется геометрия тела. Применяющий результат код должен проверять и его статус, и актуальность набора чтений. @@ -32,6 +34,8 @@ Проверка замечаний к `7a7ff32` воспроизвела ожидание отсутствующей страницы под сплошным полом и исключение `vector::reserve` при непредставимой ёмкости. После исправления прошли 13 проверок навигации и четыре полных набора с 168 случаями ядра, 9 LAN, 14 клиента и испытанием кадра за 4,61 с. Отдельно проверены недоступная цель за известной стеной, загруженная цель взаимодействия за ней, запрещённый переход за границу окна и настоящий ожидающий загрузки проход. Один предыдущий полный прогон встретил прежнюю проверку немедленного допуска при восстановлении клиента после сбоя, `viewer_session_tests.cpp:363`. Повтор этого набора и итоговый полный прогон прошли. Проверяемый файл клиента в этом срезе не изменялся. +Проверка замечания к `17389b2` воспроизвела ложную недоступность при единственном пригодном контакте за границей окна. После исправления узкое окно возвращает `SearchBoundary`, расширенное достигает той же позиции контакта. Изолированный старт и незагруженный проход проверены отдельно. Под Wine прошли 14 проверок навигации и полный `ctest -V` с блокировкой общего интерактивного окружения. Все четыре набора прошли, включая 169 случаев ядра, 9 LAN, 14 клиента и испытание кадра за 4,74 с. + ## Пространственная модель Позицию и материал предоставляет [S02](S02.md). Профиль движения определяет объём тела, высоту шага и разрешённые переходы. Для M02 нужен профиль обычного поселенца, движение по опоре, ступеням и лестницам. Особые способы движения добавляются вместе с соответствующими животными и боевыми участниками. diff --git a/engine/src/voxel_navigation.cpp b/engine/src/voxel_navigation.cpp index b958e6d..39446e6 100644 --- a/engine/src/voxel_navigation.cpp +++ b/engine/src/voxel_navigation.cpp @@ -145,11 +145,14 @@ private: std::size_t sx_, sy_, count_; }; -VoxelPathResult search(Queries& queries, const VoxelPathRequest& request, std::span goals) { +VoxelPathResult search(Queries& queries, const VoxelPathRequest& request, + std::span goals, std::span omitted = {}) { VoxelPathResult result; - if (goals.empty()) return result; + if (goals.empty() && omitted.empty()) return result; const auto& limits = request.limits; - if (goals.size() > limits.max_goals) { result.status = Status::LimitExceeded; return result; } + if (omitted.size() > limits.max_goals || goals.size() > limits.max_goals - omitted.size()) { + result.status = Status::LimitExceeded; return result; + } for (auto goal : goals) if (!request.search_bounds.contains(goal)) return result; const auto sx = static_cast(request.search_bounds.upper.x - request.search_bounds.lower.x); const auto sy = static_cast(request.search_bounds.upper.y - request.search_bounds.lower.y); @@ -195,6 +198,13 @@ VoxelPathResult search(Queries& queries, const VoxelPathRequest& request, std::s (!result.goal || goal < *result.goal))) { distance = cost; result.goal = goal; } } if (!result.goal) { + // Interaction contacts outside the selected window still matter to a + // global negative. Their feasibility cannot manufacture a frontier; + // BFS must also have reached a valid exit or an unresolved transition. + for (auto goal : omitted) { + const auto standing = queries.standing(goal); + possible_goal = possible_goal || standing != Status::Unreachable; + } result.status = Status::Unreachable; if (possible_goal) { if (graph.unavailable) result.status = Status::Unavailable; @@ -247,16 +257,22 @@ VoxelPathResult path(const VoxelRegion& world, const VoxelPathRequest& request, result.status = cell.availability == VoxelAvailability::Unavailable ? Status::Unavailable : Status::InvalidInput; } else { std::array goals{}; - std::size_t size = 0; + std::array omitted{}; + std::size_t size = 0, omitted_size = 0; + const auto add_goal = [&](std::optional goal) { + if (!goal) return; + if (request.search_bounds.contains(*goal)) goals[size++] = *goal; + else omitted[omitted_size++] = *goal; + }; constexpr std::array, 4> directions{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}}; for (auto direction : directions) for (int dz : {-1, 0}) { - if (auto goal = offset(*target, direction[0], direction[1], dz); goal && request.search_bounds.contains(*goal)) goals[size++] = *goal; + add_goal(offset(*target, direction[0], direction[1], dz)); } for (int dz : {-2, 1}) { - if (auto goal = offset(*target, 0, 0, dz); goal && request.search_bounds.contains(*goal)) goals[size++] = *goal; + add_goal(offset(*target, 0, 0, dz)); } - if (size == 0) result.status = Status::SearchBoundary; - else result = search(queries, request, std::span(goals.data(), size)); + result = search(queries, request, std::span(goals.data(), size), + std::span(omitted.data(), omitted_size)); } } else result = search(queries, request, request.goals); } catch (const NavigationFailure& failure) { result.status = failure.status; } diff --git a/tests/voxel_navigation_tests.cpp b/tests/voxel_navigation_tests.cpp index 901836d..f31a83f 100644 --- a/tests/voxel_navigation_tests.cpp +++ b/tests/voxel_navigation_tests.cpp @@ -82,6 +82,7 @@ struct [[= Void::Testing::name("VoxelNavigationTests")]] VoxelNavigationTests : [[= 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 interaction_contacts_outside_window_need_frontier_evidence(); [[= 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(); @@ -218,6 +219,50 @@ Test VoxelNavigationTests::unrepresentable_vector_capacity_is_a_bounded_refusal( require(voxel_transition(world, epoch(), query.start, {2, 1, 1}, query.limits).status == Status::LimitExceeded, "unrepresentable read reserve escaped transition API"); } +Test VoxelNavigationTests::interaction_contacts_outside_window_need_frontier_evidence() { + auto world = flat(); + edit(world, {3, 3, 1}, MaterialId::Stone); + for (auto blocker : {VoxelPosition{2, 3, 2}, VoxelPosition{3, 2, 2}, VoxelPosition{3, 4, 2}, VoxelPosition{3, 3, 3}}) { + edit(world, blocker, MaterialId::Stone); + } + auto query = request(world, {1, 1, 1}, {}); + query.search_bounds.upper.x = 6; + auto complete = find_voxel_interaction_path(world, query, {3, 3, 1}); + require_route(world, query, complete); + require(complete.goal == VoxelPosition{4, 3, 1}, "expanded window did not reach sole valid contact"); + query.search_bounds.upper.x = 4; + require(find_voxel_interaction_path(world, query, {3, 3, 1}).status == Status::SearchBoundary, + "clipped valid interaction contact was classified globally unreachable"); + + // A valid omitted goal cannot manufacture an exit from an enclosed start. + for (auto p : {VoxelPosition{0, 1, 1}, VoxelPosition{1, 0, 1}, VoxelPosition{1, 2, 1}, VoxelPosition{2, 1, 1}}) { + edit(world, p, MaterialId::Stone); + edit(world, {p.x, p.y, 2}, MaterialId::Stone); + } + require(find_voxel_interaction_path(world, query, {3, 3, 1}).status == Status::Unreachable, + "omitted contact manufactured an escape from a known enclosed start"); + + // The only useful contact is beyond x=31, in an unavailable page. + VoxelRegion pending({1, 42, 1, {{0, 0, 0}, {40, 8, 4}}}); + install(pending, {0, 0, 0}, [](auto p) { + if (p.z == 0 || p == VoxelPosition{31, 3, 1}) return MaterialId::Stone; + if (p == VoxelPosition{30, 3, 2} || p == VoxelPosition{31, 2, 2} || + p == VoxelPosition{31, 4, 2} || p == VoxelPosition{31, 3, 3}) return MaterialId::Stone; + return MaterialId::Air; + }); + auto partial = request(pending, {29, 1, 1}, {}); + partial.search_bounds.upper.x = 32; + const auto waiting = find_voxel_interaction_path(pending, partial, {31, 3, 1}); + require(waiting.status == Status::Unavailable, "unresolved interaction exit was proven unreachable"); + install(pending, {1, 0, 0}, [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; }); + require(!waiting.consulted.current(pending, epoch()), "missing omitted contact was absent from dependencies"); + require(find_voxel_interaction_path(pending, partial, {31, 3, 1}).status == Status::SearchBoundary, + "loaded omitted contact failed to expose reachable window exit"); + partial.search_bounds.upper.x = 36; + auto reached = find_voxel_interaction_path(pending, partial, {31, 3, 1}); + require_route(pending, partial, reached); + require(reached.goal == VoxelPosition{32, 3, 1}, "expanded gateway did not expose actual contact"); +} 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}});