Modern Apps git

← Modern-Apps.git

map: single-flight online range fetches across tile workers

Commit
db16c076a95e9cb130f98f28176b4df5cdafe150
Author
Vayun Mathur <[email protected]>
When
2026-12-02 03:11 UTC (4 days ago)
Parents
f44a54a
Online map rendering was slow while the offline (local .mamaps) path was
fine. The offline reader serves ranges as mmap slices with the OS page
cache deduplicating shared leaves and bodies; the online reader had no
equivalent for in-flight ranges. A cold viewport's eight tile workers
share one leaf (4096 tiles per leaf) and often one superblock body, and
each worker fetched its own copy before the first copy reached the disk
cache. Measured with a counting fake fetcher: 8 concurrent readers over
one cache dir issued 16 fetcher requests for 2 ranges. The Kotlin batch
transport was exonerated by measurement (12 ranges at 150 ms server
delay complete as one overlapped wave, and the next wave reuses pooled
connections), and queued stale tiles were already drained on pan with
in-flight results dropped at upload, so the remaining online-only waste
was duplicate in-flight fetches, the shared temp-file names their disk
cache writes raced on, and two fsyncs per written range before a worker
could tessellate.

Fix, online path only (the local-file reader is untouched):

- tile/source: a RangeFlights registry shared by every worker of a
  surface (wired in bridge/lifecycle, passed in bridge/workers). The
  first reader to miss a range leads its fetch; followers take the
  leader's published result, error included, instead of issuing a
  duplicate request. Claims drop on publish, so a later read after a
  failure retries. Ranges repeated within one batch are likewise
  fetched once.
- tile/cache: cache writes use per-writer unique temp names (pid +
  sequence), so concurrent writers of one range no longer truncate and
  rename each other's temp files and silently lose entries.
- flush_pending now orders a wave's renames with one directory sync
  instead of syncing both files of every entry (2 fsyncs per range on
  the worker thread before tessellation).

Tests pin the behaviour with fakes counting requests/connections:
Rust tests_flights (8 concurrent readers -> 2 fetches; a failed flight
fetches once for all followers; a range repeated in one batch fetches
once) and a library/network batch test asserting a 12-range wave
overlaps (max concurrency and elapsed bound) and that the next wave
reuses at least half its pooled connections (server-side remote ports).

Verified: cargo test -p map_renderer --lib 577 passed; :library:map:lint
(0 errors) and :library:map:testDebugUnitTest (98 tests) green;
:library:network:lint (0 errors) and :library:network:testDebugUnitTest
(109 tests) green; :findfamily:testDevUnitTest (354 tests) green.
:findfamily:lint and :findfamily:lintVitalRelease remain red at this
base with 13 pre-existing errors (3 DialogAsRoute, 10
RouteScreenshotCoverage) in findfamily files this change does not
touch; the parent should re-check them against the separate findfamily
lint backlog before merging.

Diff

library/map/src/main/rust/src/bridge/lifecycle.rs
diff --git a/library/map/src/main/rust/src/bridge/lifecycle.rs b/library/map/src/main/rust/src/bridge/lifecycle.rsindex fb003ce72c..5b0eb68f16 100644--- a/library/map/src/main/rust/src/bridge/lifecycle.rs+++ b/library/map/src/main/rust/src/bridge/lifecycle.rs@@ -119,6 +119,10 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>(     // worker). See `spawn_worker`.     let header = Arc::new(std::sync::OnceLock::new());     let prefix_gate = Arc::new(std::sync::atomic::AtomicBool::new(false));+    // One in-flight range registry shared by every worker: a cold leaf or+    // superblock body one worker is already fetching is not fetched again by+    // the others (see `tile::source::RangeFlights`).+    let flights = Arc::new(crate::tile::source::RangeFlights::new());     // One parsed-leaf cache shared by every worker's archive view (issue 815): a cold leaf is     // fetched once per surface, not once per worker.     let leaves = Arc::new(tilecodec::mamaps::read::LeafCache::new());@@ -135,6 +139,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>(             toggles.clone(),             header.clone(),             prefix_gate.clone(),+            flights.clone(),             leaves.clone(),         );     }
library/map/src/main/rust/src/bridge/workers.rs
diff --git a/library/map/src/main/rust/src/bridge/workers.rs b/library/map/src/main/rust/src/bridge/workers.rsindex 7f707a4c27..4fff22cb8b 100644--- a/library/map/src/main/rust/src/bridge/workers.rs+++ b/library/map/src/main/rust/src/bridge/workers.rs@@ -9,7 +9,7 @@ use crate::tile::geometry; use crate::tile::select::TileId; use crate::tile::source::BASEMAP_ARCHIVE_URL; use crate::tile::source::{-    basemap_origin, discover, CachingRangeReader, FileRangeReader, JniRangeFetcher,+    basemap_origin, discover, CachingRangeReader, FileRangeReader, JniRangeFetcher, RangeFlights, }; use std::sync::mpsc::{Receiver, Sender}; use std::sync::{Arc, Mutex};@@ -49,6 +49,7 @@ pub(crate) fn spawn_worker(     toggles: Arc<SharedToggles>,     header: Arc<std::sync::OnceLock<Option<u64>>>,     prefix_gate: Arc<std::sync::atomic::AtomicBool>,+    flights: Arc<RangeFlights>,     leaves: Arc<LeafCache>, ) {     let started = std::thread::Builder::new()@@ -113,6 +114,7 @@ pub(crate) fn spawn_worker(                 cache,                 JniRangeFetcher,                 prefix_gate,+                flights,             );             reader.set_online(online.get()); 
library/map/src/main/rust/src/tile/cache/mod.rs
diff --git a/library/map/src/main/rust/src/tile/cache/mod.rs b/library/map/src/main/rust/src/tile/cache/mod.rsindex e2e8093e1f..4e156d4b31 100644--- a/library/map/src/main/rust/src/tile/cache/mod.rs+++ b/library/map/src/main/rust/src/tile/cache/mod.rs@@ -72,6 +72,13 @@ pub struct RangeCache {     /// not awaited — and because a poisoned lock degrades to skipping one frame's flush     /// (re-fetched on demand), never to losing a tile.     pending_flush: std::sync::Mutex<Vec<String>>,+    /// Sequence for unique temp-file names in [`write_inner`](Self::write_inner).+    ///+    /// Every worker of a surface opens its own `RangeCache` over one directory,+    /// so a fixed `{key}.tmp` name meant concurrent writers of the same range+    /// truncated and renamed each other's temp files (the loser’s rename failed+    /// and its entry silently never cached).+    tmp_seq: std::sync::atomic::AtomicU64, }  /// How many unflushed keys accumulate before the oldest are dropped from the flush list.@@ -111,6 +118,7 @@ impl RangeCache {             clock,             writes_since_evict: std::sync::atomic::AtomicU64::new(0),             pending_flush: std::sync::Mutex::new(Vec::new()),+            tmp_seq: std::sync::atomic::AtomicU64::new(0),         };         cache.invalidate_on_origin_change(origin);         cache@@ -194,6 +202,20 @@ impl RangeCache {         }     } +    /// Order every rename in the directory with one sync, instead of two fsyncs+    /// per entry ([`flush_entry`] on both files of each pair).+    ///+    /// This is the wave-level flush the fetch path uses: a cold screenful writes+    /// dozens of ranges, and per-entry fsyncs on flash storage cost milliseconds+    /// each on the worker thread before it can tessellate. Best-effort like the+    /// rest of the cache — a missed flush only risks a re-fetch, and every read+    /// validates its recorded length, so a torn entry is dropped, never served.+    pub fn flush_dir(&self) {+        if let Ok(dir) = fs::File::open(&self.dir) {+            let _ = dir.sync_all();+        }+    }+     /// The keys written since the last [`drain`](Self::drain) that still need a     /// [`flush_entry`](Self::flush_entry). Returned and cleared by `drain`, so the render     /// thread's once-per-frame drain is what batches durability: writes stream in without@@ -211,7 +233,9 @@ impl RangeCache {         // writes dozens of ranges and an fsync per range is the frame-time tail. The rename         // is still atomic — a crash loses the entry (re-fetched on demand), never serves a         // torn one (every read validates its recorded length).-        let meta_tmp = self.dir.join(format!("{key}.meta.tmp"));+        let seq = self.tmp_seq.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+        let tmp_suffix = format!("tmp-{}-{seq}", std::process::id());+        let meta_tmp = self.dir.join(format!("{key}.meta.{tmp_suffix}"));         {             let mut file = fs::File::create(&meta_tmp)?;             writeln!(file, "fetchedAt={now}")?;@@ -219,7 +243,7 @@ impl RangeCache {         }         fs::rename(&meta_tmp, self.dir.join(format!("{key}.meta")))?; -        let data_tmp = self.dir.join(format!("{key}.data.tmp"));+        let data_tmp = self.dir.join(format!("{key}.data.{tmp_suffix}"));         {             let mut file = fs::File::create(&data_tmp)?;             file.write_all(body)?;
library/map/src/main/rust/src/tile/source/caching.rs
diff --git a/library/map/src/main/rust/src/tile/source/caching.rs b/library/map/src/main/rust/src/tile/source/caching.rsindex 283301fb84..0f919cc62c 100644--- a/library/map/src/main/rust/src/tile/source/caching.rs+++ b/library/map/src/main/rust/src/tile/source/caching.rs@@ -20,6 +20,86 @@ pub struct CachingRangeReader<F: RangeFetcher> {     /// worker: each reader used to carry its own flag, and four workers meant four forced     /// network reads of the same prefix before any tile was fetched.     prefix_checked: std::sync::Arc<std::sync::atomic::AtomicBool>,+    /// Ranges currently being fetched by any reader sharing this registry.+    ///+    /// Without it, a cold viewport's workers raced the same ranges: every worker's+    /// first tiles share one leaf (4096 tiles per leaf) and often one superblock+    /// body, and each of the eight workers fetched its own copy before the first+    /// copy reached the disk cache — measured at 16 fetcher requests for 2 ranges+    /// from 8 concurrent readers. Shared across a surface's workers (see+    /// [`new_shared`](Self::new_shared)), so a range in flight is fetched once and+    /// its followers take the leader's bytes (or its error) instead of issuing a+    /// duplicate request.+    flights: std::sync::Arc<RangeFlights>,+}++/// The shared in-flight registry behind [`CachingRangeReader`]'s single-flight+/// policy: one leader fetches a range, followers wait for its result.+///+/// The leader publishes its final policy result (post status/length checks), so+/// followers observe exactly what the leader's caller did, including errors.+/// Publication removes the claim first, so a later read after a failure retries+/// rather than joining a finished flight.+pub struct RangeFlights {+    flights: std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<Flight>>>,+}++struct Flight {+    state: std::sync::Mutex<Option<std::result::Result<Vec<u8>, String>>>,+    done: std::sync::Condvar,+}++enum Claim {+    Leader(std::sync::Arc<Flight>),+    Follower(std::sync::Arc<Flight>),+}++impl RangeFlights {+    pub fn new() -> RangeFlights {+        RangeFlights { flights: std::sync::Mutex::new(std::collections::HashMap::new()) }+    }++    fn claim(&self, key: &str) -> Claim {+        let mut flights = self.flights.lock().unwrap_or_else(|e| e.into_inner());+        if let Some(flight) = flights.get(key) {+            return Claim::Follower(std::sync::Arc::clone(flight));+        }+        let flight = std::sync::Arc::new(Flight {+            state: std::sync::Mutex::new(None),+            done: std::sync::Condvar::new(),+        });+        flights.insert(key.to_string(), std::sync::Arc::clone(&flight));+        Claim::Leader(flight)+    }++    fn publish(+        &self,+        key: &str,+        flight: &std::sync::Arc<Flight>,+        result: std::result::Result<Vec<u8>, String>,+    ) {+        {+            let mut flights = self.flights.lock().unwrap_or_else(|e| e.into_inner());+            if flights.get(key).is_some_and(|f| std::sync::Arc::ptr_eq(f, flight)) {+                flights.remove(key);+            }+        }+        let mut state = flight.state.lock().unwrap_or_else(|e| e.into_inner());+        *state = Some(result);+        flight.done.notify_all();+    }+}++impl Flight {+    fn wait(&self) -> std::result::Result<Vec<u8>, String> {+        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());+        loop {+            if let Some(result) = &*state {+                return result.clone();+            }+            state = self.done.wait(state).unwrap_or_else(|e| e.into_inner());+        }+    } }  impl<F: RangeFetcher> CachingRangeReader<F> {@@ -30,17 +110,21 @@ impl<F: RangeFetcher> CachingRangeReader<F> {             fetcher,             online: std::sync::atomic::AtomicBool::new(true),             prefix_checked: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),+            flights: std::sync::Arc::new(RangeFlights::new()),         }     } -    /// [`new`](Self::new) with a session-wide revalidation gate shared by every worker of one-    /// surface. The first read across *all* readers sharing the gate goes to the network; the-    /// rest serve from cache per the usual freshness policy.+    /// [`new`](Self::new) with the session-wide state shared by every worker of one+    /// surface: the revalidation gate (the first read across *all* readers sharing+    /// it goes to the network; the rest serve from cache per the usual freshness+    /// policy) and the in-flight registry (a range one worker is already fetching+    /// is not fetched again by another).     pub fn new_shared(         url: impl Into<String>,         cache: RangeCache,         fetcher: F,         prefix_checked: std::sync::Arc<std::sync::atomic::AtomicBool>,+        flights: std::sync::Arc<RangeFlights>,     ) -> Self {         CachingRangeReader {             url: url.into(),@@ -48,6 +132,7 @@ impl<F: RangeFetcher> CachingRangeReader<F> {             fetcher,             online: std::sync::atomic::AtomicBool::new(true),             prefix_checked,+            flights,         }     } @@ -94,7 +179,26 @@ impl<F: RangeFetcher> CachingRangeReader<F> {             }         } -        let response = self.fetcher.fetch(&self.url, &range)?;+        // Single-flight: another reader may already be fetching this exact range+        // (the shared leaf or superblock of a cold viewport). Followers take the+        // leader's result; only the leader pays the request.+        match self.flights.claim(&key) {+            Claim::Follower(flight) => flight.wait().map_err(tilecodec::proto::Error),+            Claim::Leader(flight) => {+                let result = self.fetch_and_cache(&range, &key, length);+                self.flights.publish(+                    &key,+                    &flight,+                    result.as_ref().map(|b| b.clone()).map_err(|e| e.0.clone()),+                );+                result+            }+        }+    }++    /// Fetch one range, apply the status/length policy and cache a trusted body.+    fn fetch_and_cache(&self, range: &str, key: &str, length: u32) -> Result<Vec<u8>> {+        let response = self.fetcher.fetch(&self.url, range)?;          if !(200..300).contains(&response.status) {             return err(format!(@@ -104,7 +208,7 @@ impl<F: RangeFetcher> CachingRangeReader<F> {         }         // Only a body we trust: a 206 partial whose length matches the request.         if response.status == 206 && response.body.len() == length as usize {-            self.cache.write(&key, &response.body);+            self.cache.write(key, &response.body);         }         Ok(response.body)     }@@ -136,8 +240,11 @@ impl<F: RangeFetcher> RangeReader for CachingRangeReader<F> {     /// call and durability-flushes them together, instead of the fsync per range the old     /// write path paid. Best-effort — a missed flush only risks a re-fetch.     fn flush_pending(&self) {-        for key in self.cache.drain() {-            self.cache.flush_entry(&key);+        // One directory sync orders the whole wave's renames, instead of the two+        // fsyncs per entry (one per file of each `.meta`/`.data` pair) the old+        // per-entry flush paid on the worker before it could tessellate.+        if !self.cache.drain().is_empty() {+            self.cache.flush_dir();         }     } @@ -190,38 +297,91 @@ impl<F: RangeFetcher> RangeReader for CachingRangeReader<F> {                 }             }         }-        // Wave: every miss in one `fetch_batch` — one JNI crossing, one dispatcher wave.+        // Wave: every distinct miss in one `fetch_batch` — one JNI crossing, one+        // dispatcher wave. A range repeated in this batch, or already in flight+        // under another reader sharing the registry, is fetched once: this+        // reader either leads its fetch or follows the leader's result.         if !miss_slots.is_empty() {-            let fetched = self.fetcher.fetch_batch(&self.url, &miss_ranges);-            debug_assert_eq!(fetched.len(), miss_slots.len());-            for (i, slot) in miss_slots.iter().enumerate() {-                let range = &miss_ranges[i];-                let key = &miss_keys[i];-                let length = miss_lengths[i];-                match fetched.get(i) {-                    Some(Ok(response)) => {-                        if !(200..300).contains(&response.status) {-                            out[*slot] = Some(err(format!(-                                "range request for {range} of {} failed with HTTP {}",-                                self.url, response.status-                            )));-                            continue;-                        }-                        // Only a body we trust: a 206 partial whose length matches the request.-                        if response.status == 206 && response.body.len() == length as usize {-                            self.cache.write(key, &response.body);-                        }-                        out[*slot] = Some(Ok(response.body.clone()));-                    }-                    Some(Err(e)) => out[*slot] = Some(Err(tilecodec::proto::Error(e.0.clone()))),+            let mut distinct_of: Vec<usize> = Vec::with_capacity(miss_slots.len());+            let mut distinct_keys: Vec<String> = Vec::new();+            for key in &miss_keys {+                match distinct_keys.iter().position(|k| k == key) {+                    Some(pos) => distinct_of.push(pos),                     None => {-                        out[*slot] = Some(err(format!(+                        distinct_of.push(distinct_keys.len());+                        distinct_keys.push(key.clone());+                    }+                }+            }+            let mut distinct_results: Vec<Option<Result<Vec<u8>>>> =+                distinct_keys.iter().map(|_| None).collect();+            let mut leader_positions: Vec<usize> = Vec::new();+            let mut leader_flights: Vec<std::sync::Arc<Flight>> = Vec::new();+            let mut follower_flights: Vec<(usize, std::sync::Arc<Flight>)> = Vec::new();+            for (pos, key) in distinct_keys.iter().enumerate() {+                match self.flights.claim(key) {+                    Claim::Leader(flight) => {+                        leader_positions.push(pos);+                        leader_flights.push(flight);+                    }+                    Claim::Follower(flight) => follower_flights.push((pos, flight)),+                }+            }+            if !leader_positions.is_empty() {+                let leader_ranges: Vec<String> = leader_positions+                    .iter()+                    .map(|&pos| {+                        miss_ranges[distinct_of.iter().position(|&p| p == pos).unwrap()].clone()+                    })+                    .collect();+                let fetched = self.fetcher.fetch_batch(&self.url, &leader_ranges);+                for (i, &pos) in leader_positions.iter().enumerate() {+                    let key = &distinct_keys[pos];+                    let miss = distinct_of.iter().position(|&p| p == pos).unwrap();+                    let range = &miss_ranges[miss];+                    let length = miss_lengths[miss];+                    let result = match fetched.get(i) {+                        Some(Ok(response)) => {+                            if !(200..300).contains(&response.status) {+                                err(format!(+                                    "range request for {range} of {} failed with HTTP {}",+                                    self.url, response.status+                                ))+                            } else {+                                // Only a body we trust: a 206 partial whose length matches.+                                if response.status == 206 && response.body.len() == length as usize+                                {+                                    self.cache.write(key, &response.body);+                                }+                                Ok(response.body.clone())+                            }+                        }+                        Some(Err(e)) => Err(tilecodec::proto::Error(e.0.clone())),+                        None => err(format!(                             "range request for {range} of {} left its slot unresolved",                             self.url-                        )));-                    }+                        )),+                    };+                    self.flights.publish(+                        key,+                        &leader_flights[i],+                        result.as_ref().map(|b| b.clone()).map_err(|e| e.0.clone()),+                    );+                    distinct_results[pos] = Some(result);                 }             }+            // Leaders all published above (and other readers' leaders publish on+            // their own threads), so following here cannot deadlock.+            for (pos, flight) in follower_flights {+                distinct_results[pos] = Some(flight.wait().map_err(tilecodec::proto::Error));+            }+            for (i, slot) in miss_slots.iter().enumerate() {+                out[*slot] = Some(match &distinct_results[distinct_of[i]] {+                    Some(Ok(body)) => Ok(body.clone()),+                    Some(Err(e)) => Err(tilecodec::proto::Error(e.0.clone())),+                    None => err("a range batch left a slot unresolved"),+                });+            }         }         out.into_iter()             .map(|slot| slot.unwrap_or_else(|| err("a range batch left a slot unresolved")))
library/map/src/main/rust/src/tile/source/mod.rs
diff --git a/library/map/src/main/rust/src/tile/source/mod.rs b/library/map/src/main/rust/src/tile/source/mod.rsindex 758348d20a..2cbf1aeed5 100644--- a/library/map/src/main/rust/src/tile/source/mod.rs+++ b/library/map/src/main/rust/src/tile/source/mod.rs@@ -27,9 +27,11 @@ mod urls;  #[cfg(test)] mod tests;+#[cfg(test)]+mod tests_flights;  pub use caching::read_batch;-pub use caching::CachingRangeReader;+pub use caching::{CachingRangeReader, RangeFlights}; #[cfg(target_os = "android")] pub use fetch::JniRangeFetcher; pub use fetch::{RangeFetcher, RangeResponse};
library/map/src/main/rust/src/tile/source/tests_flights.rs
diff --git a/library/map/src/main/rust/src/tile/source/tests_flights.rs b/library/map/src/main/rust/src/tile/source/tests_flights.rsnew file mode 100644index 0000000000..a6f2090bf0--- /dev/null+++ b/library/map/src/main/rust/src/tile/source/tests_flights.rs@@ -0,0 +1,180 @@+use super::*;+use crate::tile::cache::RangeCache;+use std::path::PathBuf;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Arc;+use tilecodec::proto::{err, Result};+use tilecodec::stream::RangeReader;++const URL: &str = BASEMAP_ARCHIVE_URL;++struct Fixture {+    dir: PathBuf,+}++impl Fixture {+    fn new(name: &str) -> Fixture {+        let dir = std::env::temp_dir().join(format!("rangeflights-{name}-{}", std::process::id()));+        let _ = std::fs::remove_dir_all(&dir);+        std::fs::create_dir_all(&dir).expect("temp dir");+        Fixture { dir }+    }+}++impl Drop for Fixture {+    fn drop(&mut self) {+        let _ = std::fs::remove_dir_all(&self.dir);+    }+}++/// Records every range asked for, and answers 206 with a canned body.+struct Fake {+    ranges: std::sync::Mutex<Vec<String>>,+}++impl RangeFetcher for Fake {+    fn fetch(&self, _url: &str, range: &str) -> Result<RangeResponse> {+        self.ranges.lock().unwrap().push(range.to_string());+        Ok(RangeResponse { status: 206, body: vec![7u8; 64] })+    }+}++fn reader(dir: &std::path::Path, clock: Arc<AtomicU64>, fetcher: Fake) -> CachingRangeReader<Fake> {+    let c = clock.clone();+    let cache = RangeCache::with_clock(+        dir,+        "v1|test",+        crate::tile::cache::DEFAULT_MAX_BYTES,+        Box::new(move || c.load(Ordering::SeqCst)),+    );+    CachingRangeReader::new(URL, cache, fetcher)+}++/// A fetcher with latency, so concurrent readers genuinely overlap in flight.+struct DelayedFake {+    delay_ms: u64,+    fail: std::sync::atomic::AtomicBool,+    calls: std::sync::atomic::AtomicU64,+}++impl RangeFetcher for DelayedFake {+    fn fetch(&self, _url: &str, _range: &str) -> Result<RangeResponse> {+        self.calls.fetch_add(1, Ordering::SeqCst);+        std::thread::sleep(std::time::Duration::from_millis(self.delay_ms));+        if self.fail.load(Ordering::SeqCst) {+            return err("no route to host");+        }+        Ok(RangeResponse { status: 206, body: vec![7u8; 64] })+    }+}++fn shared_reader(+    dir: &std::path::Path,+    clock: Arc<AtomicU64>,+    fetcher: DelayedFake,+    prefix_gate: Arc<std::sync::atomic::AtomicBool>,+    flights: Arc<crate::tile::source::RangeFlights>,+) -> CachingRangeReader<DelayedFake> {+    let c = clock.clone();+    let cache = RangeCache::with_clock(+        dir,+        "v1|test",+        crate::tile::cache::DEFAULT_MAX_BYTES,+        Box::new(move || c.load(Ordering::SeqCst)),+    );+    CachingRangeReader::new_shared(URL, cache, fetcher, prefix_gate, flights)+}++/// A cold range wanted by every worker at once is fetched once, not once per+/// worker: the eight readers of a surface share one leaf and often one body+/// range, and before single-flight each fetched its own copy (measured at 16+/// requests for 2 ranges from 8 readers).+#[test]+fn concurrent_readers_share_one_fetch_per_cold_range() {+    let f = Fixture::new("singleflight");+    let clock = Arc::new(AtomicU64::new(1_000_000));+    let prefix_gate = Arc::new(std::sync::atomic::AtomicBool::new(false));+    let flights = Arc::new(crate::tile::source::RangeFlights::new());+    let barrier = Arc::new(std::sync::Barrier::new(8));+    let total_calls = Arc::new(std::sync::atomic::AtomicU64::new(0));+    let mut handles = Vec::new();+    for _ in 0..8 {+        let dir = f.dir.clone();+        let clock = clock.clone();+        let barrier = barrier.clone();+        let prefix_gate = prefix_gate.clone();+        let flights = flights.clone();+        let total_calls = total_calls.clone();+        handles.push(std::thread::spawn(move || {+            let fetcher = DelayedFake {+                delay_ms: 100,+                fail: std::sync::atomic::AtomicBool::new(false),+                calls: std::sync::atomic::AtomicU64::new(0),+            };+            let r = shared_reader(&dir, clock, fetcher, prefix_gate, flights);+            barrier.wait();+            let out = read_batch(&r, &[(0, 16), (4096, 16)]);+            assert!(out.iter().all(|s| s.is_ok()), "every reader gets its ranges");+            total_calls.fetch_add(r.fetcher.calls.load(Ordering::SeqCst), Ordering::SeqCst);+        }));+    }+    for h in handles {+        h.join().unwrap();+    }+    assert_eq!(+        total_calls.load(Ordering::SeqCst),+        2,+        "one fetch per distinct cold range across all readers",+    );+}++/// A failed flight is shared as an error, once, rather than one failing+/// fetch per reader. (The claim is dropped on publish, so a later read+/// retries — that is the `publish` contract in `caching.rs`.)+#[test]+fn a_failed_flight_is_shared_once_not_once_per_reader() {+    let f = Fixture::new("singleflight_fail");+    let clock = Arc::new(AtomicU64::new(1_000_000));+    let prefix_gate = Arc::new(std::sync::atomic::AtomicBool::new(false));+    let flights = Arc::new(crate::tile::source::RangeFlights::new());+    let barrier = Arc::new(std::sync::Barrier::new(4));+    let total_calls = Arc::new(std::sync::atomic::AtomicU64::new(0));+    let mut handles = Vec::new();+    for _ in 0..4 {+        let dir = f.dir.clone();+        let clock = clock.clone();+        let barrier = barrier.clone();+        let prefix_gate = prefix_gate.clone();+        let flights = flights.clone();+        let total_calls = total_calls.clone();+        handles.push(std::thread::spawn(move || {+            let fetcher = DelayedFake {+                delay_ms: 100,+                fail: std::sync::atomic::AtomicBool::new(true),+                calls: std::sync::atomic::AtomicU64::new(0),+            };+            let r = shared_reader(&dir, clock, fetcher, prefix_gate, flights);+            barrier.wait();+            assert!(r.read(0, 16).is_err(), "every follower sees the failure");+            total_calls.fetch_add(r.fetcher.calls.load(Ordering::SeqCst), Ordering::SeqCst);+        }));+    }+    for h in handles {+        h.join().unwrap();+    }+    assert_eq!(total_calls.load(Ordering::SeqCst), 1, "one fetch for the whole flight");+}++/// A range repeated inside one batch is fetched once and answers both slots.+#[test]+fn a_range_repeated_in_one_batch_is_fetched_once() {+    let f = Fixture::new("batch_dup");+    let clock = Arc::new(AtomicU64::new(1_000_000));+    let r = reader(&f.dir, clock, Fake { ranges: std::sync::Mutex::new(Vec::new()) });+    let out = read_batch(&r, &[(0, 8), (0, 8), (100, 8)]);+    assert_eq!(out.len(), 3);+    assert!(out.iter().all(|s| s.is_ok()));+    let mut logged = r.fetcher.ranges.lock().unwrap().clone();+    logged.sort();+    assert_eq!(logged, vec!["bytes=0-7", "bytes=100-107"], "no duplicate range in the wave");+}
library/network/src/test/java/com/vayunmathur/library/network/NativeHttpBatchTest.kt
diff --git a/library/network/src/test/java/com/vayunmathur/library/network/NativeHttpBatchTest.kt b/library/network/src/test/java/com/vayunmathur/library/network/NativeHttpBatchTest.ktindex e01e23736f..e4f455d092 100644--- a/library/network/src/test/java/com/vayunmathur/library/network/NativeHttpBatchTest.kt+++ b/library/network/src/test/java/com/vayunmathur/library/network/NativeHttpBatchTest.kt@@ -124,6 +124,65 @@ class NativeHttpBatchTest {         assertEquals(0, replyStatus(frames[0]), "a transport failure is status 0")     } +    /**+     * The wave is concurrent over a reused pool, not N serial requests on N fresh+     * connections: with a 150 ms server delay, 12 ranges serially would take ~1.8 s+     * and 12 fresh connections; a pooled wave overlaps them and the next wave reuses+     * most of those connections (counted as server-side remote ports).+     */+    @Test+    fun a_wave_overlaps_and_the_next_wave_reuses_connections() {+        // Own server: the shared fixture's default executor serialises handlers,+        // which would mask the client's concurrency this test measures.+        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+        server.executor = java.util.concurrent.Executors.newFixedThreadPool(16)+        val baseUrl = "http://127.0.0.1:${server.address.port}"+        val body = ByteArray(8192) { (it % 251).toByte() }+        val ports = java.util.Collections.synchronizedSet(mutableSetOf<Int>())+        val concurrent = java.util.concurrent.atomic.AtomicInteger(0)+        val maxConcurrent = java.util.concurrent.atomic.AtomicInteger(0)+        server.createContext("/archive") { exchange ->+            val now = concurrent.incrementAndGet()+            maxConcurrent.updateAndGet { maxOf(it, now) }+            try {+                Thread.sleep(150)+            } catch (_: InterruptedException) {+            }+            concurrent.decrementAndGet()+            ports.add(exchange.remoteAddress.port)+            val range = exchange.requestHeaders.getFirst("Range")+            val (start, end) = range+                ?.removePrefix("bytes=")+                ?.split("-", limit = 2)+                ?.map { it.toLongOrNull() }+                .let { (it?.getOrNull(0) ?: 0L) to (it?.getOrNull(1) ?: (body.size - 1).toLong()) }+            val slice = body.copyOfRange(start.toInt(), (end + 1).toInt())+            exchange.responseHeaders.add("Content-Range", "bytes $start-$end/${body.size}")+            exchange.sendResponseHeaders(206, slice.size.toLong())+            exchange.responseBody.use { it.write(slice) }+        }+        server.start()+        try {+        val ranges = Array(12) { "bytes=${it * 128}-${it * 128 + 127}" }+        val started = System.nanoTime()+        val packed = NativeHttpBridge.requestBatch("$baseUrl/archive", ranges)+        val elapsedMs = (System.nanoTime() - started) / 1_000_000+        assertEquals(12, decodeBatch(packed, 12).size)+        assertTrue(maxConcurrent.get() >= 6, "wave overlapped only ${maxConcurrent.get()} requests")+        assertTrue(elapsedMs < 900, "wave took ${elapsedMs}ms; serial would be ~1800ms")+        val firstWavePorts = ports.toSet()+        ports.clear()+        NativeHttpBridge.requestBatch("$baseUrl/archive", ranges)+        val reused = ports.count { it in firstWavePorts }+        assertTrue(+            reused >= 6,+            "second wave reused $reused/12 pooled connections (ports $ports vs $firstWavePorts)",+        )+        } finally {+            server.stop(0)+        }+    }+     @Test     fun batch_framing_round_trips_and_refuses_garbage() {         val body = ByteArray(64) { it.toByte() }