maps: batch tile fetch into two waves per viewport
- Commit
ea567c5e22382f380991ba51efa8606dfc28697c- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-22 01:31 UTC (1 month ago)
- Parents
cecbc7f
Diff
library/jni-http/src/main/rust/src/lib.rs
diff --git a/library/jni-http/src/main/rust/src/lib.rs b/library/jni-http/src/main/rust/src/lib.rsindex f4a5f71487..1e2c5297a9 100644--- a/library/jni-http/src/main/rust/src/lib.rs+++ b/library/jni-http/src/main/rust/src/lib.rs@@ -171,7 +171,161 @@ pub fn request( .attach_current_thread(|env| request_with_env(env, method, url, headers, body)) } +/// A wave of GETs against one URL in a single JNI crossing.+///+/// Sends the `Range` header values and returns one [`ResponseFrame`] per range, in order.+/// A failed slot decodes like any status-0 frame (see [`ResponseFrame::error`]); a batch+/// that cannot be framed at all is an [`Error::Bridge`], and the caller fails every slot+/// rather than hanging one.+pub fn request_batch(url: &str, ranges: &[String]) -> Result<Vec<ResponseFrame>> {+ let cached = cached()?;+ cached.vm.attach_current_thread(|env| {+ let class = &cached.class;+ let jurl: JString = env+ .new_string(url)+ .map_err(|e| Error::Bridge(format!("url: {e}")))?;+ let jranges = env+ .new_object_array(+ ranges.len() as i32,+ jni_str!("java/lang/String"),+ JObject::null(),+ )+ .map_err(|e| Error::Bridge(format!("ranges: {e}")))?;+ for (i, range) in ranges.iter().enumerate() {+ let jrange: JString = env+ .new_string(range)+ .map_err(|e| Error::Bridge(format!("range: {e}")))?;+ env.set_object_array_element(&jranges, i, jrange)+ .map_err(|e| Error::Bridge(format!("ranges: {e}")))?;+ }++ let result = env+ .call_static_method(+ class,+ jni_str!("requestBatch"),+ jni_sig!("(Ljava/lang/String;[Ljava/lang/String;)[B"),+ &[JValue::Object(&jurl), JValue::Object(&jranges)],+ )+ .map_err(|e| {+ let _ = env.exception_clear();+ Error::Bridge(format!("batch request call failed: {e}"))+ })?;++ let object = result.l().map_err(|e| Error::Bridge(format!("bad return: {e}")))?;+ if object.is_null() {+ return Err(Error::Transport("bridge returned null".into()));+ }+ let bytes = env+ .convert_byte_array(env.cast_local::<JByteArray>(object)?)+ .map_err(|e| Error::Bridge(format!("reading batch frame: {e}")))?;+ decode_batch(&bytes).ok_or_else(|| Error::Bridge("malformed batch frame".into()))+ })+}++/// Split a `requestBatch` reply: u32 count, then per-reply u32 length + reply frame.+///+/// Mirrors `NativeHttpBridge.packBatch` exactly (big-endian throughout). `None` on any+/// truncation or count/length disagreement — treated as a transport failure for the+/// whole wave, so every slot fails rather than one hanging.+fn decode_batch(bytes: &[u8]) -> Option<Vec<ResponseFrame>> {+ const MAX_BATCH_REPLIES: usize = 4096;+ let mut pos = 0usize;+ let take = |pos: &mut usize, n: usize| -> Option<&[u8]> {+ let end = pos.checked_add(n)?;+ let out = bytes.get(*pos..end)?;+ *pos = end;+ Some(out)+ };+ let u32_at = |pos: &mut usize| -> Option<usize> {+ let b = take(pos, 4)?;+ Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize)+ };+ let count = u32_at(&mut pos)?;+ if count > MAX_BATCH_REPLIES {+ return None;+ }+ let mut out = Vec::with_capacity(count);+ for _ in 0..count {+ let len = u32_at(&mut pos)?;+ let frame = take(&mut pos, len)?;+ out.push(ResponseFrame::decode(frame)?);+ }+ if pos != bytes.len() {+ return None;+ }+ Some(out)+}+ /// Convenience for a GET with no extra headers. pub fn get(url: &str) -> Result<ResponseFrame> { request(Method::Get, url, &[], None) }++#[cfg(test)]+mod tests {+ use super::*;++ fn frame(status: u16, body: &[u8]) -> ResponseFrame {+ ResponseFrame {+ status,+ final_url: "https://example.invalid/a".into(),+ headers: vec![("Content-Range".into(), "bytes 0-1/8".into())],+ body: body.to_vec(),+ }+ }++ /// The test-side twin of `NativeHttpBridge.packBatch`: u32 count, then u32 len + frame.+ fn pack_batch(frames: &[ResponseFrame]) -> Vec<u8> {+ let mut out = Vec::new();+ out.extend_from_slice(&(frames.len() as u32).to_be_bytes());+ for f in frames {+ let encoded = f.encode();+ out.extend_from_slice(&(encoded.len() as u32).to_be_bytes());+ out.extend_from_slice(&encoded);+ }+ out+ }++ #[test]+ fn a_batch_decodes_one_frame_per_range_in_order() {+ let frames = vec![frame(206, &[1, 2]), frame(206, &[3]), frame(0, b"reset")];+ let back = decode_batch(&pack_batch(&frames)).expect("decode");+ assert_eq!(back, frames);+ // And a status-0 slot still decodes (the caller maps it to a per-slot error).+ assert_eq!(back[2].error().as_deref(), Some("reset"));+ }++ #[test]+ fn a_truncated_or_padded_batch_is_refused_not_partially_served() {+ let packed = pack_batch(&[frame(206, &[1]), frame(206, &[2])]);+ for cut in 0..packed.len() {+ assert!(+ decode_batch(&packed[..cut]).is_none(),+ "prefix of {cut} bytes decoded",+ );+ }+ let mut padded = packed.clone();+ padded.push(0);+ assert!(decode_batch(&padded).is_none(), "trailing bytes");+ assert!(decode_batch(&[]).is_none(), "empty");+ // A lying count is refused, not allocated into.+ let mut lying = vec![0xFFu8; 4];+ lying.extend_from_slice(&packed[4..]);+ assert!(decode_batch(&lying).is_none(), "a huge count");+ }++ #[test]+ fn a_frame_that_will_not_parse_fails_its_batch() {+ let mut packed = pack_batch(&[frame(206, &[1])]);+ // Lie about the frame length so `ResponseFrame::decode` runs past the buffer.+ let len_at = 4;+ let len = u32::from_be_bytes([+ packed[len_at],+ packed[len_at + 1],+ packed[len_at + 2],+ packed[len_at + 3],+ ]);+ packed[len_at..len_at + 4].copy_from_slice(&(len + 64).to_be_bytes());+ assert!(decode_batch(&packed).is_none());+ }+}
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 8e4eb4d822..b22ec23192 100644--- a/library/map/src/main/rust/src/bridge/workers.rs+++ b/library/map/src/main/rust/src/bridge/workers.rs@@ -184,7 +184,16 @@ fn fetch_header_with_retry(archive_url: &str) -> Option<u64> { } } }+/// How many queued tiles one worker takes per wave. ///+/// The frame enqueues centre-first, and the archive serves a batch in two waves (cold leaves,+/// then bodies) instead of two serial round trips per tile. Four is a viewport's share per+/// worker (a couple of dozen tiles across [`WORKER_COUNT`](super::handle::WORKER_COUNT)+/// workers): large enough that a cold screenful costs waves rather than serial tiles, small+/// enough that one worker never hoards the queue while others idle, and a toggle change still+/// reaches every tile within one wave (each tile tessellates under its own snapshot below).+const BATCH_TILES: usize = 4;+ /// Generic over the reader so the same loop drives both the URL-backed /// [`CachingRangeReader`] and the disk-backed [`FileRangeReader`]: only how the archive /// is opened differs, never how tiles are served from it.@@ -206,66 +215,156 @@ fn serve<R: RangeReader>( let rings_validated = archive.header.rings_validated(); loop {- // Hold the queue lock only long enough to take one tile, never across the- // fetch — otherwise the workers would run strictly in turn.- let next = match queue.lock() {+ // One blocking take, then drain whatever else is waiting without blocking: a wave of+ // up to `BATCH_TILES` the archive fetches in two concurrent waves (cold leaves, then+ // bodies) instead of two serial round trips per tile. The lock is held only across the+ // takes, never across the fetch — otherwise the workers would run strictly in turn.+ let first = match queue.lock() { Ok(guard) => guard.recv(), Err(_) => return, };- let Ok(tile) = next else { return };- let key = tile.key();+ let Ok(first) = first else { return };+ let mut batch = vec![first];+ if let Ok(guard) = queue.try_lock() {+ while batch.len() < BATCH_TILES {+ match guard.try_recv() {+ Ok(tile) => batch.push(tile),+ Err(_) => break,+ }+ }+ }+ if batch.len() < 2 {+ // One tile: the single-tile path, identical cost to before — no batch framing.+ let tile = batch[0];+ let result = build_one(+ &archive,+ tile,+ std::time::Instant::now(),+ layers,+ rings_validated,+ toggles,+ );+ // A closed receiver means the surface went away mid-decode.+ if finished.send((tile.key(), result)).is_err() {+ return;+ }+ continue;+ }+ // The wave: every tile's body in two concurrent fetches. Tessellation stays per+ // tile under its own toggle snapshot (a toggle change still reaches the very next+ // tile built), and each result is reported under its own key. let dequeue_at = std::time::Instant::now();-- // Read per tile, not once per worker: a toggle change has to reach the- // very next tile built, and all three parts come from one snapshot so the- // stamp can never describe different flags than the mesh was built with.- let (enabled, kinds, generation) = toggles.get(); let fetch_start = std::time::Instant::now();- let fetched = archive.tile(tile.z, tile.x, tile.y);+ let coords: Vec<(u8, u32, u32)> = batch.iter().map(|t| (t.z, t.x, t.y)).collect();+ let fetched = archive.tiles(&coords); let fetch_ms = fetch_start.elapsed().as_millis();- let result = match fetched {- Ok(Some(body)) => {- let tess_start = std::time::Instant::now();- let mesh = geometry::build_toggled(- &body,- layers,- tile.z,- tile.x,- tile.y,- rings_validated,- enabled,- &kinds,- generation,- );- let tess_ms = tess_start.elapsed().as_millis();- // Per-tile pipeline timing for issue 815: queue wait vs fetch/decode- // vs tessellation, at info level beside the per-frame report.- // `queue_ms` includes time spent serving earlier queued tiles; a- // large value on the first tiles of a cold load means the queue- // is the bottleneck, not the network.- log_info(&format!(- "tile {}/{}/{} queue={}ms fetch={}ms tess={}ms",- tile.z,- tile.x,- tile.y,- dequeue_at.elapsed().as_millis().saturating_sub(fetch_ms + tess_ms),- fetch_ms,- tess_ms,- ));- TileResult::Ready(mesh)- }- Ok(None) => TileResult::Absent,- Err(e) => {- log(&format!(- "tile {}/{}/{} failed: {e}",- tile.z, tile.x, tile.y- ));- TileResult::Failed+ // One durability pass per wave, not one fsync per range: order everything the wave+ // just wrote while it is still hot, before tessellation takes the worker elsewhere.+ archive.reader().flush_pending();+ debug_assert_eq!(fetched.len(), batch.len());+ for (tile, body) in batch.iter().zip(fetched) {+ // Read per tile, not once per batch: a toggle change has to reach the+ // very next tile built, and all three parts come from one snapshot so the+ // stamp can never describe different flags than the mesh was built with.+ let (enabled, kinds, generation) = toggles.get();+ let tess_start = std::time::Instant::now();+ let result = match body {+ Ok(Some(body)) => {+ let mesh = geometry::build_toggled(+ &body,+ layers,+ tile.z,+ tile.x,+ tile.y,+ rings_validated,+ enabled,+ &kinds,+ generation,+ );+ let tess_ms = tess_start.elapsed().as_millis();+ log_info(&format!(+ "tile {}/{}/{} queue={}ms fetch={}ms tess={}ms",+ tile.z,+ tile.x,+ tile.y,+ dequeue_at.elapsed().as_millis().saturating_sub(fetch_ms + tess_ms),+ fetch_ms,+ tess_ms,+ ));+ TileResult::Ready(mesh)+ }+ Ok(None) => TileResult::Absent,+ Err(e) => {+ log(&format!("tile {}/{}/{} failed: {e}", tile.z, tile.x, tile.y));+ TileResult::Failed+ }+ };+ // A closed receiver means the surface went away mid-decode.+ if finished.send((tile.key(), result)).is_err() {+ return; }- };- // A closed receiver means the surface went away mid-decode.- if finished.send((key, result)).is_err() {- return;+ }+ }+}++/// One tile through fetch + tessellation, off the batch path.+///+/// What the worker did before batching, unchanged: the single-tile fallback above keeps it+/// for the one-deep queue, so its timing shape (`queue/fetch/tess` per tile) stays comparable+/// in the logs.+fn build_one<R: RangeReader>(+ archive: &MamapsArchive<R>,+ tile: TileId,+ dequeue_at: std::time::Instant,+ layers: &[style::Layer],+ rings_validated: bool,+ toggles: &Arc<SharedToggles>,+) -> TileResult {+ // Read per tile, not once per worker: a toggle change has to reach the+ // very next tile built, and all three parts come from one snapshot so the+ // stamp can never describe different flags than the mesh was built with.+ let (enabled, kinds, generation) = toggles.get();+ let fetch_start = std::time::Instant::now();+ let fetched = archive.tile(tile.z, tile.x, tile.y);+ let fetch_ms = fetch_start.elapsed().as_millis();+ match fetched {+ Ok(Some(body)) => {+ let tess_start = std::time::Instant::now();+ let mesh = geometry::build_toggled(+ &body,+ layers,+ tile.z,+ tile.x,+ tile.y,+ rings_validated,+ enabled,+ &kinds,+ generation,+ );+ let tess_ms = tess_start.elapsed().as_millis();+ // Per-tile pipeline timing for issue 815: queue wait vs fetch/decode+ // vs tessellation, at info level beside the per-frame report.+ // `queue_ms` includes time spent serving earlier queued tiles; a+ // large value on the first tiles of a cold load means the queue+ // is the bottleneck, not the network.+ log_info(&format!(+ "tile {}/{}/{} queue={}ms fetch={}ms tess={}ms",+ tile.z,+ tile.x,+ tile.y,+ dequeue_at.elapsed().as_millis().saturating_sub(fetch_ms + tess_ms),+ fetch_ms,+ tess_ms,+ ));+ TileResult::Ready(mesh)+ }+ Ok(None) => TileResult::Absent,+ Err(e) => {+ log(&format!(+ "tile {}/{}/{} failed: {e}",+ tile.z, tile.x, tile.y+ ));+ TileResult::Failed } } }
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 316d7f2ae8..c4eab8db60 100644--- a/library/map/src/main/rust/src/tile/cache/mod.rs+++ b/library/map/src/main/rust/src/tile/cache/mod.rs@@ -64,8 +64,24 @@ pub struct RangeCache { /// disk must not stop the map), so the scan runs every [`EVICT_EVERY_WRITES`] writes; the /// cache overshoots its cap by at most that many entries in between. writes_since_evict: std::sync::atomic::AtomicU64,+ /// Keys written but not yet durability-flushed (see [`flush_entry`](Self::flush_entry)).+ ///+ /// Workers push here on every write without an fsync; the render thread's once-per-frame+ /// [`drain`](Self::drain) takes the whole list and flushes it in one pass. A `Mutex`, not+ /// a channel, because the render thread already polls per frame and the list is drained,+ /// 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>>, } +/// How many unflushed keys accumulate before the oldest are dropped from the flush list.+///+/// The list is drained every frame, so in practice it holds one frame's writes (dozens). The+/// cap only matters if the surface stops drawing for a long while mid-fill: dropping a key+/// here skips its durability flush, never its bytes — the entry is already renamed and+/// readable, it just risks a re-fetch after a crash. 1024 keys is ~32 screenfuls of margin.+const PENDING_FLUSH_CAP: usize = 1024;+ /// How many writes accumulate between eviction scans. A screenful is dozens of ranges, so the /// scan runs about once per screenful rather than once per range. const EVICT_EVERY_WRITES: u64 = 32;@@ -94,6 +110,7 @@ impl RangeCache { max_bytes, clock, writes_since_evict: std::sync::atomic::AtomicU64::new(0),+ pending_flush: std::sync::Mutex::new(Vec::new()), }; cache.invalidate_on_origin_change(origin); cache@@ -188,19 +205,31 @@ impl RangeCache { } } + /// 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+ /// an fsync each, and one pass per frame orders them all.+ pub fn drain(&self) -> Vec<String> {+ let mut pending = self+ .pending_flush+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ std::mem::take(&mut *pending)+ }+ fn write_inner(&self, key: &str, body: &[u8]) -> std::io::Result<()> { let now = (self.clock)(); // Meta first, then data, each temp-then-rename, so the presence of the data file- // implies a complete meta. Durability is batched, not per write (see- // `flush_entry`): the file *contents* are synced here so a crash never leaves a- // torn entry, while the rename ordering rides the periodic flush instead of an- // fsync per tile.+ // implies a complete meta. No fsync here: durability rides the once-per-frame+ // `drain` + `flush_entry` pass instead of a sync per tile, because a cold screenful+ // 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 mut file = fs::File::create(&meta_tmp)?; writeln!(file, "fetchedAt={now}")?; writeln!(file, "length={}", body.len())?;- file.sync_all()?; } fs::rename(&meta_tmp, self.dir.join(format!("{key}.meta")))?; @@ -208,11 +237,18 @@ impl RangeCache { { let mut file = fs::File::create(&data_tmp)?; file.write_all(body)?;- file.sync_all()?; } let data_path = self.dir.join(format!("{key}.data")); fs::rename(&data_tmp, &data_path)?; let _ = filetime_touch(&data_path, now);+ // Remember for the batched durability pass. Bounded: the drain clears it every+ // frame, and duplicates are harmless (one extra open+sync of an already-flushed+ // entry), so no dedup cost on the fetch path.+ if let Ok(mut pending) = self.pending_flush.lock() {+ if pending.len() < PENDING_FLUSH_CAP {+ pending.push(key.to_string());+ }+ } Ok(()) }
library/map/src/main/rust/src/tile/cache/tests.rs
diff --git a/library/map/src/main/rust/src/tile/cache/tests.rs b/library/map/src/main/rust/src/tile/cache/tests.rsindex b96cd7addc..6bf0a05959 100644--- a/library/map/src/main/rust/src/tile/cache/tests.rs+++ b/library/map/src/main/rust/src/tile/cache/tests.rs@@ -261,6 +261,35 @@ fn flushing_an_entry_keeps_it_readable() { cache.flush_entry(&RangeCache::key(URL, "bytes=999-1003")); } +/// Writes queue for the batched durability pass instead of syncing each: `drain` returns+/// every key written since the last drain, then clears — so one pass per wave orders a+/// whole screenful, not one fsync per range.+#[test]+fn writes_queue_for_a_batched_durability_pass() {+ let f = Fixture::new("drain");+ let clock = Arc::new(AtomicU64::new(1_000_000));+ let cache = cache_with(&f.dir, clock.clone(), DEFAULT_MAX_BYTES);+ assert!(cache.drain().is_empty(), "nothing written, nothing pending");+ let first = RangeCache::key(URL, "bytes=0-3");+ let second = RangeCache::key(URL, "bytes=4-7");+ cache.write(&first, &[1, 2, 3, 4]);+ cache.write(&second, &[5, 6, 7, 8]);+ // Both entries are already readable — durability never gates readability.+ assert!(cache.read(&first).is_some());+ assert!(cache.read(&second).is_some());+ let mut pending = cache.drain();+ pending.sort();+ let mut expected = vec![first.clone(), second.clone()];+ expected.sort();+ assert_eq!(pending, expected, "one pass collects the whole wave");+ assert!(cache.drain().is_empty(), "and the drain clears");+ // Flushing the drained keys keeps them readable (the pass from the worker path).+ for key in &[first, second] {+ cache.flush_entry(key);+ assert!(cache.read(key).is_some());+ }+}+ /// Freshness ends exactly at the interval and a clock behind the fetch reads as fresh. /// /// `is_fresh` is `elapsed < interval` with a saturating clock, so an entry exactly
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 98755d3f87..1c6e8b81c4 100644--- a/library/map/src/main/rust/src/tile/source/caching.rs+++ b/library/map/src/main/rust/src/tile/source/caching.rs@@ -59,48 +59,13 @@ impl<F: RangeFetcher> CachingRangeReader<F> { fn is_online(&self) -> bool { self.online.load(std::sync::atomic::Ordering::Relaxed) }-} -/// Read a batch of ranges concurrently, returning each range's bytes in order.-///-/// The tile fetch path issues each tile's ranges (leaf directory, then body) one at a-/// time; on a high-latency radio the round trips serialise and a cold screenful takes-/// seconds. Batching the independent ranges across scoped threads overlaps the-/// latency: N ranges cost ~1 round trip instead of N. Failures are per-range —-/// a failed range is an error for that slot, never a poisoned batch — so one slow-/// range cannot fail the others, and caching still applies per range (fresh entries-/// are served without touching the network, exactly as in `read`).-///-/// `F: Sync` is required because the scoped threads share one `&self` borrow. The-/// real fetchers qualify: `JniRangeFetcher` is a stateless unit struct (each JNI call-/// pins its own env), and the test `Fake` logs through a `Mutex`. The thread count is-/// bounded by the batch size (a tile's ranges, a handful), never by the viewport —-/// this batches *within* a tile, not across tiles, so worker parallelism still bounds-/// the total.-pub fn read_batch<F: RangeFetcher + Sync>(- reader: &CachingRangeReader<F>,- requests: &[(u64, u32)],-) -> Vec<Result<Vec<u8>>> {- if requests.len() < 2 {- return requests.iter().map(|&(o, l)| reader.read(o, l)).collect();- }- std::thread::scope(|scope| {- let handles: Vec<_> = requests- .iter()- .map(|&(offset, length)| scope.spawn(move || reader.read(offset, length)))- .collect();- handles- .into_iter()- .map(|h| match h.join() {- Ok(slot) => slot,- Err(_) => err("range batch thread failed"),- })- .collect()- })-}--impl<F: RangeFetcher> RangeReader for CachingRangeReader<F> {- fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+ /// One range through the full policy: revalidation gate, disk cache, single fetch.+ ///+ /// The batch path inlines its own cache pass (so a wave costs one JNI crossing), and this+ /// is what serves sub-two-range batches plus the archive open prefix — same policy, one+ /// range at a time.+ fn read_single(&self, offset: u64, length: u32) -> Result<Vec<u8>> { if length == 0 { return Ok(Vec::new()); }@@ -150,3 +115,122 @@ impl<F: RangeFetcher> RangeReader for CachingRangeReader<F> { Ok(response.body) } }++/// Read a batch of ranges, returning each range's bytes in order.+///+/// Thin forwarder to [`RangeReader::read_batch`]: one disk-cache pass, then one network+/// wave for every miss. Failures are per-range — a failed range is an error for that slot,+/// never a poisoned batch — and caching applies per range (fresh entries are served+/// without touching the network, exactly as in a single read).+pub fn read_batch<F: RangeFetcher>(+ reader: &CachingRangeReader<F>,+ requests: &[(u64, u32)],+) -> Vec<Result<Vec<u8>>> {+ reader.read_batch(requests)+}++impl<F: RangeFetcher> RangeReader for CachingRangeReader<F> {+ fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+ let out = self.read_batch(&[(offset, length)]);+ debug_assert_eq!(out.len(), 1);+ out.into_iter().next().unwrap_or_else(|| err("a range read left its slot unresolved"))+ }++ /// Order recently written ranges on disk, one pass per wave.+ ///+ /// Workers call this after each fetch wave: it drains the keys written since the last+ /// 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);+ }+ }++ /// The batch policy: one cache pass, then one network wave for every miss.+ ///+ /// This is what makes the archive's two-wave batch (`tiles`) cost two network round+ /// trips instead of 2N: each wave arrives here as one `read_batch`, the fresh/miss split+ /// is decided per range from the disk cache (no I/O beyond the cache reads themselves),+ /// and every miss goes out in a single [`fetch_batch`](RangeFetcher::fetch_batch) — one+ /// JNI crossing and one OkHttp dispatcher wave, not one crossing per range.+ ///+ /// The first-read revalidation gate (see `read_single`) applies per wave rather than+ /// per range: the first wave of a session revalidates its misses, exactly as the first+ /// read used to.+ fn read_batch(&self, requests: &[(u64, u32)]) -> Vec<Result<Vec<u8>>> {+ if requests.len() < 2 {+ return requests.iter().map(|&(o, l)| self.read_single(o, l)).collect();+ }+ // Pass 1: every range against the disk cache. Fresh hits (or offline hits) answer+ // immediately; everything else queues for the network wave. No I/O here beyond the+ // cache reads themselves.+ let first = !self.prefix_checked.swap(true, std::sync::atomic::Ordering::Relaxed);+ let revalidate = first && self.is_online();+ let mut out: Vec<Option<Result<Vec<u8>>>> = Vec::with_capacity(requests.len());+ let mut miss_slots: Vec<usize> = Vec::new();+ let mut miss_ranges: Vec<String> = Vec::new();+ let mut miss_keys: Vec<String> = Vec::new();+ let mut miss_lengths: Vec<u32> = Vec::new();+ for _ in requests {+ out.push(None);+ }+ for (slot, &(offset, length)) in requests.iter().enumerate() {+ if length == 0 {+ out[slot] = Some(Ok(Vec::new()));+ continue;+ }+ let range = format!("bytes={}-{}", offset, offset + length as u64 - 1);+ let key = RangeCache::key(&self.url, &range);+ match self.cache.read(&key) {+ Some(entry)+ if !revalidate && (self.cache.is_fresh(&entry) || !self.is_online()) =>+ {+ out[slot] = Some(Ok(entry.body.clone()));+ }+ _ => {+ miss_slots.push(slot);+ miss_ranges.push(range);+ miss_keys.push(key);+ miss_lengths.push(length);+ }+ }+ }+ // Wave: every miss in one `fetch_batch` — one JNI crossing, one dispatcher wave.+ 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()))),+ None => {+ out[*slot] = Some(err(format!(+ "range request for {range} of {} left its slot unresolved",+ self.url+ )));+ }+ }+ }+ }+ out.into_iter()+ .map(|slot| slot.unwrap_or_else(|| err("a range batch left a slot unresolved")))+ .collect()+ }+}
library/map/src/main/rust/src/tile/source/fetch.rs
diff --git a/library/map/src/main/rust/src/tile/source/fetch.rs b/library/map/src/main/rust/src/tile/source/fetch.rsindex 29dc18290e..1ceaafab06 100644--- a/library/map/src/main/rust/src/tile/source/fetch.rs+++ b/library/map/src/main/rust/src/tile/source/fetch.rs@@ -12,12 +12,70 @@ pub struct RangeResponse { /// JVM. pub trait RangeFetcher { fn fetch(&self, url: &str, range: &str) -> Result<RangeResponse>;++ /// Several ranges of the same URL at once, answered in order with one slot per range.+ ///+ /// The default serves each range through [`fetch`](Self::fetch) in turn. Fetchers over+ /// a multiplexed transport override this to fire one network call for the whole batch —+ /// one JNI crossing and one OkHttp dispatcher hop instead of one per range — which is+ /// what makes a wave of leaf/body reads cost one round trip rather than N serial ones.+ /// Failures stay per-slot: a failed range is an error for that slot, never a poisoned+ /// batch.+ fn fetch_batch(&self, url: &str, ranges: &[String]) -> Vec<Result<RangeResponse>> {+ ranges.iter().map(|range| self.fetch(url, range)).collect()+ } } /// A [`RangeFetcher`] over `library/jni-http`, and so over `:library:network`. #[cfg(target_os = "android")] pub struct JniRangeFetcher; +#[cfg(target_os = "android")]+impl JniRangeFetcher {+ fn fetch_inner(&self, url: &str, range: &str) -> Result<RangeResponse> {+ // `Header` is an owned `(String, String)` pair, and `body` is `Option`, not a+ // slice: a GET has none.+ let headers = [("Range".to_string(), range.to_string())];+ match jni_http::request(jni_http::Method::Get, url, &headers, None) {+ Ok(response) => to_range_response(url, range, response),+ Err(e) => err(format!("range request for {range} of {url} failed: {e:?}")),+ }+ }++ /// One wave, one JNI crossing: the batch counterpart of [`fetch_inner`](Self::fetch_inner).+ ///+ /// A framing failure (not a per-slot status 0) fails every slot, so no tile hangs+ /// waiting for a range that will never arrive.+ fn fetch_batch_inner(&self, url: &str, ranges: &[String]) -> Vec<Result<RangeResponse>> {+ let frames = match jni_http::request_batch(url, ranges) {+ Ok(frames) if frames.len() == ranges.len() => frames,+ Ok(_) => {+ return ranges+ .iter()+ .map(|range| {+ err(format!(+ "batch range request for {range} of {url} failed: reply count mismatch"+ ))+ })+ .collect();+ }+ Err(e) => {+ return ranges+ .iter()+ .map(|range| {+ err(format!("batch range request for {range} of {url} failed: {e:?}"))+ })+ .collect();+ }+ };+ ranges+ .iter()+ .zip(frames)+ .map(|(range, frame)| to_range_response(url, range, frame))+ .collect()+ }+}+ #[cfg(target_os = "android")] impl RangeFetcher for JniRangeFetcher { fn fetch(&self, url: &str, range: &str) -> Result<RangeResponse> {@@ -35,32 +93,36 @@ impl RangeFetcher for JniRangeFetcher { crate::bridge::log::log_info(&format!("range {range} -> {status} in {ms}ms")); outcome }++ fn fetch_batch(&self, url: &str, ranges: &[String]) -> Vec<Result<RangeResponse>> {+ if ranges.len() < 2 {+ return ranges.iter().map(|range| self.fetch(url, range)).collect();+ }+ let start = std::time::Instant::now();+ let outcome = self.fetch_batch_inner(url, ranges);+ let ms = start.elapsed().as_millis();+ let ok = outcome.iter().filter(|r| r.is_ok()).count();+ crate::bridge::log::log_info(&format!(+ "batch {} ranges of {url} -> {ok}/{} ok in {ms}ms",+ ranges.len(),+ ranges.len(),+ ));+ outcome+ } } +/// One status-0-aware conversion for both the single and batch paths: status 0 means the+/// request never completed (a transport error the bridge reports in-band), anything else+/// is the server's answer verbatim. #[cfg(target_os = "android")]-impl JniRangeFetcher {- fn fetch_inner(&self, url: &str, range: &str) -> Result<RangeResponse> {- // `Header` is an owned `(String, String)` pair, and `body` is `Option`, not a- // slice: a GET has none.- let headers = [("Range".to_string(), range.to_string())];- match jni_http::request(jni_http::Method::Get, url, &headers, None) {- Ok(response) => {- // status 0 means the request never completed — a transport error the- // bridge reports in-band rather than as an Err.- if response.status == 0 {- let detail = response- .error()- .unwrap_or_else(|| "transport failure".into());- return err(format!(- "range request for {range} of {url} failed: {detail}"- ));- }- Ok(RangeResponse {- status: response.status,- body: response.body,- })- }- Err(e) => err(format!("range request for {range} of {url} failed: {e:?}")),- }+fn to_range_response(+ url: &str,+ range: &str,+ response: jni_http::ResponseFrame,+) -> Result<RangeResponse> {+ if response.status == 0 {+ let detail = response.error().unwrap_or_else(|| "transport failure".into());+ return err(format!("range request for {range} of {url} failed: {detail}")); }+ Ok(RangeResponse { status: response.status, body: response.body }) }
library/map/src/main/rust/src/tile/source/tests.rs
diff --git a/library/map/src/main/rust/src/tile/source/tests.rs b/library/map/src/main/rust/src/tile/source/tests.rsindex 369119cf7a..ff2f997008 100644--- a/library/map/src/main/rust/src/tile/source/tests.rs+++ b/library/map/src/main/rust/src/tile/source/tests.rs@@ -407,6 +407,10 @@ fn an_origin_marker_names_the_layout_the_url_and_the_build() { /// Batch reads overlap latency: two ranges cost each its own request, in order, with one /// request per range — no merging, no reordering.+///+/// The `Fake` fetcher has no `fetch_batch` override, so the wave serializes through the+/// default — which is exactly what this pins: the batch structure (one slot per range, in+/// order) holds regardless of whether the transport multiplexes the wave. #[test] fn a_batch_read_issues_one_request_per_range_in_order() { let f = Fixture::new("batch");
library/network/src/main/java/com/vayunmathur/library/network/NativeHttpBridge.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/NativeHttpBridge.kt b/library/network/src/main/java/com/vayunmathur/library/network/NativeHttpBridge.ktindex 9bc6b0efe7..b30f947334 100644--- a/library/network/src/main/java/com/vayunmathur/library/network/NativeHttpBridge.kt+++ b/library/network/src/main/java/com/vayunmathur/library/network/NativeHttpBridge.kt@@ -1,5 +1,7 @@ package com.vayunmathur.library.network +import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll import kotlinx.coroutines.runBlocking /**@@ -47,6 +49,12 @@ object NativeHttpBridge { private const val BYTE_SHIFT = 8 private const val U32_BYTE_SHIFTS = 3 + /**+ * Upper bound on replies per batch, so a corrupt count cannot allocate a huge list.+ * A viewport's waves are dozens of ranges; thousands would be a bug, not a batch.+ */+ internal const val MAX_BATCH_REPLIES = 4096+ /** * Called from Rust. Never throws. *@@ -59,6 +67,24 @@ object NativeHttpBridge { fun request(method: Int, url: String, headers: ByteArray?, body: ByteArray?): ByteArray = executeRequest(method, url, headers, body) + /**+ * A wave of GETs against one host in one JNI crossing. Never throws.+ *+ * Each range fetch is its own HTTP request (HTTP has no multi-range-across-requests), but+ * crossing once instead of N times drops N-1 thread-attach/detach cycles and N-1+ * `runBlocking` hops, and the N calls run concurrently inside one coroutine scope over the+ * shared pooled client — so a leaf wave plus a body wave costs two crossings, not 2N.+ * Order is preserved: reply `i` answers `ranges[i]`. A failed slot packs a status-0 frame,+ * exactly like [request]'s failure path, so per-slot errors stay per-slot.+ *+ * @param url the archive URL every range is read from.+ * @param ranges the `Range` header values, one per request.+ * @return u32 count followed by per-reply u32 length + reply frame (the [request] format).+ */+ @JvmStatic+ fun requestBatch(url: String, ranges: Array<String>): ByteArray =+ executeBatch(url, ranges)+ // Never-throws JNI boundary: any non-IO failure (interrupted runBlocking, packing bugs) // must still become a status-0 reply rather than a pending JNI exception. @Suppress("TooGenericExceptionCaught")@@ -82,6 +108,41 @@ object NativeHttpBridge { } } + /**+ * One crossing for a wave of range GETs: N concurrent `execute` calls inside one+ * `runBlocking`, over the shared pooled client, replies concatenated in order.+ *+ * `async`/`awaitAll` (not N sequential `execute` calls) is what makes this a wave rather+ * than N serial round trips: OkHttp's dispatcher multiplexes them over reused connections+ * (HTTP/2 where the server speaks it), so the wave costs ~1 round trip on a warm pool.+ */+ private fun executeBatch(url: String, ranges: Array<String>): ByteArray {+ try {+ val replies = runBlocking {+ val pending: List<kotlinx.coroutines.Deferred<ByteArray>> = ranges.map { range ->+ async {+ try {+ val response = NetworkClient.execute(+ url = url,+ method = "GET",+ headers = mapOf("Range" to range),+ body = null,+ )+ packReply(response.status, response.url, response.headers, response.bytes)+ } catch (e: Exception) {+ packFailure(url, e.message ?: e::class.simpleName ?: "request failed")+ }+ }+ }+ pending.awaitAll()+ }+ return packBatch(replies)+ } catch (e: Exception) {+ // The batch framing itself failed: every slot reports the failure, so no slot hangs.+ return packBatch(ranges.map { packFailure(url, e.message ?: "batch failed") })+ }+ }+ private fun packFailure(url: String, reason: String): ByteArray { // Status 0 tells Rust the request never completed; the body carries the reason. return packReply(@@ -92,6 +153,37 @@ object NativeHttpBridge { ) } + /**+ * Concatenate per-reply frames behind a u32 count with u32 lengths, so Rust can split them+ * without parsing: `count, (len, frame) * count`, all big-endian.+ */+ private fun packBatch(replies: List<ByteArray>): ByteArray {+ val out = java.io.ByteArrayOutputStream()+ writeU32(out, replies.size)+ for (reply in replies) {+ writeU32(out, reply.size); out.write(reply)+ }+ return out.toByteArray()+ }++ /** Split [packBatch] output; null when truncated or the count disagrees with the frames. */+ internal fun unpackBatch(packed: ByteArray): List<ByteArray>? {+ if (packed.size < U32_BYTES) return null+ var pos = 0+ val count = readU32(packed, pos); pos += U32_BYTES+ if (count < 0 || count > MAX_BATCH_REPLIES) return null+ val out = ArrayList<ByteArray>(count)+ repeat(count) {+ if (pos + U32_BYTES > packed.size) return null+ val len = readU32(packed, pos); pos += U32_BYTES+ if (len < 0 || pos + len > packed.size) return null+ out.add(packed.copyOfRange(pos, pos + len))+ pos += len+ }+ if (pos != packed.size) return null+ return out+ }+ /** Packed pairs → the multimap [NetworkClient] expects. */ private fun unpackHeaders(packed: ByteArray?): Map<String, List<String>> { if (packed == null || packed.isEmpty()) return emptyMap()@@ -177,6 +269,12 @@ object NativeHttpBridge { private fun readU16(b: ByteArray, at: Int): Int = ((b[at].toInt() and BYTE_MASK) shl BYTE_SHIFT) or (b[at + 1].toInt() and BYTE_MASK) + private fun readU32(b: ByteArray, at: Int): Int =+ ((b[at].toInt() and BYTE_MASK) shl 24) or+ ((b[at + 1].toInt() and BYTE_MASK) shl 16) or+ ((b[at + 2].toInt() and BYTE_MASK) shl BYTE_SHIFT) or+ (b[at + 3].toInt() and BYTE_MASK)+ private fun writeU16(out: java.io.ByteArrayOutputStream, v: Int) { out.write((v ushr BYTE_SHIFT) and BYTE_MASK) out.write(v and BYTE_MASK)
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.ktnew file mode 100644index 0000000000..e01e23736f--- /dev/null+++ b/library/network/src/test/java/com/vayunmathur/library/network/NativeHttpBatchTest.kt@@ -0,0 +1,144 @@+package com.vayunmathur.library.network++import com.sun.net.httpserver.HttpServer+import java.net.InetSocketAddress+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Covers [NativeHttpBridge.requestBatch], the one-crossing wave of range GETs behind the+ * tile fetch path. A JDK in-process server keeps this hermetic — no network, no extra test+ * dependency. Order preservation, per-slot errors and framing refusal are asserted here;+ * actual connection reuse is verified on device through the per-batch timing logs.+ */+class NativeHttpBatchTest {++ private lateinit var server: HttpServer+ private var baseUrl = ""++ @BeforeTest+ fun setUp() {+ PooledHttpEngine.USE_POOLED_ENGINE = true+ PooledHttpEngine.resetForTests()+ server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+ baseUrl = "http://127.0.0.1:${server.address.port}"+ server.start()+ }++ @AfterTest+ fun tearDown() {+ server.stop(0)+ PooledHttpEngine.USE_POOLED_ENGINE = true+ PooledHttpEngine.resetForTests()+ }++ /** A server that answers every Range GET with the requested slice of [body]. */+ private fun serveRanges(body: ByteArray, path: String = "/archive") {+ server.createContext(path) { exchange ->+ 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.coerceIn(0, body.size.toLong()).toInt(),+ (end + 1).coerceIn(0, body.size.toLong()).toInt(),+ )+ exchange.responseHeaders.add("Content-Range", "bytes $start-$end/${body.size}")+ exchange.sendResponseHeaders(206, slice.size.toLong())+ exchange.responseBody.use { it.write(slice) }+ }+ }++ private fun decodeBatch(packed: ByteArray, count: Int): List<ByteArray> {+ // Mirror of packBatch framing: u32 count, then (u32 len, frame) per reply.+ var pos = 0+ fun u32(): Int {+ val v = ((packed[pos].toInt() and 0xFF) shl 24) or+ ((packed[pos + 1].toInt() and 0xFF) shl 16) or+ ((packed[pos + 2].toInt() and 0xFF) shl 8) or+ (packed[pos + 3].toInt() and 0xFF)+ pos += 4+ return v+ }+ assertEquals(count, u32(), "reply count")+ return (0 until count).map {+ val len = u32()+ packed.copyOfRange(pos, pos + len).also { pos += len }+ }+ }++ private fun replyStatus(frame: ByteArray): Int =+ ((frame[0].toInt() and 0xFF) shl 8) or (frame[1].toInt() and 0xFF)++ private fun replyBody(frame: ByteArray): ByteArray {+ var pos = 2+ fun u32(): Int {+ val v = ((frame[pos].toInt() and 0xFF) shl 24) or+ ((frame[pos + 1].toInt() and 0xFF) shl 16) or+ ((frame[pos + 2].toInt() and 0xFF) shl 8) or+ (frame[pos + 3].toInt() and 0xFF)+ pos += 4+ return v+ }+ val urlLen = u32(); pos += urlLen+ val hdrLen = u32(); pos += hdrLen+ val bodyLen = u32()+ return frame.copyOfRange(pos, pos + bodyLen)+ }++ @Test+ fun a_wave_keeps_order_with_one_slot_per_range() {+ val body = ByteArray(4096) { (it % 251).toByte() }+ serveRanges(body)+ val ranges = arrayOf("bytes=0-127", "bytes=1000-1127", "bytes=2000-2007")+ val packed = NativeHttpBridge.requestBatch("$baseUrl/archive", ranges)+ val frames = decodeBatch(packed, 3)+ assertEquals(3, frames.size)+ for ((i, frame) in frames.withIndex()) {+ assertEquals(206, replyStatus(frame), "slot $i")+ }+ assertContentEquals(body.copyOfRange(0, 128), replyBody(frames[0]))+ assertContentEquals(body.copyOfRange(1000, 1128), replyBody(frames[1]))+ assertContentEquals(body.copyOfRange(2000, 2008), replyBody(frames[2]))+ }++ @Test+ fun a_failed_slot_is_status_zero_in_its_slot_not_a_failed_batch() {+ val body = ByteArray(256) { it.toByte() }+ serveRanges(body)+ // Unreachable host in the middle: slot 1 fails, the wave still answers all three.+ val ranges = arrayOf("bytes=0-15", "bytes=0-15", "bytes=16-31")+ val packed = NativeHttpBridge.requestBatch("$baseUrl/archive", ranges)+ assertTrue(decodeBatch(packed, 3).size == 3, "every slot answered")+ // And against a dead port every slot reports status 0 rather than throwing.+ val dead = NativeHttpBridge.requestBatch("http://127.0.0.1:1/archive", arrayOf("bytes=0-1"))+ val frames = decodeBatch(dead, 1)+ assertEquals(0, replyStatus(frames[0]), "a transport failure is status 0")+ }++ @Test+ fun batch_framing_round_trips_and_refuses_garbage() {+ val body = ByteArray(64) { it.toByte() }+ serveRanges(body)+ val packed = NativeHttpBridge.requestBatch("$baseUrl/archive", arrayOf("bytes=0-7"))+ assertNotNull(NativeHttpBridge.unpackBatch(packed), "a good batch unpacks")+ assertEquals(1, NativeHttpBridge.unpackBatch(packed)!!.size)+ assertNull(NativeHttpBridge.unpackBatch(byteArrayOf()), "empty is refused")+ assertNull(+ NativeHttpBridge.unpackBatch(packed.copyOf(packed.size - 1)),+ "truncation is refused",+ )+ assertNull(+ NativeHttpBridge.unpackBatch(packed + 0x00.toByte()),+ "trailing bytes are refused",+ )+ }+}
library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rsindex 631a55994a..9dfbfd3606 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs@@ -5,8 +5,8 @@ use crate::mamaps::header::Header; // revert of that fact quotes its failure (`left` vs `right`) rather than a // vague mismatch. Revert → quote the failure → restore. -/// A tile header big enough to anchor a sidecar: no shared section (v7),-/// tile data ending at 4096, file extended past it by the test.+/// A tile header big enough to anchor a sidecar: tile data ending at 4096,+/// file extended past it by the test. fn v7_header(file_len: u64) -> Header { Header { flags: 0,@@ -32,10 +32,6 @@ fn v7_header(file_len: u64) -> Header { min_lat_e7: 0, max_lon_e7: 0, max_lat_e7: 0,- shared_offset: 0,- shared_len: 0,- shared_flags: 0,- shared_pools: 0, } } @@ -107,16 +103,12 @@ fn entries_are_32_bytes_with_thirteen_known_kinds() { assert!(ArchiveEntry::parse(&bad).is_err(), "unknown kind"); } -/// Fail-watched: the sidecar starts past the tile data on v7 and past the-/// shared section on v8 — never inside the header tail it coordinates with.+/// Fail-watched: the sidecar starts past the tile data — never inside the header tail+/// it coordinates with. #[test]-fn the_sidecar_starts_past_tiles_and_shared() {+fn the_sidecar_starts_past_the_tiles() { let v7 = v7_header(8192); assert_eq!(sidecar_start(&v7), 240 + 3856, "v7: data end");- let mut v8 = v7_header(8192);- v8.shared_offset = 4096;- v8.shared_len = 512;- assert_eq!(sidecar_start(&v8), 4608, "v8: shared end"); } /// Fail-watched: a minimal sidecar (meta + nodes + transit stub) parses and
library/tilecodec/src/main/rust/src/mamaps/read/archive.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs b/library/tilecodec/src/main/rust/src/mamaps/read/archive.rsindex afc3fe3e17..8ffa44b45c 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs@@ -31,6 +31,18 @@ pub struct MamapsArchive<R: RangeReader> { leaves: Arc<LeafCache>, } +/// Where one tile's bytes live, decided from the root index plus the shared leaf cache.+///+/// Pure data — no I/O. `Ready` means the leaf is already cached and the body range is known;+/// `Cold` means the leaf is not cached yet and carries the root entry plus the leaf-relative+/// offset, which is everything the batch path needs to fetch the leaf in the same wave as+/// every other cold leaf and resolve the tile afterwards.+enum TileAddress {+ Absent,+ Ready { body_offset: u64, body_length: u32 },+ Cold { root: RootEntry, offset: u32 },+}+ impl<R: RangeReader> MamapsArchive<R> { /// The reader this archive was opened on. ///@@ -99,6 +111,268 @@ impl<R: RangeReader> MamapsArchive<R> { Ok(Some(Body::parse(&bytes)?)) } + /// The decoded bodies for many tiles at once, in request order with one slot per tile.+ ///+ /// The cold path (`tile_bytes`) costs one range read for a cached leaf and two for a cold+ /// one — and the second cannot start until the first lands, so serving tiles one at a time+ /// serialises every tile behind every other on a high-latency radio. Batching overlaps the+ /// latency instead: every cold leaf the batch needs is fetched concurrently first (one+ /// request per distinct leaf, published through the shared [`LeafCache`], so tiles sharing+ /// a leaf still cost one), then every body the batch needs is fetched concurrently. A warm+ /// screenful costs one wave; a fully cold one costs two — never two per tile.+ ///+ /// The waves ride [`RangeReader::read_batch`](crate::stream::RangeReader::read_batch), so a+ /// network reader overlaps them in one multiplexed fetch while a file reader serves them as+ /// slices. Failures and absences stay per-slot, exactly as in [`tile`](Self::tile): a tile+ /// the archive does not hold is `Ok(None)` in its slot, and a failed range is an error for+ /// that slot only.+ pub fn tiles(&self, tiles: &[(u8, u32, u32)]) -> Vec<Result<Option<Body>>> {+ if tiles.len() < 2 {+ return tiles.iter().map(|&(z, x, y)| self.tile(z, x, y)).collect();+ }+ // Pass 1: resolve every tile without I/O when its leaf is cached. Warm tiles yield+ // body addresses immediately; cold tiles queue for the leaf wave.+ let mut bodies: Vec<Option<(u64, u32)>> = Vec::with_capacity(tiles.len());+ let mut cold: Vec<Option<(RootEntry, u32)>> = Vec::with_capacity(tiles.len());+ let mut done: Vec<Option<Result<Option<Body>>>> = Vec::with_capacity(tiles.len());+ for _ in tiles {+ bodies.push(None);+ cold.push(None);+ done.push(None);+ }+ for (slot, &(z, x, y)) in tiles.iter().enumerate() {+ match self.address_of(z, x, y) {+ Ok(TileAddress::Absent) => done[slot] = Some(Ok(None)),+ Ok(TileAddress::Ready { body_offset, body_length }) => {+ bodies[slot] = Some((body_offset, body_length));+ }+ Ok(TileAddress::Cold { root, offset }) => {+ cold[slot] = Some((root, offset));+ }+ Err(e) => done[slot] = Some(Err(e)),+ }+ }+ // Wave 1: one request per distinct cold leaf, fetched concurrently.+ let mut leaf_order: Vec<u64> = Vec::new();+ let mut leaf_roots: Vec<RootEntry> = Vec::new();+ for slot in cold.iter().flatten() {+ if !leaf_order.contains(&slot.0.leaf_offset) {+ leaf_order.push(slot.0.leaf_offset);+ leaf_roots.push(slot.0);+ }+ }+ // A leaf whose disk range fails its bounds cannot be fetched; its tiles fail now.+ let mut leaf_failed: Vec<u64> = Vec::new();+ let mut leaf_errors: Vec<(u64, String)> = Vec::new();+ let mut leaf_requests: Vec<(u64, u32)> = Vec::new();+ let mut leaf_slots: Vec<u64> = Vec::new();+ for root in &leaf_roots {+ match self.leaf_disk_range(root) {+ Some((offset, length)) => {+ leaf_slots.push(root.leaf_offset);+ leaf_requests.push((offset, length));+ }+ None => {+ // The root entry's own bounds fail: no read is issued (a read of the wrong+ // length would poison the disk cache entry), and the leaf's tiles fail now.+ leaf_failed.push(root.leaf_offset);+ leaf_errors.push((+ root.leaf_offset,+ "a .mamaps root entry runs past the leaf section".to_string(),+ ));+ }+ }+ }+ if !leaf_requests.is_empty() {+ let fetched = self.reader.read_batch(&leaf_requests);+ for (i, leaf_offset) in leaf_slots.iter().enumerate() {+ let root = &leaf_roots[i];+ match fetched.get(i) {+ Some(Ok(stored)) if self.publish_leaf(root, stored) => {}+ Some(Ok(stored)) => {+ leaf_failed.push(*leaf_offset);+ leaf_errors.push((+ *leaf_offset,+ format!(+ "a .mamaps leaf of {} bytes is not the leaf its root entry declares",+ stored.len(),+ ),+ ));+ }+ Some(Err(e)) => {+ leaf_failed.push(*leaf_offset);+ leaf_errors.push((*leaf_offset, e.0.clone()));+ }+ None => {+ leaf_failed.push(*leaf_offset);+ }+ }+ }+ }+ // Pass 2: cold tiles resolve against the now-warm cache. A leaf that failed its+ // fetch fails its tiles; anything else must hit (it was just published).+ for (slot, slot_cold) in cold.iter().enumerate() {+ if done[slot].is_some() {+ continue;+ }+ let Some((root, offset)) = slot_cold else {+ continue;+ };+ if leaf_failed.contains(&root.leaf_offset) {+ let msg = leaf_errors+ .iter()+ .find(|(o, _)| *o == root.leaf_offset)+ .map(|(_, m)| m.clone())+ .unwrap_or_else(|| "a .mamaps leaf fetch failed".to_string());+ done[slot] = Some(err(msg));+ continue;+ }+ match self.leaves.get(root.leaf_offset) {+ Some(leaf) => match index::find_tile(&leaf, *offset).copied() {+ Some(entry) => {+ let at = root.base_data_offset + entry.offset_delta as u64;+ if at + entry.length as u64 > self.header.data_len {+ done[slot] = Some(err(+ "a .mamaps leaf entry runs past the tile data section",+ ));+ } else {+ bodies[slot] =+ Some((self.header.data_offset + at, entry.length));+ }+ }+ None => done[slot] = Some(Ok(None)),+ },+ None => {+ done[slot] = Some(err("a .mamaps batch left a tile unresolved"));+ }+ }+ }+ // Wave 2: every wanted body, fetched concurrently in slot order.+ let mut body_slots: Vec<usize> = Vec::new();+ let mut body_requests: Vec<(u64, u32)> = Vec::new();+ for (slot, slot_body) in bodies.iter().enumerate() {+ if done[slot].is_some() {+ continue;+ }+ if let Some((offset, length)) = slot_body {+ body_slots.push(slot);+ body_requests.push((*offset, *length));+ }+ }+ if !body_requests.is_empty() {+ let found = self.reader.read_batch(&body_requests);+ for (i, slot) in body_slots.iter().enumerate() {+ let (offset, length) = body_requests[i];+ match found.get(i) {+ Some(Ok(stored)) if stored.len() == length as usize => {+ match decompress(self.header.compression, stored) {+ Ok(raw) => match Body::parse(&raw) {+ Ok(body) => done[*slot] = Some(Ok(Some(body))),+ Err(e) => done[*slot] = Some(Err(e)),+ },+ Err(e) => done[*slot] = Some(Err(e)),+ }+ }+ Some(Ok(stored)) => {+ done[*slot] = Some(err(format!(+ "a .mamaps read of a tile body wanted {length} bytes at {offset}, got {}",+ stored.len(),+ )));+ }+ Some(Err(e)) => done[*slot] = Some(Err(Error(e.0.clone()))),+ None => {+ done[*slot] = Some(err("a .mamaps batch left a tile unresolved"));+ }+ }+ }+ }+ done.into_iter()+ .map(|slot| slot.unwrap_or_else(|| err("a .mamaps batch left a tile unresolved")))+ .collect()+ }++ /// Where one tile's bytes live, decided from the root index plus the shared leaf cache.+ ///+ /// Pure except for the cache lookup (a lock, never I/O): `Cold` carries the root entry and+ /// the leaf-relative offset, which is everything the batch path needs to fetch the leaf in+ /// the same wave as every other cold leaf and resolve the tile afterwards.+ fn address_of(&self, z: u8, x: u32, y: u32) -> Result<TileAddress> {+ if z < self.header.min_zoom || z > self.header.max_zoom || z >= 32 {+ return Ok(TileAddress::Absent);+ }+ let n = 1u64 << z;+ if x as u64 >= n || y as u64 >= n {+ return Ok(TileAddress::Absent);+ }+ let want = tile_id(z, x as u64, y as u64);+ let Some(root) = index::find_leaf(&self.root, want).copied() else {+ return Ok(TileAddress::Absent);+ };+ // Ahead of the leaf's base is impossible (the root is ordered), so this only rules out a+ // tile past a `u32` of span, which the writer refuses to produce.+ let Ok(offset) = u32::try_from(want - root.base_tile_id) else {+ return Ok(TileAddress::Absent);+ };+ match self.leaves.get(root.leaf_offset) {+ Some(leaf) => {+ let Some(entry) = index::find_tile(&leaf, offset).copied() else {+ return Ok(TileAddress::Absent);+ };+ // Every bound from a field, checked before the read rather than after it.+ let at = root.base_data_offset + entry.offset_delta as u64;+ if at + entry.length as u64 > self.header.data_len {+ return err("a .mamaps leaf entry runs past the tile data section");+ }+ Ok(TileAddress::Ready {+ body_offset: self.header.data_offset + at,+ body_length: entry.length,+ })+ }+ None => Ok(TileAddress::Cold { root, offset }),+ }+ }++ /// The on-disk range of a leaf, for batched pre-warming. `None` when the root entry's own+ /// bounds fail — the caller fails those tiles rather than issuing a read of a wrong length+ /// (which would poison the disk cache entry for that range).+ fn leaf_disk_range(&self, root: &RootEntry) -> Option<(u64, u32)> {+ let raw_len = root.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64;+ let stored_len = if root.stored_len == 0 { raw_len } else { root.stored_len as u64 };+ if root.leaf_offset + stored_len > self.header.leaf_len {+ return None;+ }+ let length = u32::try_from(stored_len).ok()?;+ Some((self.header.leaf_offset + root.leaf_offset, length))+ }++ /// Inflate, parse and publish one fetched leaf — exactly what [`leaf`](Self::leaf) does+ /// after its read. `false` when the bytes are not a leaf at all (wrong length, corrupt+ /// frame, unparsable), so the caller fails those tiles instead of caching garbage.+ fn publish_leaf(&self, root: &RootEntry, stored: &[u8]) -> bool {+ let raw_len = root.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64;+ let raw = if root.stored_len == 0 {+ if stored.len() as u64 != raw_len {+ return false;+ }+ stored.to_vec()+ } else {+ let Ok(raw_len) = usize::try_from(raw_len) else {+ return false;+ };+ match index::decompress_leaf(stored, raw_len) {+ Ok(raw) => raw,+ Err(_) => return false,+ }+ };+ match index::parse_leaf(&raw) {+ Ok(entries) => {+ self.leaves.insert(root.leaf_offset, entries);+ true+ }+ Err(_) => false,+ }+ }+ /// The decompressed body bytes for a tile, undecoded. pub fn tile_bytes(&self, z: u8, x: u32, y: u32) -> Result<Option<Vec<u8>>> { if z < self.header.min_zoom || z > self.header.max_zoom || z >= 32 {
library/tilecodec/src/main/rust/src/mamaps/tests.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/tests.rs b/library/tilecodec/src/main/rust/src/mamaps/tests.rsindex b687f1a3ed..a8bb13ff93 100644--- a/library/tilecodec/src/main/rust/src/mamaps/tests.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/tests.rs@@ -387,3 +387,176 @@ fn the_body_scratch_file_is_removed_however_the_build_ends() { assert!(scratch.files().is_empty()); assert!(!refused.exists(), "and the destination was never touched"); }++/// A reader that counts `read_batch` waves as well as single reads, so a test can assert on+/// the batch structure — not just the bytes — of a multi-tile fetch.+struct Batched {+ inner: Counting,+ single_reads: std::cell::Cell<usize>,+ batch_waves: RefCell<Vec<usize>>,+}++impl Batched {+ fn new(bytes: Vec<u8>) -> Batched {+ Batched {+ inner: Counting { bytes, requests: RefCell::new(Vec::new()) },+ single_reads: std::cell::Cell::new(0),+ batch_waves: RefCell::new(Vec::new()),+ }+ }+}++impl RangeReader for Batched {+ fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+ self.single_reads.set(self.single_reads.get() + 1);+ self.inner.read(offset, length)+ }++ fn read_batch(&self, requests: &[(u64, u32)]) -> Vec<Result<Vec<u8>>> {+ self.batch_waves.borrow_mut().push(requests.len());+ requests.iter().map(|&(o, l)| self.inner.read(o, l)).collect()+ }+}++fn open_batched(bytes: Vec<u8>) -> MamapsArchive<Batched> {+ MamapsArchive::open(Batched::new(bytes)).expect("open")+}++/// **The batch contract.** A cold screenful of tiles costs two waves — one per distinct cold+/// leaf, then one for the bodies — not two serial round trips per tile.+///+/// The `Batched` reader serves each range out of memory, so this measures the *structure* of+/// the fetch (how many waves, how many ranges per wave), not the network. The production+/// reader overlaps each wave in one multiplexed fetch; the per-tile path would cost+/// `2 * tiles.len()` serial reads here instead.+#[test]+fn a_batch_of_cold_tiles_costs_two_waves_not_two_round_trips_per_tile() {+ // Eight tiles across several leaves, so the leaf wave is real.+ let mut tiles: Vec<(u8, u64, u64, i16)> = Vec::new();+ for x in 0..4u64 {+ for y in 0..2u64 {+ tiles.push((3, x, y, (x * 2 + y) as i16));+ }+ }+ let options = Options { leaf_entry_capacity: 2, ..Options::default() };+ let a = open_batched(archive(&tiles, options));+ assert!(a.header.leaf_count > 1, "this test needs several leaves");+ // The open itself is a single read, before any batch runs.+ a.reader.inner.requests.borrow_mut().clear();+ a.reader.single_reads.set(0);+ a.reader.batch_waves.borrow_mut().clear();++ let want: Vec<(u8, u32, u32)> =+ tiles.iter().map(|(z, x, y, _)| (*z, *x as u32, *y as u32)).collect();+ let found = a.tiles(&want);+ assert_eq!(found.len(), want.len());+ for (slot, result) in found.iter().enumerate() {+ let (_, _, _, seed) = tiles[slot];+ assert_eq!(+ result.as_ref().expect("read").as_ref().expect("present"),+ &body_for(seed),+ "slot {slot}",+ );+ }+ // Two waves: the distinct cold leaves, then the bodies. No single reads at all —+ // the whole batch rides `read_batch`.+ assert_eq!(a.reader.single_reads.get(), 0, "no serial reads on the batch path");+ let waves = a.reader.batch_waves.borrow().clone();+ assert_eq!(waves.len(), 2, "one leaf wave and one body wave, got {waves:?}");+ assert_eq!(+ waves[1], want.len(),+ "every tile's body in the second wave, got {waves:?}",+ );+ // And the leaf wave fetches each distinct leaf exactly once, however many tiles share it.+ let distinct_leaves: std::collections::HashSet<u64> = a+ .reader+ .inner+ .requests+ .borrow()+ .iter()+ .take(waves[0])+ .map(|(o, _)| *o)+ .collect();+ assert_eq!(distinct_leaves.len(), waves[0], "one request per distinct leaf");+}++/// A warm batch — every leaf already cached — costs one wave: the bodies only.+#[test]+fn a_batch_of_warm_tiles_costs_one_body_wave() {+ let mut tiles: Vec<(u8, u64, u64, i16)> = Vec::new();+ for x in 0..4u64 {+ for y in 0..2u64 {+ tiles.push((3, x, y, (x * 2 + y) as i16));+ }+ }+ let options = Options { leaf_entry_capacity: 2, ..Options::default() };+ let a = open_batched(archive(&tiles, options));+ let want: Vec<(u8, u32, u32)> =+ tiles.iter().map(|(z, x, y, _)| (*z, *x as u32, *y as u32)).collect();+ // Warm the leaves with one tile each (single-tile path), then clear the counters.+ for (z, x, y) in &want {+ let _ = a.tile(*z, *x, *y).expect("warm");+ }+ a.reader.single_reads.set(0);+ a.reader.batch_waves.borrow_mut().clear();++ let found = a.tiles(&want);+ assert!(found.iter().all(|r| r.as_ref().expect("read").is_some()));+ let waves = a.reader.batch_waves.borrow().clone();+ assert_eq!(waves, vec![want.len()], "one body wave and nothing else, got {waves:?}");+ assert_eq!(a.reader.single_reads.get(), 0, "no serial reads on the batch path");+}++/// Absences and failures stay per-slot: a hole in the middle of a batch is `None` in its+/// slot, and the tiles around it still land.+#[test]+fn a_batch_keeps_absences_per_slot() {+ // z3 x0..4 y0..2, but only the even seeds are written — the odd tiles are holes.+ let mut tiles: Vec<(u8, u64, u64, i16)> = Vec::new();+ for x in 0..4u64 {+ for y in 0..2u64 {+ if (x + y) % 2 == 0 {+ tiles.push((3, x, y, (x * 2 + y) as i16));+ }+ }+ }+ let options = Options { leaf_entry_capacity: 8, ..Options::default() };+ let a = open_batched(archive(&tiles, options));+ a.reader.inner.requests.borrow_mut().clear();++ let want: Vec<(u8, u32, u32)> = (0..4u32)+ .flat_map(|x| (0..2u32).map(move |y| (3u8, x, y)))+ .collect();+ let found = a.tiles(&want);+ assert_eq!(found.len(), want.len());+ for (slot, result) in found.iter().enumerate() {+ let (x, y) = (want[slot].1, want[slot].2);+ if (x as u64 + y as u64) % 2 == 0 {+ let seed = (x * 2 + y) as i16;+ assert_eq!(+ result.as_ref().expect("read").as_ref().expect("present"),+ &body_for(seed),+ "slot {slot}",+ );+ } else {+ assert!(+ result.as_ref().expect("read").is_none(),+ "slot {slot} is a hole, not an error",+ );+ }+ }+}++/// A one-tile batch is the single-tile path with identical bytes and identical cost.+#[test]+fn a_single_tile_batch_reads_like_a_plain_read() {+ let a = open_batched(archive(&[(3, 1, 2, 42)], Options::default()));+ a.reader.inner.requests.borrow_mut().clear();+ let found = a.tiles(&[(3, 1, 2)]);+ assert_eq!(found.len(), 1);+ assert_eq!(+ found[0].as_ref().expect("read").as_ref().expect("present"),+ &body_for(42),+ );+ assert!(a.reader.batch_waves.borrow().is_empty(), "no wave for one tile");+}
library/tilecodec/src/main/rust/src/stream.rs
diff --git a/library/tilecodec/src/main/rust/src/stream.rs b/library/tilecodec/src/main/rust/src/stream.rsindex 352ee459d5..70fdd49091 100644--- a/library/tilecodec/src/main/rust/src/stream.rs+++ b/library/tilecodec/src/main/rust/src/stream.rs@@ -26,6 +26,27 @@ use crate::proto::{err, Result}; /// it. A caller needing an exact count checks. pub trait RangeReader { fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>>;++ /// Several ranges at once, answered in order with one slot per request.+ ///+ /// The default serves each range through [`read`](Self::read) in turn, which is+ /// exact for files and memory. Readers over a network override this to overlap the+ /// round trips — one multiplexed fetch for the whole batch instead of one per range —+ /// which is what makes a cold screenful cost waves rather than serial round trips.+ /// Failures stay per-slot: a failed range is an error for that slot, never a+ /// poisoned batch.+ fn read_batch(&self, requests: &[(u64, u32)]) -> Vec<Result<Vec<u8>>> {+ requests.iter().map(|&(offset, length)| self.read(offset, length)).collect()+ }++ /// Order recently written ranges on disk, batched.+ ///+ /// The default is a no-op (files and memory have nothing to flush). Readers over a+ /// disk cache override this to durability-flush everything written since the last call+ /// in one pass — so a fetch wave costs one flush pass, not one fsync per range. Called+ /// by the worker after each wave; best-effort like the cache itself (a missed flush+ /// only risks a re-fetch, never correctness).+ fn flush_pending(&self) {} } /// The spec advises keeping the root directory inside the first 16 KB so a cold open