maps: keep the traffic prefetch off the main thread and its lock short (#maprender)
- Commit
4f866653b7227c2fc5747b2eccf22de1cd81fb80- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 20:29 UTC (22 days ago)
- Parents
5ae3f77
Part of "Maps isn't responding" (with the traffic layer on): a main thread JNI call that waits on a lock a background thread holds. Root cause: `TrafficPrefetchEffect` runs in a LaunchedEffect, i.e. on the main thread. On every camera settle (400 ms debounce, z11+) it called `prefetchTrafficSquares`, which makes up to 16 `OfflineRouter.ensureTrafficLoadedNative` JNI calls. Each takes the router's `traffic_meta` mutex first. `updateTrafficNative`, run on an IO thread when a square's fetch lands, held that same mutex (and the traffic-speed write lock) for its whole per-square walk: for every edge a binary search over the planet's node array to recover the source node, plus three record reads from the memory-mapped, zstd-blocked graph. On a phone those reads are cold flash pages and block inflates in an 81 GB file, so a settle that coincided with a landing fetch parked the main thread for the length of the walk. What changed: - Kotlin: the camera bounds are still read on the main thread (camera state), and the prefetch JNI calls run in `withContext(Dispatchers.IO)`. - Rust: `updateTrafficNative` builds the square's segments and speed updates with no lock held, then takes the speed write lock for one `extend` and `traffic_meta` for one `insert` (replacing the old clear-then-push under lock; same contents, readers see the old square until the new one is complete, exactly as before). Measured (new ignored harness tests/traffic_update_bench.rs, real world.mamaps, 60k edges per 1-degree square, host with the archive in page cache): the walk is 11.6-19.1 ms on the first pass and 7.2-7.7 ms warm (0.12-0.13 us/edge). That was the `traffic_meta` hold time per landing square; it is now a single map insert (microseconds). On a device the same walk runs over cold flash and zstd blocks, so the old hold was a multiple of the host figure; either way the main thread no longer takes the lock at all. Verified: offlinerouter lib tests (93) pass; android target type-checks; harness above.
Diff
maps/src/main/java/com/vayunmathur/maps/ui/map/TrafficPrefetchEffect.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/TrafficPrefetchEffect.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/TrafficPrefetchEffect.ktindex 2fa505191d..4d2a1717c8 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/TrafficPrefetchEffect.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/TrafficPrefetchEffect.kt@@ -5,8 +5,10 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.snapshotFlow import com.vayunmathur.library.map.CameraState import com.vayunmathur.maps.util.visibleBoundsOrWorld+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.withContext /** * Prefetch traffic for the visible 1° squares once the camera settles, so the@@ -30,7 +32,11 @@ fun TrafficPrefetchEffect(camera: CameraState, trafficEnabled: Boolean) { // world-zoom viewport would enumerate hundreds of 1° squares, so only prefetch // once zoomed in enough for it to be useful. if (camera.position.zoom < TRAFFIC_MIN_ZOOM) return@collectLatest- prefetchTrafficSquares(camera.visibleBoundsOrWorld())+ // The bounds are camera state (read here, on main); the prefetch itself is up to+ // sixteen JNI calls into the router, each taking the native traffic lock a+ // finished fetch's update holds while it walks its square, so it runs on IO.+ val bounds = camera.visibleBoundsOrWorld()+ withContext(Dispatchers.IO) { prefetchTrafficSquares(bounds) } } } }
maps/src/main/rust/src/jni/traffic_jni.rs
diff --git a/maps/src/main/rust/src/jni/traffic_jni.rs b/maps/src/main/rust/src/jni/traffic_jni.rsindex cb0d674454..33225b4eeb 100644--- a/maps/src/main/rust/src/jni/traffic_jni.rs+++ b/maps/src/main/rust/src/jni/traffic_jni.rs@@ -62,38 +62,44 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_updateTraffi return Ok(()); } - let mut speeds_w = super::routes::traffic_speeds().write().unwrap();- let mut meta = traffic_meta().lock().unwrap();- let segments = meta.by_square.entry(packed_square).or_default();- segments.clear();-+ // The walk runs with no lock held. It recovers each edge's source node (a binary+ // search over the planet's node array) and reads three records out of the mapped+ // graph, which on a phone means cold flash pages and zstd blocks — while+ // `traffic_meta` is the lock the camera-settle prefetch (`ensureTrafficLoadedNative`)+ // takes first. Holding it across the walk let the caller wait out the whole square.+ // Now both locks are held only for the swap-in below.+ let mut updates: Vec<(u64, u8)> = Vec::with_capacity(len);+ let mut fresh: Vec<f64> = Vec::with_capacity(len * 5); for i in 0..len { let edge_id = ids[i] as u64; let speed = sp[i] as u8;- if edge_id < g.edge_count {- if speed < 255 {- speeds_w.insert(edge_id, speed);- // The only entry point with no source node in hand: the id comes- // from Kotlin. Recovered first, because reading the record needs it.- let source = g.find_node_idx_for_edge(edge_id);- let edge = g.edge(source, edge_id);- let node_u = g.node(source);- if edge.target < g.node_count {- let node_v = g.node(edge.target);- let ratio = if edge.speed_limit > 0 {- speed as f64 / edge.speed_limit as f64- } else {- 1.0- };- segments.push(node_u.lat_e7 as f64 * 1e-7);- segments.push(node_u.lon_e7 as f64 * 1e-7);- segments.push(node_v.lat_e7 as f64 * 1e-7);- segments.push(node_v.lon_e7 as f64 * 1e-7);- segments.push(ratio);- }+ if edge_id < g.edge_count && speed < 255 {+ updates.push((edge_id, speed));+ // The only entry point with no source node in hand: the id comes+ // from Kotlin. Recovered first, because reading the record needs it.+ let source = g.find_node_idx_for_edge(edge_id);+ let edge = g.edge(source, edge_id);+ let node_u = g.node(source);+ if edge.target < g.node_count {+ let node_v = g.node(edge.target);+ let ratio = if edge.speed_limit > 0 {+ speed as f64 / edge.speed_limit as f64+ } else {+ 1.0+ };+ fresh.push(node_u.lat_e7 as f64 * 1e-7);+ fresh.push(node_u.lon_e7 as f64 * 1e-7);+ fresh.push(node_v.lat_e7 as f64 * 1e-7);+ fresh.push(node_v.lon_e7 as f64 * 1e-7);+ fresh.push(ratio); } } }+ {+ let mut speeds_w = super::routes::traffic_speeds().write().unwrap();+ speeds_w.extend(updates);+ }+ traffic_meta().lock().unwrap().by_square.insert(packed_square, fresh); Ok(()) }) .resolve::<jni::errors::LogErrorAndDefault>()
maps/src/main/rust/tests/traffic_update_bench.rs
diff --git a/maps/src/main/rust/tests/traffic_update_bench.rs b/maps/src/main/rust/tests/traffic_update_bench.rsnew file mode 100644index 0000000000..ec6475aa98--- /dev/null+++ b/maps/src/main/rust/tests/traffic_update_bench.rs@@ -0,0 +1,108 @@+//! Host timing for `updateTrafficNative`'s per-square walk, against a REAL planet archive.+//!+//! Ignored by default and gated on `MAMAPS_REAL_ARCHIVE` like `real_archive.rs`:+//!+//! ```text+//! MAMAPS_REAL_ARCHIVE=/path/to/world.mamaps \+//! cargo test -p offlinerouter --release --test traffic_update_bench -- --ignored --nocapture+//! ```+//!+//! `updateTrafficNative` runs on an IO thread after each 1° traffic square lands, and for every+//! edge in it recovers the source node (a binary search over the planet's node array), reads the+//! edge and both endpoints. Until this change it did all of that while holding `traffic_meta`,+//! the same lock the main thread's camera-settle prefetch (`ensureTrafficLoadedNative`) takes+//! first, so the main thread could sit behind the whole walk. This harness times that walk.++use offlinerouter::graph::{Graph, DRIVING};+use offlinerouter::routing::find_nearest_edge;+use std::collections::{HashSet, VecDeque};+use std::time::Instant;++fn archive() -> Option<String> {+ match std::env::var("MAMAPS_REAL_ARCHIVE") {+ Ok(p) if std::path::Path::new(&p).is_file() => Some(p),+ _ => {+ eprintln!("MAMAPS_REAL_ARCHIVE not set: skipped");+ None+ }+ }+}++/// Up to `cap` edge ids whose source node lies in the 1° square at (`lat0`, `lon0`), found by a+/// breadth-first walk from the node nearest the square's centre — a stand-in for the edge ids a+/// traffic fetch for that square carries.+fn square_edges(g: &Graph, lat0: f64, lon0: f64, cap: usize) -> Vec<u64> {+ let start = find_nearest_edge(g, lat0 + 0.5, lon0 + 0.5, DRIVING).node_a;+ let inside = |n: u32| {+ let m = g.node(n);+ let (lat, lon) = (m.lat_e7 as f64 * 1e-7, m.lon_e7 as f64 * 1e-7);+ lat >= lat0 && lat < lat0 + 1.0 && lon >= lon0 && lon < lon0 + 1.0+ };+ let mut seen = HashSet::new();+ let mut queue = VecDeque::from([start]);+ let mut edges = Vec::new();+ while let Some(n) = queue.pop_front() {+ if !seen.insert(n) || !inside(n) {+ continue;+ }+ let (s, e) = g.edge_range(n);+ for idx in s..e {+ edges.push(idx);+ let t = g.edge(n, idx).target;+ if t < g.node_count {+ queue.push_back(t);+ }+ }+ if edges.len() >= cap {+ break;+ }+ }+ edges+}++/// The per-edge work `updateTrafficNative` does, minus the JNI copy.+fn walk(g: &Graph, edges: &[u64]) -> Vec<f64> {+ let mut segments = Vec::with_capacity(edges.len() * 5);+ for &edge_id in edges {+ if edge_id >= g.edge_count {+ continue;+ }+ let source = g.find_node_idx_for_edge(edge_id);+ let edge = g.edge(source, edge_id);+ let node_u = g.node(source);+ if edge.target < g.node_count {+ let node_v = g.node(edge.target);+ segments.extend_from_slice(&[+ node_u.lat_e7 as f64 * 1e-7,+ node_u.lon_e7 as f64 * 1e-7,+ node_v.lat_e7 as f64 * 1e-7,+ node_v.lon_e7 as f64 * 1e-7,+ 1.0,+ ]);+ }+ }+ segments+}++#[test]+#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"]+fn the_traffic_square_walk() {+ let Some(path) = archive() else { return };+ let g = Graph::load_archive(&path).expect("graph");+ for (name, lat0, lon0) in [("SF", 37.0, -123.0), ("LA", 34.0, -119.0), ("London", 51.0, -1.0)] {+ let edges = square_edges(&g, lat0, lon0, 60_000);+ let t = Instant::now();+ let first = walk(&g, &edges);+ let first_ms = t.elapsed().as_secs_f64() * 1e3;+ let t = Instant::now();+ let again = walk(&g, &edges);+ let again_ms = t.elapsed().as_secs_f64() * 1e3;+ assert_eq!(first.len(), again.len());+ println!(+ "{name}: {} edges, walk {first_ms:.1} ms first pass, {again_ms:.1} ms warm \+ ({:.2} us/edge warm)",+ edges.len(),+ again_ms * 1e3 / edges.len().max(1) as f64+ );+ }+}