diff --git a/backends/osmand/CMakeLists.txt b/backends/osmand/CMakeLists.txt index f8debcf..bc5c84a 100644 --- a/backends/osmand/CMakeLists.txt +++ b/backends/osmand/CMakeLists.txt @@ -153,3 +153,15 @@ target_link_options(route_bench PRIVATE -static-libstdc++ -static-libgcc -Wl,-Bs add_executable(route_bench_run ${ONC_ROOT}/deploy/bench/route_bench_run.c) target_link_libraries(route_bench_run PRIVATE c) set_target_properties(route_bench_run PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bench) + +# Full worker diagnostic: queueing, routing and OM turns. +add_library(route_worker_bench SHARED ${ONC_ROOT}/deploy/bench/route_worker_bench.cpp + navigation_worker.cpp ch_planner.cpp route_maneuvers.cpp config.cpp) +target_include_directories(route_worker_bench PRIVATE ${ONC_OSMAND_INCLUDES}) +target_compile_definitions(route_worker_bench PRIVATE ${ONC_OSMAND_DEFINES} ONC_ROUTE_DIAGNOSTICS) +target_compile_options(route_worker_bench PRIVATE ${ONC_WARNINGS} ${ONC_OSMAND_FLAGS}) +target_link_libraries(route_worker_bench PRIVATE navigation_ui organicmaps_turns osmand_core m c) +set_target_properties(route_worker_bench PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bench + SKIP_BUILD_RPATH ON) +target_link_options(route_worker_bench PRIVATE -static-libstdc++ -static-libgcc -Wl,-Bsymbolic + -Wl,-rpath,/open-navicore -Wl,--no-undefined) diff --git a/backends/osmand/ch_planner.cpp b/backends/osmand/ch_planner.cpp index d8e09b0..1d2af71 100644 --- a/backends/osmand/ch_planner.cpp +++ b/backends/osmand/ch_planner.cpp @@ -1,6 +1,7 @@ #include "ch_planner.h" #include "ch/ch_sidecar.h" +#include "snap_policy.h" #include "binaryRoutePlanner.h" #include "generalRouter.h" @@ -13,6 +14,7 @@ #include #include #include +#include #include #include @@ -42,7 +44,6 @@ constexpr double kSnapMsPerMetre = 120.0; // the distance to the road, as t constexpr double kReversePenaltyMs = 60000.0; // starting against the car's heading constexpr double kMaxSnapMetres = 1000.0; constexpr double kMaxApproachMetres = 5000.0; // along a road to its first junction -constexpr std::size_t kSnapRoads = 8; // nearest roads tried at each end double metres_between(int x1, int y1, int x2, int y2) { @@ -76,7 +77,6 @@ std::vector snap_roads(RoutingContext* context, int x, int y) points.insert(points.end(), nearest->others.begin(), nearest->others.end()); const auto& router = context->config->router; for (const auto& point : points) { - if (snaps.size() >= kSnapRoads) break; if (!point || !point->road || !router->acceptLine(point->road)) continue; RoadSnap snap; snap.road = point->road; @@ -91,6 +91,13 @@ std::vector snap_roads(RoutingContext* context, int x, int y) continue; snaps.push_back(snap); } + keep_nearest_roads(snaps); +#ifdef ONC_ROUTE_DIAGNOSTICS + // Causal probe for the route survey, never compiled into the backend. + const char* nearest_only = std::getenv("ROUTE_BENCH_NEAREST_ONLY"); + if (nearest_only && std::strcmp(nearest_only, "1") == 0 && snaps.size() > 1) + snaps.resize(1); +#endif return snaps; } @@ -283,7 +290,7 @@ std::string ChPlanner::describe() const { return impl_->description; } ChPlanner::Segments ChPlanner::route(RoutePlannerFrontEnd& front_end, const SHARED_PTR& context, int start_x, int start_y, int end_x, int end_y, std::string& why, - double start_heading_degrees) + double start_heading_degrees, RouteRoads* roads) { timing_ = Timing(); why.clear(); @@ -310,6 +317,23 @@ ChPlanner::Segments ChPlanner::route(RoutePlannerFrontEnd& front_end, const SHAR } timing_.snap_ms = ms_since(step); +#ifdef ONC_ROUTE_DIAGNOSTICS + // Standalone route survey only; absent from the installed backend. + std::size_t start_nodes = 0, end_nodes = 0; + for (const auto& approach : starts) start_nodes += approach.nodes.size(); + for (const auto& approach : ends) end_nodes += approach.nodes.size(); + std::fprintf(stderr, "ch_diag start_roads=%zu end_roads=%zu start_approaches=%zu end_approaches=%zu " + "start_nodes=%zu end_nodes=%zu direct=%d snap_ms=%.1f\n", from_roads.size(), to_roads.size(), + starts.size(), ends.size(), start_nodes, end_nodes, has_direct ? 1 : 0, timing_.snap_ms); + const auto print_snaps = [](const char* side, const std::vector& snaps) { + for (const auto& snap : snaps) + std::fprintf(stderr, "ch_snap side=%s road=%lld gap_m=%.2f lo=%d hi=%d oneway=%d\n", + side, static_cast(snap.road->getId()), snap.metres, snap.lo, snap.hi, snap.oneway); + }; + print_snaps("start", from_roads); + print_snaps("end", to_roads); +#endif + std::vector runs; onc_ch::u32 cost = 0; const Approach* first = nullptr; @@ -354,23 +378,42 @@ ChPlanner::Segments ChPlanner::route(RoutePlannerFrontEnd& front_end, const SHAR } else if (has_direct) { use_direct = true; } else { - // No road near enough to snap onto: the nearest junctions, as before. - step = Clock::now(); - const auto status = impl_->router->route(start_x, start_y, end_x, end_y, runs, cost, - start_heading_degrees, cancelled); - timing_.search_ms = ms_since(step); - timing_.settled = impl_->router->settled(); - if (status == onc_ch::Router::Status::NoRoute) { why = "no_route_in_sidecar"; return {}; } - if (status == onc_ch::Router::Status::Inconsistent) { why = "sidecar_inconsistent"; return {}; } - if (status == onc_ch::Router::Status::Cancelled) { why = "cancelled"; return {}; } - if (runs.empty()) { why = "too_short_for_sidecar"; return {}; } + // Do not silently bypass the selected endpoint road with a nearby node. + why = from_roads.empty() ? "no_start_road" : to_roads.empty() ? "no_destination_road" : + starts.empty() ? "start_road_not_connected" : "destination_road_not_connected"; + return {}; } timing_.base_edges = use_direct ? 0 : impl_->router->edges().size(); timing_.road_runs = use_direct ? 0 : runs.size(); Segments results; + // Capture adjacent roads as geometry is loaded in travel order. OsmAnd's + // prepareResult and OM can then share that snapshot instead of decoding + // the same long route's evicted tiles on two further passes. + const auto append = [&](const SHARED_PTR& road, int start, int end) { + auto result = std::make_shared(road, start, end); + if (roads) { + const int direction = start <= end ? 1 : -1; + result->preAttachedRoutes.reserve(std::abs(end - start) + 1); + for (int i = start;; i += direction) { + const auto key = route_node_key(road->pointsX[i], road->pointsY[i]); + auto found = roads->find(key); + if (found == roads->end()) { + std::vector> adjacent; + for (const auto& segment : context->loadRouteSegment(road->pointsX[i], road->pointsY[i])) { + if (segment) adjacent.push_back(std::make_shared( + segment->getRoad(), segment->getSegmentStart(), segment->getSegmentStart())); + } + found = roads->emplace(key, std::move(adjacent)).first; + } + result->preAttachedRoutes.push_back(found->second); + if (i == end) break; + } + } + results.push_back(std::move(result)); + }; if (use_direct) { - results.push_back(std::make_shared(direct.road, direct.start, direct.end)); + append(direct.road, direct.start, direct.end); timing_.direct = true; } else { // Each stretch needs its RouteDataObject: loading the tile at a point of the road @@ -378,8 +421,9 @@ ChPlanner::Segments ChPlanner::route(RoutePlannerFrontEnd& front_end, const SHAR step = Clock::now(); results.reserve(runs.size() + 2); if (first && first->start != first->end) - results.push_back(std::make_shared(first->road, first->start, first->end)); + append(first->road, first->start, first->end); for (const onc_ch::RoadRun& run : runs) { + if (cancelled()) { why = "cancelled"; return {}; } SHARED_PTR road; for (const auto& segment : context->loadRouteSegment(run.anchor_x, run.anchor_y)) { if (segment && segment->getRoad()->getId() == run.road) { @@ -389,13 +433,17 @@ ChPlanner::Segments ChPlanner::route(RoutePlannerFrontEnd& front_end, const SHAR } const int points = road ? static_cast(road->pointsX.size()) : 0; if (!road || run.start < 0 || run.end < 0 || run.start >= points || run.end >= points) { +#ifdef ONC_ROUTE_DIAGNOSTICS + std::fprintf(stderr, "ch_diag missing_road=%lld from=%d to=%d points=%d anchor=%d,%d\n", + static_cast(run.road), run.start, run.end, points, run.anchor_x, run.anchor_y); +#endif why = "road_missing_in_maps"; return {}; } - results.push_back(std::make_shared(road, run.start, run.end)); + append(road, run.start, run.end); } if (last && last->start != last->end) - results.push_back(std::make_shared(last->road, last->start, last->end)); + append(last->road, last->start, last->end); timing_.roads_ms = ms_since(step); if (results.empty()) { why = "too_short_for_sidecar"; return {}; } } @@ -403,6 +451,16 @@ ChPlanner::Segments ChPlanner::route(RoutePlannerFrontEnd& front_end, const SHAR step = Clock::now(); prepareResult(context.get(), results); front_end.makeStartEndPointsPrecise(context.get(), results, start_x, start_y, end_x, end_y); +#ifdef ONC_ROUTE_DIAGNOSTICS + if (!results.empty()) { + const auto& first_result = results.front(); + const auto& last_result = results.back(); + std::fprintf(stderr, "ch_selected start_road=%lld end_road=%lld start_index=%d end_index=%d direct=%d\n", + static_cast(first_result->object->getId()), + static_cast(last_result->object->getId()), first_result->getStartPointIndex(), + last_result->getEndPointIndex(), use_direct ? 1 : 0); + } +#endif timing_.prepare_ms = ms_since(step); return results; } diff --git a/backends/osmand/ch_planner.h b/backends/osmand/ch_planner.h index fcfe6e5..adbd924 100644 --- a/backends/osmand/ch_planner.h +++ b/backends/osmand/ch_planner.h @@ -3,6 +3,7 @@ #include #include #include +#include "route_roads.h" // Core and core-legacy both ship a Logging.h with the same public names but // different include guards. The provider uses Core's logger consistently. @@ -19,8 +20,8 @@ namespace navicore_osmand { // Routes with a contraction hierarchy built offline from the same OBF maps (a // "sidecar", tools/ch) and hands the result to the core's own result // preparation, so turn instructions, street names and attached roads are -// exactly what the A* and HH routers give. The search itself takes well under -// a millisecond; what remains is loading the route's roads from the maps. +// exactly what the A* and HH routers give. Search, geometry loading and result preparation are measured separately; +// long routes are dominated by map loading and turn preparation. class ChPlanner { public: using Segments = std::vector>; @@ -28,18 +29,18 @@ class ChPlanner { struct Timing { double snap_ms = 0; // start/end onto roads, along them to junctions double search_ms = 0; // hierarchy query, unpack - double roads_ms = 0; // load the route's roads from the maps + double roads_ms = 0; // load route roads and optional junction snapshots double prepare_ms = 0; // prepareResult + makeStartEndPointsPrecise std::size_t road_runs = 0; std::size_t base_edges = 0; std::size_t settled = 0; - bool road_snap = false; // snapped onto roads (else to the nearest junctions) + bool road_snap = false; // selected endpoint roads connected to the hierarchy bool direct = false; // start and end on one road: no hierarchy needed }; // Maps the sidecar and checks it was built from exactly these map files // (same names and sizes, whatever the order). On failure returns null and - // says why in `error`; the caller then routes without it. + // says why in `error`; the caller reports that its selected router is unavailable. static std::unique_ptr open(const std::string& sidecar_path, const std::vector& routable_maps, std::string& error); @@ -48,12 +49,12 @@ class ChPlanner { // The fastest route between two points (31-bit tile numbers), or empty // when the sidecar cannot serve it (a point too far from every road, // start and end on one road node, a road missing from the loaded maps); - // `why` then names the reason and the caller falls back to HH or A*. + // `why` then names the reason; the caller reports failure. // start_heading_degrees: the car's direction (clockwise from north), or // negative when unknown; start nodes behind it cost a reverse penalty. Segments route(RoutePlannerFrontEnd& front_end, const SHARED_PTR& context, int start_x, int start_y, int end_x, int end_y, std::string& why, - double start_heading_degrees = -1.0); + double start_heading_degrees = -1.0, RouteRoads* roads = nullptr); const Timing& last_timing() const { return timing_; } // One-line description for the log: nodes, edges, maps. diff --git a/backends/osmand/config.h b/backends/osmand/config.h index 0cbb728..678346c 100644 --- a/backends/osmand/config.h +++ b/backends/osmand/config.h @@ -31,9 +31,11 @@ struct Config { std::string vector_cache = "/datastore/navicore-backend/vectorcache"; // Contraction-hierarchy routing sidecar built from the maps (tools/ch): // "car.chr" in the map directory, or ".chr" next to a single - // map file. Routing falls back to HH and A* when it is absent, stale or - // cannot serve a route. Empty when disabled (marker - // /datastore/navicore-backend/disable-ch, or OPEN_NAVICORE_OSMAND_CH_DISABLE=1). + // map file. A configured sidecar that is absent, stale or cannot serve a + // route reports failure. Empty explicitly selects HH (or A* for maps + // without HH data); the routers never retry each other's failures. Disabled by + // the marker + // /datastore/navicore-backend/disable-ch, or OPEN_NAVICORE_OSMAND_CH_DISABLE=1. std::string ch_sidecar = ""; // Turn instructions come from Organic Maps' turn generator (omaps_turns.h). // OsmAnd's own only with the marker /datastore/navicore-backend/osmand-turns diff --git a/backends/osmand/navigation_worker.cpp b/backends/osmand/navigation_worker.cpp index cdc80b0..768cb95 100644 --- a/backends/osmand/navigation_worker.cpp +++ b/backends/osmand/navigation_worker.cpp @@ -18,16 +18,15 @@ #include #include #include -#include #include #include -#include #include // Core and core-legacy both ship a Logging.h with the same public names but // different include guards. The provider uses Core's logger consistently. #define _OSMAND_LOGGING_H_ #include "binaryRead.h" +#include "binaryRoutePlanner.h" #include "commonOsmAndCore.h" #include "hhRouteDataStructure.h" #include "hhRoutePlanner.h" @@ -375,26 +374,6 @@ class NavigationWorker::Impl { condition_.notify_one(); } - void submit_address(std::uint64_t revision, ui::GeoPoint point) - { - std::lock_guard lock(mutex_); - if (stopping_) return; - if (active_) active_->cancel(); - pending_ = Request::address(revision, point); - has_pending_ = true; - trace_result("worker=address_queued", revision, 1u); - condition_.notify_one(); - } - - bool take(AddressResult& output) - { - std::lock_guard lock(mutex_); - if (!has_address_result_) return false; - output = std::move(address_result_); - has_address_result_ = false; - return true; - } - bool take(SearchResult& output) { std::lock_guard lock(mutex_); @@ -434,7 +413,8 @@ class NavigationWorker::Impl { private: struct Request { - enum class Kind { Search, Route, Address } kind = Kind::Search; + enum class Kind { Search, Route } kind = Kind::Search; + std::chrono::steady_clock::time_point queued = std::chrono::steady_clock::now(); std::uint64_t revision = 0; std::string query; ui::Destination destination; @@ -462,37 +442,8 @@ class NavigationWorker::Impl { request.origin = origin; return request; } - static Request address(std::uint64_t revision, ui::GeoPoint point) - { - Request request; - request.kind = Kind::Address; - request.revision = revision; - request.origin = point; - return request; - } }; - // Nearest address of a point: "street, house number", or the street - // alone; empty when there is no road nearby. - std::string address(const Request& request) - { - if (!road_locator_) - road_locator_ = std::make_shared(obfs_); - OsmAnd::ReverseGeocoder geocoder(obfs_, road_locator_); - OsmAnd::ReverseGeocoder::Criteria criteria; - criteria.latLon = OsmAnd::LatLon(request.origin.latitude, request.origin.longitude); - const auto entry = geocoder.performSearch(criteria); - if (!entry) return {}; - const auto name = [](const OsmAnd::Address& address) { return localized_name(address); }; - std::string street = entry->street ? name(*entry->street) : utf8(entry->streetName); - if (street.empty()) return {}; - if (entry->building) { - const std::string number = name(*entry->building); - if (!number.empty()) street += ", " + number; - } - return street; - } - std::vector search(const Request& request, const std::shared_ptr& cancel) { @@ -650,10 +601,25 @@ class NavigationWorker::Impl { return true; } - bool accept_route(const Segments& segments, const char* which) + bool accept_route(const Segments& segments, const char* which, int sx, int sy, int ex, int ey, + double start_limit = 1000.0, double end_limit = 1000.0) { const RouteCheck check = check_segments(segments); - if (check.ok()) return true; + if (check.ok()) { + double length = 0; + for (const auto& segment : segments) if (segment) length += segment->distance; + const auto start = segments.front()->getStartPoint(); + const auto end = segments.back()->getEndPoint(); + const auto extent = check_route_extent({get31LatitudeY(sy), get31LongitudeX(sx)}, + {get31LatitudeY(ey), get31LongitudeX(ex)}, {start.lat, start.lon}, {end.lat, end.lon}, length, start_limit, end_limit); + if (extent.usable) return true; + char line[192]; + std::snprintf(line, sizeof(line), "worker=route_rejected route=%s why=invalid_extent " + "length_m=%.1f start_gap_m=%.1f end_gap_m=%.1f", which, length, + extent.start_gap_metres, extent.end_gap_metres); + trace(line); + return false; + } char line[160]; std::snprintf(line, sizeof(line), "worker=route_rejected route=%s why=straight_legs legs=%zu filler=%zu gaps=%zu " @@ -672,6 +638,27 @@ class NavigationWorker::Impl { int sx, int sy, int ex, int ey, bool alternatives) { std::vector routes; + // HH may silently choose a connected road farther away than the pin's + // own road. Bound its output by the actual nearest eligible road, too. + const auto snap_limit = [&](int x, int y) { + auto nearest = findRouteSegment(x, y, context.get()); + if (!nearest) return -1.0; + auto candidates = nearest->others; + candidates.push_back(nearest); + double gap = 1001.0; + for (const auto& point : candidates) { + if (point && point->road && context->config->router->acceptLine(point->road)) + gap = std::min(gap, measuredDist31(x, y, point->preciseX, point->preciseY)); + } + // Projection and geographic-distance helpers differ slightly. + return gap > 1000.0 ? -1.0 : std::min(1000.0, gap + 3.0); + }; + const double start_limit = snap_limit(sx, sy), end_limit = snap_limit(ex, ey); + if (start_limit < 0 || end_limit < 0) { + trace(start_limit < 0 ? "worker=hh_rejected why=no_start_road" : + "worker=hh_rejected why=no_destination_road"); + return routes; + } std::unique_ptr config(HHRoutingConfig::astar(0)); config->calcDetailed(HHRoutingConfig::CALCULATE_ALL_DETAILED); if (alternatives) config->calcAlternative(); @@ -699,15 +686,15 @@ class NavigationWorker::Impl { front_end.makeStartEndPointsPrecise(context.get(), main->detailed, sx, sy, ex, ey); // Where a leg's road geometry could not be loaded the core joins the // network nodes with a straight line; such a route crosses water and - // forest. A bad main route fails HH (the caller runs A*); a bad + // forest. A bad main route fails the request; a bad // alternative is dropped. - if (!accept_route(main->detailed, "main")) return routes; + if (!accept_route(main->detailed, "main", sx, sy, ex, ey, start_limit, end_limit)) return routes; routes.push_back(std::move(main->detailed)); for (auto& alt : others) { if (alt->detailed.empty()) continue; prepareResult(context.get(), alt->detailed); front_end.makeStartEndPointsPrecise(context.get(), alt->detailed, sx, sy, ex, ey); - if (!accept_route(alt->detailed, "alternative")) continue; + if (!accept_route(alt->detailed, "alternative", sx, sy, ex, ey, start_limit, end_limit)) continue; routes.push_back(std::move(alt->detailed)); } return routes; @@ -716,7 +703,20 @@ class NavigationWorker::Impl { std::vector route( const Request& request, const std::shared_ptr& cancel) { + if (metres_between(request.origin, {request.destination.latitude, request.destination.longitude}) < 1.0) { + trace("worker=route_failed why=already_at_destination"); + return {}; + } + const auto preparing = std::chrono::steady_clock::now(); if (!prepare_router() || cancel->isAborted()) return {}; + { + char line[160]; + std::snprintf(line, sizeof(line), "worker=route_ready revision=%llu wait_ms=%lld", + static_cast(request.revision), + static_cast(std::chrono::duration_cast( + std::chrono::steady_clock::now() - preparing).count())); + trace(line); + } const auto started = std::chrono::steady_clock::now(); const int sx = get31TileNumberX(request.origin.longitude); const int sy = get31TileNumberY(request.origin.latitude); @@ -741,6 +741,12 @@ class NavigationWorker::Impl { // Organic Maps' turns for each route found, while its routing context (the // roads at every node) is alive; parallel to |found|. std::vector found_turns; + RouteRoads road_cache; + RouteRoads* cached_roads = &road_cache; +#ifdef ONC_ROUTE_DIAGNOSTICS + // Same corrected routes with/without the per-request cache for A/B tests. + if (std::getenv("ROUTE_BENCH_NO_ROAD_CACHE")) cached_roads = nullptr; +#endif const auto annotate = [&](RoutingContext& context) { while (found_turns.size() < found.size()) { if (!organic_turns_) { @@ -751,7 +757,7 @@ class NavigationWorker::Impl { omaps::Result result = omaps::annotate( context, found[found_turns.size()], request.origin.latitude, request.origin.longitude, request.destination.latitude, - request.destination.longitude); + request.destination.longitude, ch_ ? cached_roads : nullptr); const long long ms = std::chrono::duration_cast( std::chrono::steady_clock::now() - annotate_started).count(); char line[200]; @@ -765,15 +771,19 @@ class NavigationWorker::Impl { found_turns.push_back(std::move(result)); } }; - // Both ends on one sidecar node: a route of a few metres, which A* finds - // at once and HH (seconds over the whole network) often does not. - bool skip_hh = false; + // A configured CH sidecar is the selected router. A missing/stale index + // or failed query must be visible, not silently trigger slower routers. + // Empty ch_sidecar_ is the explicit switch to OsmAnd's HH/A* router. + if (!ch_sidecar_.empty() && !ch_) { + trace("worker=route_failed method=ch why=sidecar_unavailable"); + return {}; + } if (ch_) { auto context = new_context(); std::string why; Segments segments = ch_->route(front_end, context, sx, sy, ex, ey, why, - request.heading_degrees.value_or(-1.0)); - if (!segments.empty() && accept_route(segments, "ch")) { + request.heading_degrees.value_or(-1.0), cached_roads); + if (!segments.empty() && accept_route(segments, "ch", sx, sy, ex, ey)) { const ChPlanner::Timing& timing = ch_->last_timing(); char line[200]; std::snprintf(line, sizeof(line), @@ -786,34 +796,37 @@ class NavigationWorker::Impl { found.push_back(std::move(segments)); annotate(*context); } else if (!cancel->isAborted()) { - trace(("worker=ch_fallback why=" + (why.empty() ? std::string("route_rejected") : why)).c_str()); - skip_hh = why == "too_short_for_sidecar"; + trace(("worker=route_failed method=ch why=" + + (why.empty() ? std::string("route_rejected") : why)).c_str()); + return {}; } } - if (found.empty() && !cancel->isAborted()) method = "hh"; - if (found.empty() && has_hh_ && !skip_hh && !cancel->isAborted()) { + if (!ch_ && has_hh_ && !cancel->isAborted()) { + method = "hh"; auto context = new_context(); found = route_hh(front_end, context, sx, sy, ex, ey, request.alternatives && kAlternativeRoutes); annotate(*context); } - if (found.empty() && !cancel->isAborted()) { - // A* (no HH data, or HH found nothing usable). + if (!ch_ && !has_hh_ && !cancel->isAborted()) { + // Explicit OsmAnd mode, maps without HH data: select A* directly. method = "astar"; - trace(skip_hh ? "worker=route_fallback why=too_short" - : has_hh_ ? "worker=route_fallback why=hh_unusable" - : "worker=route_fallback why=no_hh_data"); + trace("worker=route_method method=astar why=no_hh_data"); auto context = new_context(); std::vector intermediates_x; std::vector intermediates_y; auto segments = front_end.searchRoute(context, sx, sy, ex, ey, intermediates_x, intermediates_y, nullptr); - if (!segments.empty()) { + if (!segments.empty() && accept_route(segments, "astar", sx, sy, ex, ey)) { found.push_back(std::move(segments)); annotate(*context); } } - if (cancel->isAborted() || found.empty()) return {}; + if (cancel->isAborted()) return {}; + if (found.empty()) { + trace((std::string("worker=route_failed method=") + method + " why=no_usable_route").c_str()); + return {}; + } { char line[96]; std::snprintf(line, sizeof(line), "worker=route_calculated method=%s routes=%zu ms=%lld", @@ -844,9 +857,13 @@ class NavigationWorker::Impl { // Organic Maps switched off: OsmAnd's own manoeuvres (no Result). const omaps::Result* turns = organic_turns_ ? &found_turns[index] : nullptr; ui::RouteAlternative alternative = convert(request, found, index, turns); - if (alternative.geometry.size() < 2) continue; + if (alternative.geometry.size() < 2) { + trace("worker=route_rejected why=empty_geometry"); + continue; + } output.push_back(std::move(alternative)); } + if (output.empty()) trace("worker=route_failed why=no_usable_geometry"); if (output.size() > 1) { const double fastest_metres = output.front().distance_metres; for (std::size_t index = 1; index < output.size(); ++index) @@ -973,30 +990,46 @@ class NavigationWorker::Impl { } using Kind = Request::Kind; + const auto begun = std::chrono::steady_clock::now(); + const auto queue_ms = std::chrono::duration_cast(begun - request.queued).count(); + const char* kind = request.kind == Kind::Search ? "search" + : "route"; + { + char line[160]; + std::snprintf(line, sizeof(line), "worker=request_begin kind=%s revision=%llu queue_ms=%lld", + kind, static_cast(request.revision), static_cast(queue_ms)); + trace(line); + } trace_result(request.kind == Kind::Search ? "worker=search_begin" - : request.kind == Kind::Route ? "worker=route_begin" - : "worker=address_begin", + : "worker=route_begin", request.revision, request.kind == Kind::Search ? request.query.size() : 1u); std::vector destinations; std::vector routes; - std::string address_text; try { if (request.kind == Kind::Search) destinations = search(request, cancel); - else if (request.kind == Kind::Route) - routes = route(request, cancel); else - address_text = address(request); + routes = route(request, cancel); } catch (...) { trace(request.kind == Kind::Search ? "error=destination_search_exception" - : request.kind == Kind::Route ? "error=route_calculation_exception" - : "error=address_exception"); + : "error=route_calculation_exception"); // Publish an empty result so the UI leaves its busy state. // A genuinely superseded request has already been cancelled // by submit(), and remains excluded by the check below. } + { + char line[200]; + const auto work_ms = std::chrono::duration_cast( + std::chrono::steady_clock::now() - begun).count(); + std::snprintf(line, sizeof(line), + "worker=request_done kind=%s revision=%llu work_ms=%lld total_ms=%lld cancelled=%d", + kind, static_cast(request.revision), + static_cast(work_ms), static_cast(queue_ms + work_ms), + cancel->superseded() ? 1 : 0); + trace(line); + } bool published = false; std::size_t published_count = 0; { @@ -1007,14 +1040,10 @@ class NavigationWorker::Impl { result_ = {request.revision, std::move(destinations)}; published_count = result_.destinations.size(); has_result_ = true; - } else if (request.kind == Kind::Route) { + } else { route_result_ = {request.revision, std::move(routes)}; published_count = route_result_.routes.size(); has_route_result_ = true; - } else { - published_count = address_text.empty() ? 0u : 1u; - address_result_ = {request.revision, std::move(address_text)}; - has_address_result_ = true; } published = true; } @@ -1022,8 +1051,7 @@ class NavigationWorker::Impl { } if (published) trace_result(request.kind == Kind::Search ? "worker=search_published" - : request.kind == Kind::Route ? "worker=route_published" - : "worker=address_published", + : "worker=route_published", request.revision, published_count); if (published && wakeup_) (void)wakeup_->request(); @@ -1050,13 +1078,10 @@ class NavigationWorker::Impl { Request pending_; SearchResult result_; RouteResult route_result_; - AddressResult address_result_; - std::shared_ptr road_locator_; // worker thread std::shared_ptr active_; bool has_pending_ = false; bool has_result_ = false; bool has_route_result_ = false; - bool has_address_result_ = false; bool stopping_ = false; bool router_ready_ = false; bool has_hh_ = false; // the map has highway-hierarchy routing sections @@ -1107,16 +1132,6 @@ bool NavigationWorker::take_search_result(SearchResult& output) return impl_->take(output); } -void NavigationWorker::submit_address(std::uint64_t revision, ui::GeoPoint point) -{ - impl_->submit_address(revision, point); -} - -bool NavigationWorker::take_address_result(AddressResult& output) -{ - return impl_->take(output); -} - void NavigationWorker::stop() noexcept { impl_->stop(); } } // namespace navicore_osmand diff --git a/backends/osmand/navigation_worker.h b/backends/osmand/navigation_worker.h index 0d1d35b..2a43ad4 100644 --- a/backends/osmand/navigation_worker.h +++ b/backends/osmand/navigation_worker.h @@ -30,13 +30,6 @@ class NavigationWorker { std::vector routes; }; - // Address of a map point (dropped pin): "street, number"; empty when - // none was found. - struct AddressResult { - std::uint64_t revision = 0; - std::string address; - }; - // search_index: the address index file (search/search_index.h); when it // is missing or unreadable, search falls back to OsmAnd's name search. // organic_turns: turn instructions from Organic Maps' generator @@ -65,11 +58,8 @@ class NavigationWorker { void submit_route(std::uint64_t revision, ui::Destination destination, ui::GeoPoint origin, bool alternatives, std::optional heading_degrees); - // Replaces a pending request like the others (one job at a time). - void submit_address(std::uint64_t revision, ui::GeoPoint point); bool take_search_result(SearchResult& output); bool take_route_result(RouteResult& output); - bool take_address_result(AddressResult& output); void stop() noexcept; private: diff --git a/backends/osmand/omaps_turns.cpp b/backends/osmand/omaps_turns.cpp index 5d0f022..eaaa5de 100644 --- a/backends/osmand/omaps_turns.cpp +++ b/backends/osmand/omaps_turns.cpp @@ -254,7 +254,7 @@ struct RouteEdgeSource class Builder { public: - Builder(RoutingContext & context) : m_context(context) {} + Builder(RoutingContext & context, RouteRoads const * roads) : m_context(context), m_cachedRoads(roads) {} Result Run(std::vector> const & route, double startLat, double startLon, double finishLat, double finishLon); @@ -272,6 +272,7 @@ class Builder void DumpPathSegments() const; RoutingContext & m_context; + RouteRoads const * m_cachedRoads; std::map, std::vector> m_nodes; std::unordered_map m_featureIndex; @@ -290,6 +291,16 @@ std::vector const & Builder::RoadsAt(uint32_t x31, uint32_t y31) if (it != m_nodes.end()) return it->second; std::vector roads; + if (m_cachedRoads) + { + auto cached = m_cachedRoads->find(route_node_key(x31, y31)); + if (cached != m_cachedRoads->end()) + { + for (auto const & rs : cached->second) + roads.push_back({rs->object, rs->getStartPointIndex()}); + return m_nodes.emplace(key, std::move(roads)).first->second; + } + } for (auto const & rs : m_context.loadRouteSegment(static_cast(x31), static_cast(y31))) roads.push_back({rs->getRoad(), rs->getSegmentStart()}); return m_nodes.emplace(key, std::move(roads)).first->second; @@ -918,11 +929,12 @@ Result Builder::Run(std::vector> const & route, d } // namespace Result annotate(RoutingContext & context, std::vector> const & route, - double start_latitude, double start_longitude, double finish_latitude, double finish_longitude) + double start_latitude, double start_longitude, double finish_latitude, double finish_longitude, + RouteRoads const * roads) { try { - Builder builder(context); + Builder builder(context, roads); return builder.Run(route, start_latitude, start_longitude, finish_latitude, finish_longitude); } // OM's CHECK failures (shim/base/assert.hpp) by their own type: a catch of diff --git a/backends/osmand/omaps_turns.h b/backends/osmand/omaps_turns.h index 4e9a986..1364417 100644 --- a/backends/osmand/omaps_turns.h +++ b/backends/osmand/omaps_turns.h @@ -10,6 +10,7 @@ // third_party/organicmaps-routing/README.md lists the OsmAnd -> OM mapping. #include "ui/navigation_model.h" +#include "route_roads.h" #include #include @@ -55,6 +56,6 @@ struct Result { // route like OM's own router does. Never throws: an OM check failure is an error. Result annotate(RoutingContext& context, const std::vector>& route, double start_latitude, double start_longitude, double finish_latitude, - double finish_longitude); + double finish_longitude, const RouteRoads* roads = nullptr); } // namespace navicore_osmand::omaps diff --git a/backends/osmand/osmand_engine.cpp b/backends/osmand/osmand_engine.cpp index faa63b3..af78030 100644 --- a/backends/osmand/osmand_engine.cpp +++ b/backends/osmand/osmand_engine.cpp @@ -274,9 +274,7 @@ class OsmAndEngine final : public Engine { void update_pin_marker(); bool unproject_lat_lon(int x, int y, OsmAnd::LatLon& out) const; std::string with_distance(std::string text, const OsmAnd::LatLon& location) const; - std::string pin_id_; // the pin whose address is pending Config config_; - std::uint64_t address_revision_ = 0; ui::MapTouch map_touch_; std::chrono::steady_clock::time_point clock_origin_ = std::chrono::steady_clock::now(); @@ -1497,7 +1495,7 @@ void OsmAndEngine::handle_map_tap(int x, int y) } // Long press on the map: a pin there with its card. The subtitle shows -// the coordinates until the worker finds the nearest address. +// the coordinates. Routing uses this exact point; no reverse geocoding is needed. void OsmAndEngine::drop_pin(int x, int y) { OsmAnd::LatLon location; @@ -1512,13 +1510,9 @@ void OsmAndEngine::drop_pin(int x, int y) pin.latitude = location.latitude; pin.longitude = location.longitude; pin.subtitle = with_distance(coordinates, location); - pin_id_ = pin.id; if (!view_->show_place_card(std::move(pin), "pin")) return; trace("map_gesture=pin"); - if (ensure_navigation_worker()) - navigation_worker_->submit_address(++address_revision_, - {location.latitude, location.longitude}); } // The pin follows the map while its card is open. @@ -1584,17 +1578,6 @@ void OsmAndEngine::drain_navigation_results() (void)view_->apply_search_results(search_result.revision, std::move(search_result.destinations)); } - NavigationWorker::AddressResult address_result; - if (navigation_worker_ && navigation_worker_->take_address_result(address_result) && - address_result.revision == address_revision_) { - trace_result("engine=address_result", address_result.revision, - address_result.address.size()); - const ui::Destination* pin = navigation_->place_card(); - if (!address_result.address.empty() && pin && pin->id == pin_id_) - (void)view_->set_place_subtitle( - pin_id_, with_distance(address_result.address, - OsmAnd::LatLon(pin->latitude, pin->longitude))); - } NavigationWorker::RouteResult route_result; if (navigation_worker_ && navigation_worker_->take_route_result(route_result)) { trace_result("engine=route_result", route_result.revision, diff --git a/backends/osmand/route_check.cpp b/backends/osmand/route_check.cpp index ac08e4d..0938c3b 100644 --- a/backends/osmand/route_check.cpp +++ b/backends/osmand/route_check.cpp @@ -18,6 +18,19 @@ double metres_between(double lat1, double lon1, double lat2, double lon2) } // namespace +RouteExtentCheck check_route_extent(ui::GeoPoint origin, ui::GeoPoint destination, + ui::GeoPoint start, ui::GeoPoint end, double length_metres, + double max_start_gap, double max_end_gap) +{ + RouteExtentCheck check; + check.start_gap_metres = metres_between(origin.latitude, origin.longitude, start.latitude, start.longitude); + check.end_gap_metres = metres_between(destination.latitude, destination.longitude, end.latitude, end.longitude); + check.usable = std::isfinite(length_metres) && length_metres >= 1.0 && + std::isfinite(check.start_gap_metres) && check.start_gap_metres <= max_start_gap && + std::isfinite(check.end_gap_metres) && check.end_gap_metres <= max_end_gap; + return check; +} + RouteCheck check_route_legs(const std::vector& legs, double gap_tolerance_metres) { RouteCheck check; diff --git a/backends/osmand/route_check.h b/backends/osmand/route_check.h index 53ac768..ba4f84b 100644 --- a/backends/osmand/route_check.h +++ b/backends/osmand/route_check.h @@ -3,6 +3,7 @@ #include #include #include +#include "ui/navigation_model.h" namespace navicore_osmand { @@ -30,4 +31,16 @@ struct RouteCheck { // is drawn across water and forest, so it must never be shown as a route. RouteCheck check_route_legs(const std::vector& legs, double gap_tolerance_metres = 150.0); +struct RouteExtentCheck { + bool usable = false; + double start_gap_metres = 0; + double end_gap_metres = 0; +}; + +// The selected router must actually reach both endpoints within its snap radius, +// and return a travelled path, not two copies of the same junction. +RouteExtentCheck check_route_extent(ui::GeoPoint origin, ui::GeoPoint destination, + ui::GeoPoint start, ui::GeoPoint end, double length_metres, + double max_start_gap = 1000.0, double max_end_gap = 1000.0); + } // namespace navicore_osmand diff --git a/backends/osmand/route_roads.h b/backends/osmand/route_roads.h new file mode 100644 index 0000000..5fea88d --- /dev/null +++ b/backends/osmand/route_roads.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include +#include + +struct RouteSegmentResult; + +namespace navicore_osmand { + +// Immutable road/index snapshots at route nodes, owned by one request. These +// are not reusable search-state wrappers or a process-wide decoded-map cache. +using RouteRoads = std::unordered_map>>; + +inline std::uint64_t route_node_key(std::uint32_t x, std::uint32_t y) +{ + return (static_cast(x) << 32) | y; +} + +} // namespace navicore_osmand diff --git a/backends/osmand/snap_policy.h b/backends/osmand/snap_policy.h new file mode 100644 index 0000000..e67de66 --- /dev/null +++ b/backends/osmand/snap_policy.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include +#include + +namespace navicore_osmand { + +// Resolve the endpoint before optimizing travel time. Only geometrically tied +// roads may compete (junctions and overlapping map ways); a cheaper journey +// must not move a pin to another street. One metre allows map quantization. +template +void keep_nearest_roads(std::vector& snaps) +{ + snaps.erase(std::remove_if(snaps.begin(), snaps.end(), [](const Snap& s) { + return !std::isfinite(s.metres) || s.metres < 0 || s.metres > 1000; + }), snaps.end()); + if (snaps.empty()) return; + const double nearest = std::min_element(snaps.begin(), snaps.end(), + [](const Snap& a, const Snap& b) { return a.metres < b.metres; })->metres; + snaps.erase(std::remove_if(snaps.begin(), snaps.end(), [nearest](const Snap& s) { + return s.metres > nearest + 1.0; + }), snaps.end()); +} + +} // namespace navicore_osmand diff --git a/backends/osmand/ui/navigation_model.cpp b/backends/osmand/ui/navigation_model.cpp index 34941ab..77a8655 100644 --- a/backends/osmand/ui/navigation_model.cpp +++ b/backends/osmand/ui/navigation_model.cpp @@ -440,16 +440,6 @@ bool NavigationModel::show_place_card(Destination place, std::string icon) return true; } -bool NavigationModel::set_place_subtitle(const std::string& id, std::string subtitle) -{ - if (!has_place_ || place_.id != id || place_.subtitle == subtitle) - return false; - place_.subtitle = std::move(subtitle); - if (has_destination_ && destination_.id == id) - destination_.subtitle = place_.subtitle; - return true; -} - bool NavigationModel::close_place_card() noexcept { if (!has_place_) diff --git a/backends/osmand/ui/navigation_model.h b/backends/osmand/ui/navigation_model.h index 3a31b1e..dc8b448 100644 --- a/backends/osmand/ui/navigation_model.h +++ b/backends/osmand/ui/navigation_model.h @@ -320,8 +320,6 @@ class NavigationModel { const std::string& place_card_icon() const noexcept { return place_icon_; } bool show_place_card(Destination place, std::string icon); bool close_place_card() noexcept; - // A late subtitle (a dropped pin's address) for the card showing `id`. - bool set_place_subtitle(const std::string& id, std::string subtitle); // Dropped pins: their card's place id starts with this. static constexpr const char* pin_prefix = "pin:"; bool place_card_is_pin() const noexcept diff --git a/backends/osmand/ui/navigation_view.cpp b/backends/osmand/ui/navigation_view.cpp index 3eee886..d1d0d81 100644 --- a/backends/osmand/ui/navigation_view.cpp +++ b/backends/osmand/ui/navigation_view.cpp @@ -770,15 +770,6 @@ void NavigationView::set_pin_marker(bool visible, int x, int y) pin_y_ = y; } -bool NavigationView::set_place_subtitle(const std::string& id, std::string subtitle) -{ - if (!model_.set_place_subtitle(id, std::move(subtitle))) - return false; - if (built_screen_ == Screen::FreeDrive) - rebuild(); - return true; -} - void NavigationView::set_vehicle_marker(bool visible, int x, int y, float rotation_degrees) { diff --git a/backends/osmand/ui/navigation_view.h b/backends/osmand/ui/navigation_view.h index a8a7b94..181b5b0 100644 --- a/backends/osmand/ui/navigation_view.h +++ b/backends/osmand/ui/navigation_view.h @@ -106,8 +106,6 @@ class NavigationView { bool open_dev_menu(); bool close_dev_menu(); bool set_dev_info(std::vector sections, std::vector toggles); - // A late subtitle (dropped pin address) for the card showing `id`. - bool set_place_subtitle(const std::string& id, std::string subtitle); private: struct PointerSample { int action; int32_t x; int32_t y; int contact = 0; }; diff --git a/deploy/bench/route_bench_run.c b/deploy/bench/route_bench_run.c index 4793489..e2469f3 100644 --- a/deploy/bench/route_bench_run.c +++ b/deploy/bench/route_bench_run.c @@ -16,7 +16,8 @@ int main(int argc, char **argv) fprintf(stderr, "dlopen %s: %s\n", core, dlerror()); return 1; } - library = dlopen("/tmp/libroute_bench.so", RTLD_NOW); + const int worker = argc > 1 && strcmp(argv[1], "worker") == 0; + library = dlopen(worker ? "/tmp/libroute_worker_bench.so" : "/tmp/libroute_bench.so", RTLD_NOW); if (library == NULL) { fprintf(stderr, "dlopen: %s\n", dlerror()); return 1; @@ -29,7 +30,7 @@ int main(int argc, char **argv) } return entry(argc - 1, argv + 1); } - entry = (int (*)(int, char **))dlsym(library, "route_bench_main"); + entry = (int (*)(int, char **))dlsym(library, worker ? "route_worker_bench_main" : "route_bench_main"); if (entry == NULL) { fprintf(stderr, "dlsym: %s\n", dlerror()); return 1; diff --git a/deploy/bench/route_worker_bench.cpp b/deploy/bench/route_worker_bench.cpp new file mode 100644 index 0000000..b65667c --- /dev/null +++ b/deploy/bench/route_worker_bench.cpp @@ -0,0 +1,204 @@ +// Runs the product worker in a separate process against the installed maps. +// No screen, GPS injection, persistent markers, or navigation service restart. +#include "navigation_worker.h" +#include "config.h" +#include "diagnostics.h" +#include "session.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using Clock = std::chrono::steady_clock; +const auto started = Clock::now(); +std::atomic ready{false}; +std::atomic deadline{120000}; +std::atomic turn_errors{0}; +bool wait_for_ch = true; +long long elapsed() { return std::chrono::duration_cast(Clock::now() - started).count(); } +void poll_pause() { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } +double metres(navicore_osmand::ui::GeoPoint a, navicore_osmand::ui::GeoPoint b) { + constexpr double rad = 3.14159265358979323846 / 180.0; + const double p = (b.latitude - a.latitude) * rad; + const double q = (b.longitude - a.longitude) * rad; + const double h = std::sin(p/2)*std::sin(p/2) + std::cos(a.latitude*rad)*std::cos(b.latitude*rad)* + std::sin(q/2)*std::sin(q/2); + return 12742000.0 * std::asin(std::sqrt(std::min(1.0, std::max(0.0, h)))); +} +std::uint64_t fingerprint(const std::string& text) { + std::uint64_t value = 14695981039346656037ull; + for (unsigned char c : text) { value ^= c; value *= 1099511628211ull; } + return value; +} +struct Case { + std::string id; + navicore_osmand::ui::GeoPoint origin, destination; + double heading = -1; +}; +} +namespace navicore_osmand { +// Keep diagnostic worker traces out of the running product's log. +void trace(const char* message) noexcept { + std::printf("%lld %s\n", elapsed(), message); + if (std::strncmp(message, "worker=omaps_error", 18) == 0) ++turn_errors; + if (std::strncmp(message, "worker=ch ", 10) == 0 || + std::strncmp(message, "worker=ch_off ", 14) == 0) ready = true; + if (!wait_for_ch && std::strncmp(message, "worker=router ", 14) == 0) ready = true; +} +void trace_result(const char* stage, std::uint64_t revision, std::size_t count) noexcept { + char line[160]; + std::snprintf(line, sizeof(line), "%s revision=%llu count=%zu", stage, + static_cast(revision), count); + trace(line); +} +int Wakeup::request() const noexcept { return 0; } +} + +extern "C" __attribute__((visibility("default"))) +int route_worker_bench_main(int argc, char** argv) { + const bool batch = argc == 7 && std::strcmp(argv[6], "batch") == 0; + if (argc != 10 && !batch) { + std::fprintf(stderr, "usage: worker MAP XML SIDECAR LAT1 LON1 LAT2 LON2 route|reject|cold\n" + " worker MAP XML SIDECAR CASES.tsv batch\n"); + return 2; + } + wait_for_ch = std::strcmp(argv[4], "-") != 0; + std::setvbuf(stdout, nullptr, _IONBF, 0); + // A timeout exits only this diagnostic process, never the navigation service. + std::thread([] { + for (;;) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + if (elapsed() > deadline.load()) { + std::fprintf(stderr, "diagnostic timeout: no request completed within 120 seconds\n"); + std::_Exit(124); + } + } + }).detach(); + using namespace navicore_osmand; + auto resources = OsmAnd::CoreResourcesEmbeddedBundle::loadFromLibrary( + QString::fromLatin1("/open-navicore/libOsmAndCore_ResourcesBundle_shared.so")); + if (!resources || !OsmAnd::InitializeCore(resources, "/datastore/navicore-backend/fonts")) return 2; + const auto maps = obf_files(argv[2]); + auto obfs = std::make_shared(); + for (const auto& file : maps) if (!is_basemap(file)) obfs->addFile(QString::fromLocal8Bit(file.c_str())); + std::ifstream input(argv[3]); + const std::string xml((std::istreambuf_iterator(input)), std::istreambuf_iterator()); + if (xml.empty()) return 2; + std::vector cases; + if (batch) { + std::ifstream file(argv[5]); + std::string line; + while (std::getline(file, line)) { + if (line.empty() || line[0] == '#') continue; + std::istringstream row(line); + Case item; + if (!(row >> item.id >> item.origin.latitude >> item.origin.longitude >> + item.destination.latitude >> item.destination.longitude)) return 2; + row >> item.heading; // optional heading in degrees + cases.push_back(std::move(item)); + } + if (cases.empty()) return 2; + } else { + Case item{"single", {std::atof(argv[5]), std::atof(argv[6])}, + {std::atof(argv[7]), std::atof(argv[8])}}; + cases = {item, item}; + } + std::printf("bench=cases count=%zu mode=%s\n", cases.size(), batch ? "batch" : argv[9]); + { + NavigationWorker worker(obfs, {}, maps, xml, std::string(argv[2]) + "/search.idx", wait_for_ch ? argv[4] : ""); + if (batch || std::strcmp(argv[9], "cold") != 0) while (!ready) poll_pause(); + for (std::size_t run = 0; run < cases.size(); ++run) { + const auto& item = cases[run]; + ui::Destination destination; + destination.id = item.id; destination.title = item.id; + destination.latitude = item.destination.latitude; + destination.longitude = item.destination.longitude; + turn_errors = 0; + deadline = elapsed() + 120000; + std::printf("batch=begin id=%s origin=%.8f,%.8f destination=%.8f,%.8f\n", + item.id.c_str(), item.origin.latitude, item.origin.longitude, + destination.latitude, destination.longitude); + const auto submitted = Clock::now(); + worker.submit_route(run + 2, destination, item.origin, false, + item.heading >= 0 ? std::optional(item.heading) : std::nullopt); + NavigationWorker::RouteResult result; + while (!worker.take_route_result(result)) poll_pause(); + const auto wall_ms = std::chrono::duration_cast(Clock::now() - submitted).count(); + std::printf("bench=complete run=%zu wall_ms=%lld routes=%zu distance_m=%.0f points=%zu\n", run, + static_cast(wall_ms), result.routes.size(), + result.routes.empty() ? 0.0 : result.routes.front().distance_metres, + result.routes.empty() ? 0u : result.routes.front().geometry.size()); + if (batch) { + double start_gap = -1, end_gap = -1, geometry = 0, max_step = 0; + bool finite = true; + std::size_t maneuvers = 0; + std::uint64_t geometry_hash = 0, turns_hash = 0; + double duration = 0; + if (!result.routes.empty()) { + const auto& route = result.routes.front(); + maneuvers = route.maneuvers.size(); + duration = route.duration_seconds; + std::ostringstream shape, turns; + shape.precision(15); turns.precision(15); + for (const auto& p : route.geometry) shape << p.latitude << ',' << p.longitude << ';'; + for (const auto& m : route.maneuvers) { + turns << static_cast(m.kind) << ',' << m.road << ',' << m.distance_from_start_metres + << ',' << m.geometry_index << ',' << m.roundabout_exit << ',' << m.left_side + << ',' << m.turn_angle_degrees << ',' << m.junction.valid << ',' << m.junction.route_angle + << ',' << m.junction.through_road << ',' << m.junction.truncated << ',' + << m.junction.recommended_lanes << ',' << static_cast(m.junction.lane_change); + for (const auto& lane : m.lanes) turns << ':' << static_cast(lane.kind) << ',' + << static_cast(lane.also) << ',' << lane.combined << ',' << lane.recommended; + for (unsigned j = 0; j < m.junction.branch_count; ++j) turns << '/' << m.junction.branches[j]; + turns << ';'; + } + geometry_hash = fingerprint(shape.str()); turns_hash = fingerprint(turns.str()); + if (!route.geometry.empty()) { + start_gap = metres(item.origin, route.geometry.front()); + end_gap = metres(item.destination, route.geometry.back()); + } + finite = std::isfinite(route.distance_metres) && std::isfinite(route.duration_seconds); + for (std::size_t i = 0; i < route.geometry.size(); ++i) { + const auto& point = route.geometry[i]; + finite = finite && std::isfinite(point.latitude) && std::isfinite(point.longitude) && + std::fabs(point.latitude) <= 90 && std::fabs(point.longitude) <= 180; + if (i) { + const double step = metres(route.geometry[i-1], point); + geometry += step; max_step = std::max(max_step, step); + } + } + } + std::printf("batch=case id=%s status=%s wall_ms=%lld routes=%zu air_m=%.1f distance_m=%.1f " + "start_gap_m=%.1f end_gap_m=%.1f geometry_m=%.1f max_step_m=%.1f finite=%d maneuvers=%zu omaps_errors=%u duration_s=%.3f geometry_hash=%llu turns_hash=%llu\n", + item.id.c_str(), result.revision != run + 2 ? "revision_mismatch" : result.routes.empty() ? "no_route" : "ok", + static_cast(wall_ms), result.routes.size(), metres(item.origin, item.destination), + result.routes.empty() ? 0 : result.routes.front().distance_metres, + start_gap, end_gap, geometry, max_step, finite ? 1 : 0, maneuvers, turn_errors.load(), duration, + static_cast(geometry_hash), static_cast(turns_hash)); + continue; // A failed route is a recorded observation, not the end of the survey. + } + const bool reject = std::strcmp(argv[9], "reject") == 0; + const char* limit = std::getenv("ROUTE_WORKER_MAX_MS"); + if (result.revision != run + 2 || result.routes.empty() != reject || + (limit && wall_ms > std::atoll(limit))) { + std::fprintf(stderr, "bench=failed unexpected revision, route count, or latency\n"); + std::_Exit(1); + } + } + worker.stop(); + } + std::printf("bench=%s\n", batch ? "batch_complete" : "passed"); + // OsmAnd's QNX global teardown is process-owned, as in route_bench. + std::_Exit(0); + return 0; +} diff --git a/deploy/bench/ukraine-routing-20261028.tsv b/deploy/bench/ukraine-routing-20261028.tsv new file mode 100644 index 0000000..2f6f697 --- /dev/null +++ b/deploy/bench/ukraine-routing-20261028.tsv @@ -0,0 +1,128 @@ +regional_000_f 49.83526384 32.33332962 49.64637130 31.93366036 +regional_000_r 49.64637130 31.93366036 49.83526384 32.33332962 +regional_001_f 50.94496975 32.00861871 51.07575041 31.88422590 +regional_001_r 51.07575041 31.88422590 50.94496975 32.00861871 +regional_002_f 48.28371318 25.98064765 48.27931957 25.92825606 +regional_002_r 48.27931957 25.92825606 48.28371318 25.98064765 +regional_003_f 44.53557129 34.10890639 44.43534842 34.12801310 +regional_003_r 44.43534842 34.12801310 44.53557129 34.10890639 +regional_004_f 48.63622328 34.66625199 48.49901549 35.10015026 +regional_004_r 48.49901549 35.10015026 48.63622328 34.66625199 +regional_005_f 48.31946382 37.83987254 48.23250858 37.55748421 +regional_005_r 48.23250858 37.55748421 48.31946382 37.83987254 +regional_006_f 48.46439392 24.90684807 48.38957018 24.81517956 +regional_006_r 48.38957018 24.81517956 48.46439392 24.90684807 +regional_007_f 50.26294792 35.47179043 50.09854974 35.09791866 +regional_007_r 50.09854974 35.09791866 50.26294792 35.47179043 +regional_008_f 46.70466786 32.61088192 46.54775272 32.93026865 +regional_008_r 46.54775272 32.93026865 46.70466786 32.61088192 +regional_009_f 49.34424940 27.57440820 49.26957748 27.39520177 +regional_009_r 49.26957748 27.39520177 49.34424940 27.57440820 +regional_010_f 48.61952618 32.33536005 48.63363801 32.80987635 +regional_010_r 48.63363801 32.80987635 48.61952618 32.33536005 +regional_011_f 50.44229599 30.64199835 50.42891907 30.25634497 +regional_011_r 50.42891907 30.25634497 50.44229599 30.64199835 +regional_012_f 50.52965943 30.37265763 50.45403826 30.35832658 +regional_012_r 50.45403826 30.35832658 50.52965943 30.37265763 +regional_013_f 48.68007369 38.55903313 48.97345136 38.48416194 +regional_013_r 48.97345136 38.48416194 48.68007369 38.55903313 +regional_014_f 49.44352115 24.31683987 49.55796233 24.36039761 +regional_014_r 49.55796233 24.36039761 49.44352115 24.31683987 +regional_015_f 46.99825866 31.51426479 47.01103220 32.00164765 +regional_015_r 47.01103220 32.00164765 46.99825866 31.51426479 +regional_016_f 47.09713332 30.75439230 47.03674378 30.56729749 +regional_016_r 47.03674378 30.56729749 47.09713332 30.75439230 +regional_017_f 49.61124350 34.67953965 49.72265937 34.44530502 +regional_017_r 49.72265937 34.44530502 49.61124350 34.67953965 +regional_018_f 50.61239889 26.65200993 50.63631231 26.20466575 +regional_018_r 50.63631231 26.20466575 50.61239889 26.65200993 +regional_019_f 50.68976484 33.41851383 50.84646030 33.24902236 +regional_019_r 50.84646030 33.24902236 50.68976484 33.41851383 +regional_020_f 50.11936049 25.70144579 50.07675225 26.01652220 +regional_020_r 50.07675225 26.01652220 50.11936049 25.70144579 +regional_021_f 48.98663758 22.83970177 48.85107538 22.58440912 +regional_021_r 48.85107538 22.58440912 48.98663758 22.83970177 +regional_022_f 48.99557047 28.20409298 49.32390699 28.40542495 +regional_022_r 49.32390699 28.40542495 48.99557047 28.20409298 +regional_023_f 50.57424687 24.92339730 50.72073074 24.80159014 +regional_023_r 50.72073074 24.80159014 50.57424687 24.92339730 +regional_024_f 47.83941894 35.12779444 47.83155631 35.19858196 +regional_024_r 47.83155631 35.19858196 47.83941894 35.12779444 +regional_025_f 50.35072436 28.44216049 50.26422703 28.68611678 +regional_025_r 50.26422703 28.68611678 50.35072436 28.44216049 +cross_026_f 48.60248124 22.29130402 50.94127364 31.80916563 +cross_026_r 50.94127364 31.80916563 48.60248124 22.29130402 +cross_027_f 50.68931709 32.79626682 50.03781273 35.93853503 +cross_027_r 50.03781273 35.93853503 50.68931709 32.79626682 +cross_028_f 49.92190278 37.06184283 51.88516449 25.14362812 +cross_028_r 51.88516449 25.14362812 49.92190278 37.06184283 +cross_029_f 51.22439856 24.65947464 49.90826447 23.97229135 +cross_029_r 49.90826447 23.97229135 51.22439856 24.65947464 +cross_030_f 49.81854578 23.83573741 46.78119025 33.48256767 +cross_030_r 46.78119025 33.48256767 49.81854578 23.83573741 +cross_031_f 46.65510593 33.35702822 44.95090740 34.13091257 +cross_031_r 44.95090740 34.13091257 46.65510593 33.35702822 +cross_032_f 45.07383504 34.61538523 50.25822899 32.48137683 +cross_032_r 50.25822899 32.48137683 45.07383504 34.61538523 +cross_033_f 49.39359219 35.11524573 48.33693204 28.34804848 +cross_033_r 48.33693204 28.34804848 49.39359219 35.11524573 +cross_034_f 49.08840094 28.61819386 48.95795545 24.61515918 +cross_034_r 48.95795545 24.61515918 49.08840094 28.61819386 +cross_035_f 48.78148479 24.85525176 48.03030007 38.60147774 +cross_035_r 48.03030007 38.60147774 48.78148479 24.85525176 +cross_036_f 48.38076696 37.70113796 48.43493286 36.56333685 +cross_036_r 48.43493286 36.56333685 48.38076696 37.70113796 +cross_037_f 47.60548127 34.33567375 49.06722634 31.20664358 +cross_037_r 49.06722634 31.20664358 47.60548127 34.33567375 +cross_038_f 50.17812801 32.09823802 48.79127873 32.38846242 +cross_038_r 48.79127873 32.38846242 50.17812801 32.09823802 +cross_039_f 48.34874937 30.52547380 47.98745783 25.93290836 +cross_039_r 47.98745783 25.93290836 48.34874937 30.52547380 +cross_040_f 48.53136305 27.47864127 48.91624491 38.37612122 +cross_040_r 48.91624491 38.37612122 48.53136305 27.47864127 +cross_041_f 48.62639910 39.36399087 48.64535882 26.76961809 +cross_041_r 48.64535882 26.76961809 48.62639910 39.36399087 +cross_042_f 48.96756700 27.08355859 50.36670006 30.54235160 +cross_042_r 50.36670006 30.54235160 48.96756700 27.08355859 +cross_043_f 50.49662158 30.54467842 50.60375008 26.34341240 +cross_043_r 50.60375008 26.34341240 50.49662158 30.54467842 +cross_044_f 50.63493690 26.52730465 46.61254191 31.79373488 +cross_044_r 46.61254191 31.79373488 50.63493690 26.52730465 +cross_045_f 46.85334410 32.82565981 49.53561093 25.50498605 +cross_045_r 49.53561093 25.50498605 46.85334410 32.82565981 +cross_046_f 49.29728060 25.68588227 47.93971169 29.62556317 +cross_046_r 47.93971169 29.62556317 49.29728060 25.68588227 +cross_047_f 47.17916494 29.94056046 50.61029088 35.32251611 +cross_047_r 50.61029088 35.32251611 47.17916494 29.94056046 +cross_048_f 50.71290945 33.61984313 49.83869516 29.06003952 +cross_048_r 49.83869516 29.06003952 50.71290945 33.61984313 +cross_049_f 50.38439265 28.71635064 50.37448746 30.47685206 +cross_049_r 50.37448746 30.47685206 50.38439265 28.71635064 +cross_050_f 50.91849728 29.89812121 46.79782212 36.75255194 +cross_050_r 46.79782212 36.75255194 50.91849728 29.89812121 +cross_051_f 47.70192261 35.49835637 48.22368090 24.17233720 +cross_051_r 48.22368090 24.17233720 47.70192261 35.49835637 +short_052_f 50.71495257 26.88563168 50.71513429 26.88611984 +short_052_r 50.71513429 26.88611984 50.71495257 26.88563168 +short_053_f 50.23488810 31.05077773 50.23510428 31.05003476 +short_053_r 50.23510428 31.05003476 50.23488810 31.05077773 +short_054_f 49.17387271 24.45406169 49.17390778 24.45434600 +short_054_r 49.17390778 24.45434600 49.17387271 24.45406169 +short_055_f 46.18360216 33.59621823 46.18477764 33.59505147 +short_055_r 46.18477764 33.59505147 46.18360216 33.59621823 +short_056_f 48.24685065 30.35156071 48.24649520 30.35045028 +short_056_r 48.24649520 30.35045028 48.24685065 30.35156071 +short_057_f 48.25129259 25.69461823 48.25184982 25.69285333 +short_057_r 48.25184982 25.69285333 48.25129259 25.69461823 +short_058_f 49.66098724 32.75757194 49.65982223 32.75654465 +short_058_r 49.65982223 32.75654465 49.66098724 32.75757194 +short_059_f 50.33252869 24.19531971 50.33279578 24.19400543 +short_059_r 50.33279578 24.19400543 50.33252869 24.19531971 +short_060_f 48.87918479 22.48547584 48.87925005 22.48475969 +short_060_r 48.87925005 22.48475969 48.87918479 22.48547584 +short_061_f 48.23129633 34.19446349 48.23074960 34.19439375 +short_061_r 48.23074960 34.19439375 48.23129633 34.19446349 +short_062_f 50.50487553 30.46351612 50.50533954 30.46341956 +short_062_r 50.50533954 30.46341956 50.50487553 30.46351612 +short_063_f 49.31390794 36.37162328 49.31483642 36.37209803 +short_063_r 49.31483642 36.37209803 49.31390794 36.37162328 diff --git a/deploy/bench/ukraine-routing-controls.tsv b/deploy/bench/ukraine-routing-controls.tsv new file mode 100644 index 0000000..2910fbd --- /dev/null +++ b/deploy/bench/ukraine-routing-controls.tsv @@ -0,0 +1,13 @@ +# id lat1 lon1 lat2 lon2 [heading_degrees] +# offroad_far and same_point must be rejected; other cases must return routes. +heading_city_0 50.4501 30.5234 50.4398 30.5582 0 +heading_road_0 50.50487553 30.46351612 50.50533954 30.46341956 0 +heading_city_90 50.4501 30.5234 50.4398 30.5582 90 +heading_road_90 50.50487553 30.46351612 50.50533954 30.46341956 90 +heading_city_180 50.4501 30.5234 50.4398 30.5582 180 +heading_road_180 50.50487553 30.46351612 50.50533954 30.46341956 180 +heading_city_270 50.4501 30.5234 50.4398 30.5582 270 +heading_road_270 50.50487553 30.46351612 50.50533954 30.46341956 270 +offroad_near 49.83531383900768 32.33332961797714 49.64642130219407 31.933660358190536 +offroad_far 50.4501 30.5234 46 31 +same_point 50.4501 30.5234 50.4501 30.5234 diff --git a/docs/performance/route-calculation.md b/docs/performance/route-calculation.md index c1a4302..f14d4af 100644 --- a/docs/performance/route-calculation.md +++ b/docs/performance/route-calculation.md @@ -1,5 +1,71 @@ # Route calculation +## Intermittent delays, 2026-10-28 + +Two independent delays were reproduced on M9304002366 using the product's +`NavigationWorker` in a separate process with the installed core, all 26 maps, +the CH sidecar, and Organic Maps turn generation. No UI simulation or service +restart was needed for these measurements. + +Dropping a pin used to run reverse geocoding to replace the coordinates on its +card with a street/address. It used the same queue as routing. For Maidan +(50.4501, 30.5234) to Kozatskiy (50.451725, 30.5220848), requesting a route +100 ms after the lookup began waited **50,346 ms** in the queue; the route +calculation itself took 575 ms. Repeating the route took 408 ms overall. +Passing a cancellation controller reduced the first request to 13,564 ms, but +the core's initial map/road loading still held the queue for 12,894 ms. + +Pin reverse geocoding is removed: the card retains its coordinates and distance, +and routing uses the selected coordinates directly. There is no extra address +thread. Named destinations and typed address search still use their existing +names/search path. The same hotel route now takes **572 ms**, then **342 ms**, +including worker publication; both produce 179 m / 16 geometry points. + +Separately, the point (46.0, 31.0) has no CH route from Maidan. Previously it +silently switched to HH and returned a route after **12,508 / 10,077 ms**. +The selected CH router now reports that failure in **781 / 221 ms**. A missing +or stale selected sidecar also reports failure instead of changing engines. +The existing `disable-ch` marker/environment switch explicitly selects HH +(or A* for maps without HH); a failed HH query no longer retries with A*. +This intentionally trades automatic slow retries for visible route failure. + +Successful routing remains functional: Kyiv–Dnipro (478,427 m / 4,707 points) +took 6,399 / 6,039 ms including Organic Maps turns. Explicit HH mode on +Maidan–Troieshchyna produced a 15,171 m route in 6,248 / 6,634 ms. + +These figures exclude one-time router warm-up. A first request can still wait +for that initialization. `worker=request_begin` now records `queue_ms`, +`worker=route_ready` records the warm-up wait, and `worker=request_done` records +work and end-to-end time even for cancelled/failed requests. Existing CH-stage +and Organic Maps timings remain. The older `worker=placed runmask=1` field is +a success flag for allowing all CPUs, not a CPU0-only affinity mask. + +`make` builds `bench/libroute_worker_bench.so` alongside `route_bench_run`. +Copy both to `/tmp` on the radio and supply the routing XML: + +```sh +ROUTE_WORKER_MAX_MS=5000 /tmp/route_bench_run worker /navi_map/osm /tmp/routing.xml \ + /navi_map/osm/car.chr 50.4501 30.5234 50.451725 30.5220848 route +``` + +The runner uses the actual worker, timestamps its trace to stdout, repeats the +request twice, and checks the revision and route outcome. `reject` expects no +route, `cold` submits before warm-up, and sidecar `-` selects OsmAnd explicitly. +The optional latency limit applies to each submitted request; a 120-second +process timeout bounds a stuck diagnostic. It does not control the installed +navigation process. The runner is not included in the installed backend/image. + +Validation: QNX build and ELF checks, 35 host tests, pin-card render, and the +four on-radio worker cases above. After installing the backend and rebooting once, +a real long-press pin at (50.45132, 30.52168) retained its coordinates and +produced an 88 m route preview: queue 0 ms, warm-up wait 0 ms, request work +957 ms, Organic Maps 11 ms. No address job was queued. + +Earlier measurements below describe older +router implementations and hardware; they are retained as history. + +## Earlier routing measurements + Measured on the bench unit (M9148801407, 2 × Cortex-A9) with the Kyiv map (`kyiv.obf`, 87 MB, with two HH routing sections), 2026-10-15, using `deploy/bench/route_bench.cpp` (see below). @@ -124,3 +190,118 @@ cd /tmp; ./route_bench_run /datastore/navicore-backend/maps/kyiv.obf /tmp/routin `ROUTE_BENCH_CORE=/tmp/x/libOsmAndCore_shared.so` tries another core without installing it (the library's RPATH would otherwise win). + +## Ukraine worker survey, 2026-10-28 + +The real navigation worker was run in separate diagnostic processes on the +bench radio with the installed core, all 26 Ukraine maps, car CH sidecar and +Organic Maps turns. Seed 20261028 sampled car-road points from the maps, +including mid-segment points. The 128 requests comprise 52 regional, 52 +cross-region and 24 short same-road cases, with every pair reversed. Requests +were sequential in batches of eight. Map initialization preceded each batch +and is excluded from the request timings; rendering and interactive UI latency +are not exercised by this helper. The production backend was not changed. + +| Cases | Returned / requested | Median request | Maximum request | +|---|---:|---:|---:| +| Regional | 52 / 52 | 0.551 s | 4.281 s | +| Cross-region | 52 / 52 | 4.077 s | 30.405 s | +| Short | 18 / 24 | 0.188 s | 0.540 s | + +Returned is not equivalent to correct. Of the 122 returned routes, 94 start +or end more than 100 m from the requested road point (maximum 930.5 m). +Six short requests publish no route after geometry collapses to fewer than +two points; two further short requests return zero-length geometry. All eight +log `worker=omaps_error why=route has fewer than two points`. The six empty +results lack a `worker=route_failed` reason in the current product trace. + +The road snapper lets up to eight roads within 1 km compete on total route +cost. Its 120 ms/m snap penalty permits a farther road to win by saving +driving time. In `regional_000_f` the requested road is a zero-distance +candidate, but the selected road is 194 m away. Short requests can select +approaches that collapse onto the same junction instead of the requested +short road. A diagnostic nearest-road-only run corrected all 18 selected +problem cases: 18 returned routes, endpoint gaps below the output's 0.1 m +resolution and no turn errors. Explicit HH also returned correct endpoints +for seven selected cases. This establishes the snap-selection cause in those +cases, not a validated general production policy for ambiguous locations, +headings, disconnected roads or grade-separated crossings. + +The earlier `(46, 31)` destination is a different failure: diagnostics find +zero eligible destination roads within the CH snap radius. CH rejects it in +0.826 s. Explicit HH returns a route in 11.958 s, but its geometry ends +24,653.4 m from the destination. That result is not evidence that fallback +successfully reaches this point. + +The 30.405 s Lviv-region to Kherson-region request spent 0.132 s snapping, +1.199 s in CH search, 7.334 s loading roads, 10.810 s preparing the result +and 9.341 s annotating Organic Maps turns. It reproduces a long calculation +without reverse-geocoding or router fallback; most time is after graph search. + +Reproduction inputs are `deploy/bench/ukraine-routing-20261028.tsv`. +`tools/ch/sample_route_cases.py ROUTING_XML MAP_DIR OUTPUT_DIR [SEED]` +generates new inputs and road provenance. After `make`, copy the worker bench +library and launcher from `build/qnx/bench` to `/tmp` on the bench. Invoke: + +```sh +ROUTE_BENCH_CORE=/open-navicore/libOsmAndCore_shared.so \ +LD_LIBRARY_PATH=/open-navicore:/usr/lib:/lib \ + /tmp/route_bench_run worker /navi_map/osm /tmp/routing.xml \ + /navi_map/osm/car.chr /tmp/cases.tsv batch +``` + +Use sidecar `-` for an explicit HH comparison. Only the diagnostic worker +build enables snap traces and `ROUTE_BENCH_NEAREST_ONLY=1`; neither affects +the production backend. Each request has a 120 s diagnostic process timeout. +`tools/ch/summarize_route_batch.py EVIDENCE_DIR` reads `cases.json` and +`batch-NN.log`, writing endpoint/geometry flags in `analysis.json` and +`results.csv`. Flags require investigation. This survey checks offline map +routing, not current road accessibility or all turn restrictions. + + +## Routing fixes and repeated survey, 2026-10-28 + +Endpoint road selection now precedes journey-cost optimization. The nearest +eligible road is used; roads within 1 m of the nearest projection remain tied +for junction/overlap handling. Direction and one-way restrictions still apply. +An endpoint road that cannot connect to the sidecar fails explicitly; the +planner no longer substitutes a nearby graph node. The worker rejects collapsed +geometry and results outside the endpoint snap limits before turn annotation. +HH additionally validates its returned endpoints against the nearest eligible +roads, and identical origin/destination requests stop without driving a loop. + +Long CH routes retain adjacent-road snapshots only for the current request. +Snapshots contain road objects and node indexes, not mutable search wrappers. +OsmAnd uses its existing pre-attached-road interface; Organic Maps reads the +same snapshot. Both original turn-generation passes remain enabled, including +OsmAnd roundabouts. No core library or map file changes are required. + +The same 128-case survey returned 126 routes with endpoint gaps below the +0.1 m reporting resolution, zero turn errors and zero degenerate geometries. +All 24 short requests passed. The two rejected requests are the forward/reverse +pair involving Crimean service road 26164803745: its 21 map points share no +node with any other road in that regional routing index. Previously the +snapper silently selected a different street. Explicit HH likewise stopped +98.2 m from this endpoint before the stricter validation was added. + +| Metric | Before | After | +|---|---:|---:| +| Returned routes with endpoint gap over 100 m | 94 | 0 | +| Short requests returning a route | 18 / 24 | 24 / 24 | +| Turn-generation errors | 8 | 0 | +| Maximum request time | 30.405 s | 14.906 s | +| 95th percentile of returned-route times | 15.258 s | 9.648 s | + +A separate nine-case cache A/B comparison used the same corrected snapping +in both variants. Geometry and maneuver fingerprints, distance, duration and +maneuver counts matched in every case. The four long requests improved from +23.079 / 19.427 / 27.809 / 25.323 s to 13.278 / 9.703 / 13.971 / 11.573 s. +For the 27.809 s request, preparation fell from 9.914 to 3.031 s and Organic +Maps annotation from 8.559 to 0.871 s. The diagnostic-only +`ROUTE_BENCH_NO_ROAD_CACHE=1` reproduces the uncached control. These are worker +measurements on the bench; cold map opening and display latency are separate. + +`deploy/bench/ukraine-routing-controls.tsv` exercises headings, nearby off-road +pins, a distant off-road destination and an identical origin/destination. +The optional fifth numeric field after the case id is the starting heading +in degrees. The distant and identical-point controls must be rejected. diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 0bc396c..a5ee718 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -110,6 +110,7 @@ onc_test(dev_menu_test SOURCES dev_menu_test.cpp LIBS navigation_ui) onc_test(reroute_state_test SOURCES reroute_state_test.cpp INCLUDES ${ONC_ROOT}/backends/osmand) onc_test(labels_test SOURCES labels_test.cpp LIBS navigation_ui) onc_test(route_check_test SOURCES route_check_test.cpp LIBS navigation_ui m) +onc_test(snap_policy_test SOURCES snap_policy_test.cpp INCLUDES ${ONC_ROOT}/backends/osmand) # Address search index: built from a small dump fixture by the real builder. find_package(Python3 COMPONENTS Interpreter REQUIRED) set(_search_fixture ${CMAKE_CURRENT_BINARY_DIR}/search_fixture.idx) diff --git a/tests/navigation_ui_test.cpp b/tests/navigation_ui_test.cpp index af027fb..e57bbde 100644 --- a/tests/navigation_ui_test.cpp +++ b/tests/navigation_ui_test.cpp @@ -428,17 +428,18 @@ void test_place_card_and_back() assert(!view.apply_routes(cancelled, {route})); assert(model.screen() == Screen::FreeDrive); - // A dropped pin is a place card too: its address arrives later (for - // that pin only), and Navigate routes to it. + // A dropped pin keeps its coordinates on the card and routes to that + // exact point without an address lookup. Destination pin{"pin:50.44000, 30.52000", "Dropped pin", "50.44000, 30.52000", "", 50.44, 30.52}; assert(view.show_place_card(pin, "pin")); assert(model.place_card_is_pin()); - assert(!view.set_place_subtitle("pin:other", "вулиця Інша")); - assert(view.set_place_subtitle(pin.id, "вулиця Хрещатик, 22 · 0.4 km")); - assert(model.place_card()->subtitle == "вулиця Хрещатик, 22 · 0.4 km"); + assert(model.place_card()->subtitle == pin.subtitle); assert(view.select_place(*model.place_card())); assert(model.destination() && model.destination()->id == pin.id); + assert(model.destination()->latitude == pin.latitude); + assert(model.destination()->longitude == pin.longitude); + assert(model.destination()->subtitle == pin.subtitle); assert(view.close_place_card() && !model.place_card_is_pin()); view.set_pin_marker(true, 600, 300); // no card, no crash; hidden on rebuild settle(view, 2); diff --git a/tests/route_check_test.cpp b/tests/route_check_test.cpp index 6c6fff4..411d61a 100644 --- a/tests/route_check_test.cpp +++ b/tests/route_check_test.cpp @@ -15,6 +15,16 @@ RouteLeg leg(long long road, double lat0, double lon0, double lat1, double lon1) int main() { + using navicore_osmand::check_route_extent; + // A closed loop can have identical endpoints but nonzero travelled length. + assert(check_route_extent({50,30}, {50,30}, {50,30}, {50,30}, 300).usable); + assert(!check_route_extent({50,30}, {50,30.001}, {50,30}, {50,30}, 0).usable); + // HH's former apparent success at an off-road destination must be rejected. + assert(!check_route_extent({50,30}, {46,31}, {50,30}, {46.22,31}, 525000).usable); + // Being inside the global snap radius does not permit HH to skip an + // isolated endpoint road: this point was on a road, not 98 m from one. + assert(!check_route_extent({50,30}, {50.01,30}, {50.00088,30}, {50.01,30}, 1200, 3, 3).usable); + assert(check_route_extent({50,30}, {50.01,30}, {50,30}, {50.01,30}, 1113).usable); // An empty route is not usable. assert(!check_route_legs({}).ok()); diff --git a/tests/snap_policy_test.cpp b/tests/snap_policy_test.cpp new file mode 100644 index 0000000..48cbe9f --- /dev/null +++ b/tests/snap_policy_test.cpp @@ -0,0 +1,24 @@ +#include "snap_policy.h" +#include +#include + +struct Snap { int road; double metres; }; +int main() +{ + // Real Cherkasy failure: the 194 m road must not beat the requested road + // even when its driving cost is lower. Input priority order is irrelevant. + std::vector roads{{6,194}, {2,107}, {1,0}, {3,112}}; + navicore_osmand::keep_nearest_roads(roads); + assert(roads.size() == 1 && roads[0].road == 1); + // Shared junctions remain available in either legal travel direction. + roads = {{1,0.02}, {2,0.03}, {3,5.7}}; + navicore_osmand::keep_nearest_roads(roads); + assert(roads.size() == 2); + // An off-road pin uses the closest road, without a larger search radius. + roads = {{1,55}, {2,15}, {3,15.5}}; + navicore_osmand::keep_nearest_roads(roads); + assert(roads.size() == 2 && roads[0].road == 2); + roads = {{1,1001}, {2,std::numeric_limits::quiet_NaN()}}; + navicore_osmand::keep_nearest_roads(roads); + assert(roads.empty()); +} diff --git a/tests/ui_render_tool.cpp b/tests/ui_render_tool.cpp index 8f2adac..69eb639 100644 --- a/tests/ui_render_tool.cpp +++ b/tests/ui_render_tool.cpp @@ -296,7 +296,7 @@ int main(int argc, char** argv) ok = write(view, out + (failed ? "/place_failed.argb" : "/place_calculating.argb")) && ok; } { - // Dropped pin (long press) with its address; heading-up dimmed + // Dropped pin (long press) with its coordinates; heading-up dimmed // (no heading known yet). NavigationModel model; NavigationView view(model, 1024, 574); @@ -305,7 +305,7 @@ int main(int argc, char** argv) (void)model.set_map_view(state); settle(view); (void)view.show_place_card({"pin:50.44000, 30.52000", loc::tr(loc::Str::DroppedPin), - "вулиця Хрещатик, 22 · " + loc::format_distance(400.0), "", + "50.44000, 30.52000 · " + loc::format_distance(400.0), "", 50.44, 30.52}, "pin"); view.set_pin_marker(true, 640, 300); settle(view); diff --git a/tools/ch/sample_route_cases.py b/tools/ch/sample_route_cases.py new file mode 100644 index 0000000..39644f5 --- /dev/null +++ b/tools/ch/sample_route_cases.py @@ -0,0 +1,97 @@ +"""Seeded route cases from interior car-road points, one OBF region at a time. + +Usage: sample_route_cases.py ROUTING_XML MAP_DIR OUTPUT_DIR [SEED] +Writes sampled endpoints with road provenance, and 128 forward/reverse cases: +26 regional pairs, 26 cross-region pairs, and 12 short same-road pairs. +The profile approximation is the one used by the CH graph builder. Runtime +snapping and route availability are checked by the real navigation worker. +""" +import gc +import json +from pathlib import Path +import random +import sys + +import obf_routing +import routing_rules +from gen_pairs import km, to_lat_lon + + +def sample(xml, directory, output, seed): + output = Path(output) + output.mkdir(parents=True, exist_ok=True) + rng = random.Random(seed) + profile = routing_rules.Profile(xml) + regions = {} + shorts = {} + for path in sorted(Path(directory).glob('Ukraine_*.obf')): + region = path.name[len('Ukraine_'):-len('_europe_2.obf')] + index = obf_routing.RoutingIndex(str(path)) + access = {} + eligible = [] + for road in index.roads.values(): + if road.types not in access: + tags = dict(index.rules[t] for t in road.types if t in index.rules) + access[road.types] = profile.road(tags)[0] + if access[road.types] and len(road.xs) >= 4: + eligible.append(road) + selected = rng.sample(eligible, min(256, len(eligible))) + points = [] + short = [] + for road in selected: + i = rng.randrange(1, len(road.xs) - 2) + a = to_lat_lon(road.xs[i], road.ys[i]) + b = to_lat_lon(road.xs[i + 1], road.ys[i + 1]) + # Mid-segment endpoints exercise road snapping, rather than merely + # selecting CH nodes. The original road and indexes stay recorded. + point = tuple((x + y) / 2 for x, y in zip(a, b)) + points.append(dict(region=region, road=road.id, segment=i, + lat=point[0], lon=point[1])) + first = to_lat_lon(road.xs[1], road.ys[1]) + last = to_lat_lon(road.xs[-2], road.ys[-2]) + if 0.015 <= km(first, last) <= 0.8: + short.append((dict(region=region, road=road.id, segment=1, + lat=first[0], lon=first[1]), + dict(region=region, road=road.id, segment=len(road.xs)-2, + lat=last[0], lon=last[1]))) + regions[region] = points + shorts[region] = short + print(region, 'roads', len(index.roads), 'car_candidates', len(eligible), + 'sampled', len(points), 'short', len(short), flush=True) + # Release each decoded region before loading the next one. + del index, eligible, selected, road + gc.collect() + + cases = [] + def add(kind, a, b): + distance = km((a['lat'], a['lon']), (b['lat'], b['lon'])) + group = len(cases) // 2 + for suffix, start, end in [('f', a, b), ('r', b, a)]: + cases.append(dict(id=f'{kind}_{group:03d}_{suffix}', kind=kind, + start=start, end=end, air_km=distance)) + for region, points in regions.items(): + for _ in range(10000): + a, b = rng.sample(points, 2) + if 2 <= km((a['lat'], a['lon']), (b['lat'], b['lon'])) <= 40: + add('regional', a, b) + break + else: + raise RuntimeError('no regional pair in ' + region) + names = list(regions) + rng.shuffle(names) + for i, region in enumerate(names): + other = names[(i + 1) % len(names)] + add('cross', rng.choice(regions[region]), rng.choice(regions[other])) + for region in rng.sample([n for n in names if shorts[n]], 12): + add('short', *rng.choice(shorts[region])) + (output / 'cases.json').write_text(json.dumps(dict(seed=seed, regions=regions, cases=cases), + ensure_ascii=False, indent=2)) + with (output / 'cases.tsv').open('w') as stream: + for case in cases: + a, b = case['start'], case['end'] + stream.write(f"{case['id']} {a['lat']:.8f} {a['lon']:.8f} {b['lat']:.8f} {b['lon']:.8f}\n") + print('cases', len(cases), 'seed', seed, flush=True) + + +if __name__ == '__main__': + sample(*sys.argv[1:4], int(sys.argv[4]) if len(sys.argv) > 4 else 20261028) diff --git a/tools/ch/summarize_route_batch.py b/tools/ch/summarize_route_batch.py new file mode 100644 index 0000000..f371f47 --- /dev/null +++ b/tools/ch/summarize_route_batch.py @@ -0,0 +1,49 @@ +"""Summarize route_worker_bench batch-NN.log files alongside cases.json. + +Usage: summarize_route_batch.py EVIDENCE_DIR +Writes analysis.json and results.csv; endpoint flags require manual diagnosis. +A returned route is not proof of road connectivity or endpoint correctness. +""" +import csv,json,pathlib,statistics,sys +from collections import Counter +p=pathlib.Path(sys.argv[1]) +meta={x['id']:x for x in json.loads((p/'cases.json').read_text())['cases']} +rows=[] +def fields(line): return dict(x.split('=',1) for x in line.strip().split() if '=' in x) +for log in sorted(p.glob('batch-[0-9][0-9].log')): + case={} + for line in log.read_text().splitlines(): + if line.startswith('batch=begin '): case=fields(line);case['log']=log.name + elif 'worker=route_failed ' in line: case['failure_reason']=fields(line).get('why','unknown') + elif 'worker=route_rejected ' in line: case['rejected']=fields(line) + elif 'worker=omaps_error why=' in line: case['turn_error']=line.split('why=',1)[1].rsplit(' ms=',1)[0] + elif line.startswith('ch_diag start_roads='): case['snap']=fields(line) + elif 'worker=ch_route ' in line: case['timing']=fields(line) + elif line.startswith('batch=case '): + case.update(fields(line));case.update({k:meta[case['id']][k] for k in ('kind','start','end','air_km')}) + for k in ['wall_ms','routes','air_m','distance_m','start_gap_m','end_gap_m','geometry_m','max_step_m','finite','maneuvers','omaps_errors']: + case[k]=float(case[k]) + case['endpoint_suspect']=case['status']=='ok' and max(case['start_gap_m'],case['end_gap_m'])>100 + case['degenerate']=case['status']=='ok' and case['air_m']>10 and case['geometry_m']<1 + case['distance_suspect']=case['status']=='ok' and abs(case['geometry_m']-case['distance_m'])>max(100,case['distance_m']*.05) + rows.append(case) +if not rows: print('No completed cases');raise SystemExit +ok=[r for r in rows if r['status']=='ok'] +times=sorted(r['wall_ms'] for r in ok) +summary={'completed':len(rows),'expected':len(meta),'status':dict(Counter(r['status'] for r in rows)), + 'failure_reasons':dict(Counter(r.get('failure_reason','unknown') for r in rows if r['status']!='ok')), + 'endpoint_suspect':sum(r['endpoint_suspect'] for r in rows),'distance_suspect':sum(r['distance_suspect'] for r in rows), + 'degenerate':sum(r['degenerate'] for r in rows), + 'omaps_errors':sum(r['omaps_errors'] for r in rows),'nonfinite':sum(not r['finite'] for r in ok), + 'latency_ms':{'median':statistics.median(times),'p95':times[min(len(times)-1,int(.95*len(times)))],'max':max(times)} if times else {}} +for kind in ['regional','cross','short']: + part=[r for r in rows if r['kind']==kind] + summary[kind]={'completed':len(part),'status':dict(Counter(r['status'] for r in part))} +(p/'analysis.json').write_text(json.dumps({'summary':summary,'cases':rows},indent=2,ensure_ascii=False)) +with (p/'results.csv').open('w') as f: + keys=['id','kind','status','wall_ms','distance_m','start_gap_m','end_gap_m','geometry_m','max_step_m','maneuvers','omaps_errors','endpoint_suspect','distance_suspect','degenerate','failure_reason','turn_error'] + w=csv.DictWriter(f,fieldnames=keys,extrasaction='ignore');w.writeheader();w.writerows(rows) +print(json.dumps(summary,indent=2)) +for r in rows: + if r['status']!='ok' or r['endpoint_suspect'] or r['distance_suspect'] or r['omaps_errors']: + print('FLAG',r['id'],r['start']['region'],r['end']['region'],r['status'],r.get('failure_reason'),r['wall_ms'],r['start_gap_m'],r['end_gap_m'],r.get('snap',{}))