From c1f874b840b8969a7182852e8a6ef91046a403e1 Mon Sep 17 00:00:00 2001 From: Oleksandr Shyshatskyi Date: Tue, 27 Oct 2026 15:14:26 +0200 Subject: [PATCH] routing: keep picked routes alive, one CH search, warm router - A recent picked on the Search screen set the query to its title; the debounced search for it then cancelled the route on the one worker and the route was never published. No search once a destination is picked (NavigationModel::search_wanted). - CH seeds every start/end snap candidate into one bidirectional search (was up to 16 pair searches plus a rerun over the paged sidecar) and checks the route's cancellation while it runs. - Both ends on one CH node: A* directly instead of HH (49 s for a long route over all of Ukraine on the bench); a cancelled route stops the fallback chain. - The routing maps (10 s to open for Ukraine) open on a background thread at priority 9 once the worker starts: when a place card or another screen opens, or 30 s after start-up. The worker itself runs at 10. Co-Authored-By: Claude Opus 5.5 --- backends/osmand/ch/ch_query.h | 36 +++++++++++++- backends/osmand/ch/ch_sidecar.h | 45 +++++++++-------- backends/osmand/ch_planner.cpp | 5 +- backends/osmand/navigation_worker.cpp | 70 +++++++++++++++++++++------ backends/osmand/osmand_engine.cpp | 13 ++++- backends/osmand/ui/navigation_model.h | 7 +++ tests/ch_test.cpp | 36 ++++++++++++++ tests/navigation_ui_test.cpp | 4 ++ 8 files changed, 176 insertions(+), 40 deletions(-) diff --git a/backends/osmand/ch/ch_query.h b/backends/osmand/ch/ch_query.h index 979d39e..3c629e1 100644 --- a/backends/osmand/ch/ch_query.h +++ b/backends/osmand/ch/ch_query.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -106,18 +107,39 @@ class BasicQuery { public: explicit BasicQuery(Store store) : store_(std::move(store)) {} + // A start or end node and what reaching it costs already (snapping onto it). + struct Seed { u32 node, cost; }; + // Cheapest cost from source to target, INF when unreachable. `meet` is // the node where the two upward searches met. u32 run(u32 source, u32 target, u32& meet) + { + const Seed s {source, 0}, t {target, 0}; + return run(&s, 1, &t, 1, meet); + } + + // Cheapest path from any source to any target, seeds' costs included: one + // search instead of one per pair. INF when unreachable or when `cancelled` + // (asked every 1024 settled nodes) says stop. source_of()/target_of() + // name the seeds the path starts and ends at. + u32 run(const Seed* sources, size_t source_count, const Seed* targets, size_t target_count, + u32& meet, const std::function& cancelled = {}) { settled = 0; f_.reset(); b_.reset(); using Item = std::pair; std::priority_queue, std::greater> qf, qb; - f_.set(source, 0, source); qf.push({0, source}); - b_.set(target, 0, target); qb.push({0, target}); + const auto seed = [](Table& table, auto& queue, const Seed& s) { + const Entry* known = table.find(s.node); + if (known && known->dist <= s.cost) return; + table.set(s.node, s.cost, s.node); + queue.push({s.cost, s.node}); + }; + for (size_t i = 0; i < source_count; ++i) seed(f_, qf, sources[i]); + for (size_t i = 0; i < target_count; ++i) seed(b_, qb, targets[i]); u32 best = INF; meet = INF; while (!qf.empty() || !qb.empty()) { + if ((settled & 1023u) == 1023u && cancelled && cancelled()) { meet = INF; return INF; } const u32 top = std::min(qf.empty() ? INF : qf.top().first, qb.empty() ? INF : qb.top().first); if (top >= best) break; const bool forward = !qf.empty() && (qb.empty() || qf.top().first <= qb.top().first); @@ -173,6 +195,10 @@ class BasicQuery { return true; } + // The seed the last run()'s path starts at (seeds are their own parents). + u32 source_of(u32 meet) const { return root(f_, meet); } + u32 target_of(u32 meet) const { return root(b_, meet); } + size_t settled = 0; // nodes settled by the last run() private: @@ -222,6 +248,12 @@ class BasicQuery { u32 used_ = 0; }; + static u32 root(const Table& table, u32 v) + { + for (const Entry* e = table.find(v); e && e->parent != v; e = table.find(v)) v = e->parent; + return v; + } + // The cheapest arc at -> to in the upward out (forward) or in arcs of `at`. bool find(bool forward, u32 at, u32 to, QArc& result) { diff --git a/backends/osmand/ch/ch_sidecar.h b/backends/osmand/ch/ch_sidecar.h index a007a2d..0b3afac 100644 --- a/backends/osmand/ch/ch_sidecar.h +++ b/backends/osmand/ch/ch_sidecar.h @@ -311,7 +311,7 @@ inline const QArc* SidecarStore::arcs(bool forward, u32 node, u32& count, std::v // sidecar's page cache and the query state are not shared). class Router { public: - enum class Status { Ok, NoRoute, Inconsistent }; + enum class Status { Ok, NoRoute, Inconsistent, Cancelled }; explicit Router(Sidecar& sidecar) : sidecar_(sidecar), query_(sidecar.store()) {} @@ -320,11 +320,14 @@ class Router { // (120 ms per metre) against the route cost, so a far node does not win on route // cost alone. With a start heading (degrees clockwise from north) a start node more // than 120 degrees off it, i.e. behind the car, costs kReversePenaltyMs more, as - // OsmAnd's own routers charge for starting against the initial direction. On success - // runs are the road stretches in travel order (empty when both ends snap to the same - // node: too short to route here) and cost is the routing cost in milliseconds. + // OsmAnd's own routers charge for starting against the initial direction. All + // candidates seed one search with those costs (the best of every pair, in one run). + // On success runs are the road stretches in travel order (empty when both ends snap + // to the same node: too short to route here) and cost is the routing cost in + // milliseconds. `cancelled`, when set, is asked during the search. Status route(int sx, int sy, int ex, int ey, std::vector& runs, u32& cost, - double start_heading_degrees = kNoHeading) + double start_heading_degrees = kNoHeading, + const std::function& cancelled = {}) { runs.clear(); sidecar_.nearest_nodes(sx, sy, kSnapNodes, from_); @@ -332,23 +335,22 @@ class Router { const auto too_far = [](const Sidecar::Candidate& c) { return c.metres > kMaxSnapMetres; }; from_.erase(std::remove_if(from_.begin(), from_.end(), too_far), from_.end()); to_.erase(std::remove_if(to_.begin(), to_.end(), too_far), to_.end()); - double best = 1e18; - u32 best_from = 0, best_to = 0, best_cost = INF; - for (const auto& s : from_) { - for (const auto& t : to_) { - u32 meet = 0; - const u32 c = query_.run(s.node, t.node, meet); - if (c == INF) continue; - const double total = c + 120.0 * (s.metres + t.metres) + - reverse_penalty(sx, sy, s, start_heading_degrees); - if (total < best) { best = total; best_from = s.node; best_to = t.node; best_cost = c; } - } - } - if (best_cost == INF) return Status::NoRoute; + sources_.clear(); + targets_.clear(); + for (const auto& s : from_) + sources_.push_back({s.node, (u32)std::lround(120.0 * s.metres + + reverse_penalty(sx, sy, s, start_heading_degrees))}); + for (const auto& t : to_) targets_.push_back({t.node, (u32)std::lround(120.0 * t.metres)}); u32 meet = 0; - query_.run(best_from, best_to, meet); // path_edges reads the last run - if (!query_.path_edges(best_from, best_to, meet, edges_)) return Status::Inconsistent; - cost = best_cost; + const u32 total = query_.run(sources_.data(), sources_.size(), targets_.data(), targets_.size(), + meet, cancelled); + if (total == INF) return cancelled && cancelled() ? Status::Cancelled : Status::NoRoute; + const u32 from = query_.source_of(meet), to = query_.target_of(meet); + u32 offsets = 0; + for (const auto& s : sources_) if (s.node == from) offsets += s.cost; + for (const auto& t : targets_) if (t.node == to) offsets += t.cost; + if (!query_.path_edges(from, to, meet, edges_)) return Status::Inconsistent; + cost = total - std::min(total, offsets); return merge(runs) ? Status::Ok : Status::Inconsistent; } @@ -397,6 +399,7 @@ class Router { Sidecar& sidecar_; BasicQuery query_; std::vector from_, to_; + std::vector::Seed> sources_, targets_; std::vector edges_; }; diff --git a/backends/osmand/ch_planner.cpp b/backends/osmand/ch_planner.cpp index a1724a9..5402ff1 100644 --- a/backends/osmand/ch_planner.cpp +++ b/backends/osmand/ch_planner.cpp @@ -93,14 +93,17 @@ ChPlanner::Segments ChPlanner::route(RoutePlannerFrontEnd& front_end, const SHAR auto step = Clock::now(); std::vector runs; onc_ch::u32 cost = 0; + const auto progress = context->progress; const auto status = impl_->router->route(start_x, start_y, end_x, end_y, runs, cost, - start_heading_degrees); + start_heading_degrees, + [&progress] { return progress && progress->isCancelled(); }); timing_.search_ms = ms_since(step); timing_.settled = impl_->router->settled(); timing_.base_edges = impl_->router->edges().size(); timing_.road_runs = runs.size(); 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 {}; } // Each stretch needs its RouteDataObject: loading the tile at a point of the road diff --git a/backends/osmand/navigation_worker.cpp b/backends/osmand/navigation_worker.cpp index f3e2027..112a9c8 100644 --- a/backends/osmand/navigation_worker.cpp +++ b/backends/osmand/navigation_worker.cpp @@ -262,11 +262,15 @@ std::vector lanes_of(const SHARED_PTR& turn) // Routing runs for seconds. nv_navigation is pinned to one core, where the // render thread (priority 20) leaves it about half the CPU: a 15 km route // took 7.3 s there against 3.7 s free to use either core (route_bench, -// 2026-10-15). Below the default priority 10 it only takes idle time from -// the other core's services. -constexpr int kWorkerPriority = 9; - -void place_worker_thread() +// 2026-10-15). At the default priority 10 it shares the other core with its +// services in turn; at 9 it only got their idle time, and a busy Android +// Auto session stretched a route by seconds. +constexpr int kWorkerPriority = 10; +// Opening the routing maps (about 10 s for all of Ukraine, 2026-10-27) runs +// ahead of the first route on idle time only. +constexpr int kWarmupPriority = 9; + +void place_worker_thread(int priority = kWorkerPriority, const char* name = "worker=placed") { const unsigned cpus = _syspage_ptr ? _syspage_ptr->num_cpu : 1u; const unsigned mask = cpus >= 32u ? ~0u : (1u << cpus) - 1u; @@ -276,12 +280,12 @@ void place_worker_thread() sched_param parameters{}; bool lowered = false; if (pthread_getschedparam(pthread_self(), &policy, ¶meters) == 0) { - parameters.sched_priority = kWorkerPriority; + parameters.sched_priority = priority; lowered = pthread_setschedparam(pthread_self(), policy, ¶meters) == 0; } char line[80]; - std::snprintf(line, sizeof(line), "worker=placed cpus=%u runmask=%d priority=%d", - cpus, any_cpu ? 1 : 0, lowered ? kWorkerPriority : -1); + std::snprintf(line, sizeof(line), "%s cpus=%u runmask=%d priority=%d", + name, cpus, any_cpu ? 1 : 0, lowered ? priority : -1); trace(line); } @@ -399,6 +403,11 @@ class NavigationWorker::Impl { // against later members such as has_pending_ and stopping_. thread_ = std::thread(&Impl::run, this); trace("worker=thread_started"); + // The first route would otherwise wait for every map to open. + warmup_ = std::thread([this] { + place_worker_thread(kWarmupPriority, "worker=warmup_placed"); + (void)prepare_router(); + }); } ~Impl() { stop(); } @@ -481,6 +490,8 @@ class NavigationWorker::Impl { if (active_) active_->cancel(); condition_.notify_one(); } + stop_warmup_ = true; + if (warmup_.joinable()) warmup_.join(); if (thread_.joinable()) thread_.join(); if (router_ready_) { for (const std::string& path : map_paths_) @@ -626,10 +637,20 @@ class NavigationWorker::Impl { return output; } + // Once, by the warm-up thread or the first route, whichever comes first; + // the other waits for it. bool prepare_router() { + std::lock_guard lock(router_mutex_); if (router_ready_) return true; - if (routing_xml_.empty() || map_paths_.empty()) return false; + if (router_failed_ || routing_xml_.empty() || map_paths_.empty()) return false; + router_failed_ = !open_router(); + return !router_failed_; + } + + bool open_router() + { + const auto started = std::chrono::steady_clock::now(); const std::string path = write_routing_xml(routing_xml_); // fileName namespaces imported configurations. A non-empty value // would rename "car" and make build("car") return an empty router. @@ -651,7 +672,15 @@ class NavigationWorker::Impl { std::size_t routable = 0; std::size_t with_hh = 0; std::vector routable_maps; + std::vector opened; for (const std::string& path : map_paths_) { + if (stop_warmup_) { + // Shutting down: close what is open, route never. + for (const std::string& done : opened) (void)closeBinaryMapFile(done); + trace("worker=router_stopped"); + return false; + } + opened.push_back(path); const auto map = initBinaryMapFile(path, false, true); if (map && !map->routingIndexes.empty()) { ++routable; @@ -671,9 +700,11 @@ class NavigationWorker::Impl { // crosses into a file without it would have no network there. has_hh_ = with_hh == routable; { - char line[96]; - std::snprintf(line, sizeof(line), "worker=router hh=%d routable=%zu hh_car=%zu", - has_hh_ ? 1 : 0, routable, with_hh); + char line[128]; + std::snprintf(line, sizeof(line), "worker=router hh=%d routable=%zu hh_car=%zu open_ms=%lld", + has_hh_ ? 1 : 0, routable, with_hh, + static_cast(std::chrono::duration_cast( + std::chrono::steady_clock::now() - started).count())); trace(line); } // Contraction-hierarchy routing: only with a sidecar built from exactly these maps. @@ -775,6 +806,9 @@ class NavigationWorker::Impl { if (request.heading_degrees) trace_result("worker=route_heading", request.revision, static_cast(*request.heading_degrees)); + // 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; if (ch_) { auto context = new_context(); std::string why; @@ -791,10 +825,11 @@ class NavigationWorker::Impl { found.push_back(std::move(segments)); } 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"; } } if (found.empty() && !cancel->isAborted()) method = "hh"; - if (found.empty() && has_hh_) { + if (found.empty() && has_hh_ && !skip_hh && !cancel->isAborted()) { auto context = new_context(); found = route_hh(front_end, context, sx, sy, ex, ey, request.alternatives && kAlternativeRoutes); @@ -802,8 +837,9 @@ class NavigationWorker::Impl { if (found.empty() && !cancel->isAborted()) { // A* (no HH data, or HH found nothing usable). method = "astar"; - trace(has_hh_ ? "worker=route_fallback why=hh_unusable" - : "worker=route_fallback why=no_hh_data"); + trace(skip_hh ? "worker=route_fallback why=too_short" + : has_hh_ ? "worker=route_fallback why=hh_unusable" + : "worker=route_fallback why=no_hh_data"); auto context = new_context(); std::vector intermediates_x; std::vector intermediates_y; @@ -1018,6 +1054,10 @@ class NavigationWorker::Impl { std::mutex mutex_; std::condition_variable condition_; std::thread thread_; + std::thread warmup_; // opens the routing maps once + std::mutex router_mutex_; // prepare_router: warm-up or first route + std::atomic stop_warmup_{false}; + bool router_failed_ = false; // under router_mutex_ Request pending_; SearchResult result_; RouteResult route_result_; diff --git a/backends/osmand/osmand_engine.cpp b/backends/osmand/osmand_engine.cpp index 44ed4e1..07e351b 100644 --- a/backends/osmand/osmand_engine.cpp +++ b/backends/osmand/osmand_engine.cpp @@ -158,6 +158,7 @@ class OsmAndEngine final : public Engine { std::uint64_t submitted_route_revision_ = 0; std::chrono::steady_clock::time_point search_revision_observed_at_{}; bool search_revision_observed_ = false; + std::chrono::steady_clock::time_point ready_at_{}; // rendering came up GuidanceTracker guidance_tracker_; // Spoken guidance: the planner decides what to say, the client hands it to navi_voiced. PromptPlanner prompt_planner_; @@ -526,6 +527,7 @@ bool OsmAndEngine::initialize(const Config& config, // Rendering now has a valid teardown contract. Mark it before allocations // below so an LVGL construction exception can still release OsmAnd. phase_ = Phase::Ready; + ready_at_ = std::chrono::steady_clock::now(); trace("init=rendering"); if (!init_vector_map(wakeup)) return false; @@ -1546,8 +1548,17 @@ bool OsmAndEngine::sync_navigation_to_screen() return changed; } +// The worker opens the routing maps in the background (about 10 s for all of +// Ukraine), so it starts before the first route is asked for: when a place +// card or another screen opens, or a while after start-up, out of its way. +constexpr std::chrono::seconds kWorkerWarmupDelay{30}; + void OsmAndEngine::submit_navigation_requests() { + if (!navigation_worker_ && !worker_creation_failed_ && + (navigation_->screen() != ui::Screen::FreeDrive || navigation_->place_card() || + std::chrono::steady_clock::now() - ready_at_ >= kWorkerWarmupDelay)) + (void)ensure_navigation_worker(); if (navigation_->screen() == ui::Screen::Search) { const auto revision = navigation_->search_revision(); const auto now = std::chrono::steady_clock::now(); @@ -1555,7 +1566,7 @@ void OsmAndEngine::submit_navigation_requests() observed_search_revision_ = revision; search_revision_observed_at_ = now; search_revision_observed_ = true; - } else if (revision != submitted_search_revision_ && + } else if (revision != submitted_search_revision_ && navigation_->search_wanted() && now - search_revision_observed_at_ >= search_debounce()) { submitted_search_revision_ = revision; if (!navigation_->query().empty()) { diff --git a/backends/osmand/ui/navigation_model.h b/backends/osmand/ui/navigation_model.h index 4fcab8e..3a31b1e 100644 --- a/backends/osmand/ui/navigation_model.h +++ b/backends/osmand/ui/navigation_model.h @@ -295,6 +295,13 @@ class NavigationModel { { return has_destination_ && routes_.empty() && message_ == calculating_message; } + // The query still needs a search. Not once a destination is picked from + // it: a recent sets the query to its title, and a late search for that + // would cancel the destination's route on the one worker. + bool search_wanted() const noexcept + { + return screen_ == Screen::Search && !query_.empty() && !has_destination_; + } // Route preview Back: returns to where the route was picked (the search // results, or free drive with the place card). bool back_to_search() noexcept; diff --git a/tests/ch_test.cpp b/tests/ch_test.cpp index 037f653..bcdce9a 100644 --- a/tests/ch_test.cpp +++ b/tests/ch_test.cpp @@ -106,6 +106,42 @@ int main() for (u32 e : edges) { assert(g.from[e] == at); at = g.to[e]; sum += g.cost[e]; } assert(at == t && sum == cost); } + + // Seeded with several starts and ends (with their own costs), one search finds + // the best of every pair, and the path runs from the seeds it names. + for (int i = 0; i < 200; ++i) { + std::vector from, to; + for (int k = 0; k < 4; ++k) { + from.push_back({(u32)(rng() % g.n), (u32)(rng() % 3000)}); + to.push_back({(u32)(rng() % g.n), (u32)(rng() % 3000)}); + } + u32 brute = INF; + for (const auto& s : from) + for (const auto& t : to) { + const u32 d = dijkstra(g, s.node, t.node); + if (d != INF) brute = std::min(brute, d + s.cost + t.cost); + } + u32 meet = 0; + const u32 cost = query.run(from.data(), from.size(), to.data(), to.size(), meet); + assert(cost == brute); + if (cost == INF) continue; + const u32 s = query.source_of(meet), t = query.target_of(meet); + assert(query.path_edges(s, t, meet, edges)); + u32 at = s, sum = 0; + for (u32 e : edges) { assert(g.from[e] == at); at = g.to[e]; sum += g.cost[e]; } + u32 offsets = INF; + for (const auto& a : from) + for (const auto& b : to) + if (a.node == s && b.node == t) offsets = std::min(offsets, a.cost + b.cost); + assert(at == t && sum + offsets == cost); + } + + // A cancelled search stops with no route. + { + const Query::Seed s {0, 0}, t {g.n - 1, 0}; + u32 meet = 0; + assert(query.run(&s, 1, &t, 1, meet, [] { return true; }) == INF || query.settled < 1024); + } } // The sidecar round trip: counts, hierarchy, snap lookup against brute force, routing. diff --git a/tests/navigation_ui_test.cpp b/tests/navigation_ui_test.cpp index 2a4bb0c..6927bdc 100644 --- a/tests/navigation_ui_test.cpp +++ b/tests/navigation_ui_test.cpp @@ -357,6 +357,10 @@ void test_car_controls() // first row at y 336..400 on the left. tap(view, 200, 336 + 32); assert(model.destination() && model.destination()->id == "home"); + // The pick set the query to its title: no search may follow and + // cancel the route being calculated. + assert(model.query() == "Home" && model.calculating_route()); + assert(!model.search_wanted()); assert(view.set_moving(false)); } }