From 61219c2eb89298bf66ac22171a633c4d00034fda Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 02:33:56 -0600 Subject: [PATCH 1/6] perf(render): keep a streamed layer's view with the geometry drawn from it (#1065) A Shapefile read in place was read, parsed and projected again for every frame, even of the same view. The view a frame reads is now kept on the source with the rows' projected and display geometry; a frame of a view inside it (the same view again, a short pan, a zoom in, a restyle) draws from it without reading. The view is read a quarter of its size wider on each side so that a short pan still finds it, unless a view as coarse was too large to keep. A kept view is for the projection and datum grids it was drawn with, holds at most 64 MB and no more than the source's share of the map's view memory leaves beside its interaction rows, and is let go when that share shrinks. Geometry a frame makes from it (a finer level of detail) is kept with it. --- crates/map/src/lib.rs | 18 ++++ crates/map/src/source.rs | 46 ++++++++ crates/map/src/source/render_view.rs | 156 +++++++++++++++++++++++++++ crates/render/src/lib.rs | 89 ++++++++++++--- crates/render/src/stream_tests.rs | 71 +++++++++++- 5 files changed, 367 insertions(+), 13 deletions(-) create mode 100644 crates/map/src/source/render_view.rs diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 6068463f82..2347761acd 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -1529,6 +1529,18 @@ impl Layer { fits } + /// Takes the rows of `kept`, a chunk of a streamed layer drawn before (a copy of this layer + /// with other rows), and the geometry drawing made of them: projected, and thinned for + /// display. Sharing them costs a pointer; this layer keeps its own look. What drawing makes + /// that `kept` lacks is made from the rows as usual. + pub fn draw_rows_of(&mut self, kept: &Layer) { + self.clear_cache(); + self.dataset.features = kept.dataset.features.clone(); + self.dataset.held_in = kept.dataset.held_in; + self.geometry_rev = kept.geometry_rev; + self.adopt_cache(kept); + } + /// Whether the projected geometry cache is filled for a projection, from the layer's current /// rows and its coordinate system ([`Dataset::coord_crs`]). pub fn is_cached(&self, key: &str) -> bool { @@ -3087,6 +3099,12 @@ impl Map { src.saved_selection = selected; } } + // A view kept for its frames fits in what its share leaves beside the rows it + // holds, hidden or not: a share shrunk by another streamed layer lets it go. + let room = bytes.saturating_sub(layer.view_cache_bytes()); + if let Some(src) = &layer.source { + src.trim_kept_view(room); + } } } for l in self.layers.iter_mut().filter(|l| l.is_streamed() && l.visible && l.in_scale_range(scale) && !held.contains(&l.id)) { diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index a952b4f266..4cf3090372 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -19,6 +19,8 @@ use rustgis_geom::Extent; use serde::{Deserialize, Serialize}; mod render_lod; +mod render_view; +pub use render_view::KEPT_VIEW_BYTES; mod window; pub(crate) use window::Query; @@ -178,6 +180,9 @@ pub struct SourceLayer { /// Whole-source thinning decisions shared by render snapshots, independent of view rows. #[serde(skip)] render_lod: Arc>, + /// The last view's rows and drawn geometry, shared by render snapshots ([`render_view`]). + #[serde(skip)] + render_view: Arc>, #[serde(skip)] pending: Option>, /// Projection used for this disposable window's geometry cache. @@ -1203,6 +1208,44 @@ impl SourceLayer { cache.get_or_try_insert(handle, projection, level, calculate) } + /// The chunks a frame drew from the source's last view, with their projected and display + /// geometry, when that view was read for a longitude/latitude box holding `near`, drawn for + /// `key` (the projection and datum grids, as the renderer names them) and holding at most + /// `room` bytes (#1065). They hold rows only: the drawing takes the layer's look from the + /// layer, its rows and geometry from them ([`crate::Layer::draw_rows_of`]). + pub fn kept_view(&self, key: &str, near: &Extent, room: usize) -> Option>> { + let handle = self.handle.as_ref()?; + self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(handle, key, near, room) + } + + /// Whether a frame at resolution `res` (map units a pixel) should read a view wider than it + /// draws, to keep it for the frames after: not after a view as coarse or coarser was too large + /// to keep. + pub fn view_worth_keeping(&self, key: &str, res: f64) -> bool { + let Some(handle) = &self.handle else { return false }; + self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).worth_keeping(handle, key, res) + } + + /// Keeps the chunks a frame at resolution `res` drew from a view read for `read`, with the + /// bytes they hold, in place of the last view kept; `None` says they came to more than may be + /// kept. + pub fn keep_view(&self, key: &str, read: Extent, res: f64, chunks: Option<(Vec, usize)>) { + let Some(handle) = &self.handle else { return }; + self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).put(handle, key, read, res, chunks); + } + + /// Lets the kept view go when it holds more than `room` bytes. + pub fn trim_kept_view(&self, room: usize) { + self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).trim(room); + } + + /// Puts the kept chunks drawn again, with the geometry drawing made of them, in place of + /// `drawn`, the ones [`SourceLayer::kept_view`] gave, while those are still what is kept. + pub fn refresh_kept_view(&self, key: &str, drawn: &Arc>, chunks: Vec, bytes: usize) { + let Some(handle) = &self.handle else { return }; + self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).refresh(handle, key, drawn, chunks, bytes); + } + /// Retained interaction bytes assigned by the map, or the standalone default. pub fn budget(&self) -> usize { if self.byte_budget == 0 { VIEW_BYTES } else { self.byte_budget } @@ -1734,6 +1777,7 @@ impl SourceLayer { pub fn detach_read(&mut self) { self.pending = None; self.render_lod = Default::default(); + self.render_view = Default::default(); } /// Whether `other` (a copy of this one) reads the same source the same way: the same file and @@ -1757,6 +1801,7 @@ impl SourceLayer { /// Forgets the window, so the next view reads again (after the source changes). pub fn reset(&mut self) { self.render_lod = Default::default(); + self.render_view = Default::default(); self.reset_window(); } @@ -2021,6 +2066,7 @@ impl SourceLayer { handle: _, window: _, render_lod: _, + render_view: _, pending: _, projection: _, ready_cache: _, diff --git a/crates/map/src/source/render_view.rs b/crates/map/src/source/render_view.rs new file mode 100644 index 0000000000..95f38b5178 --- /dev/null +++ b/crates/map/src/source/render_view.rs @@ -0,0 +1,156 @@ +//! The features a streamed layer's last view read and the geometry its drawing made of them +//! (projected, and thinned for display), kept so that a frame of a view inside that one draws +//! without reading, parsing or projecting them again (#1065). Shared by render snapshots, like +//! the thinning decisions ([`super::render_lod`]), and bounded by [`KEPT_VIEW_BYTES`] and the +//! room the source's share of the map's view memory leaves. +use rustgis_data::source::FeatureSource; +use rustgis_geom::Extent; +use std::sync::{Arc, Weak}; + +use crate::Layer; + +/// The most a kept view holds: its rows and the geometry drawn from them +/// ([`Layer::view_cache_bytes`]). A view with more, or with more than the source's share of the +/// map's view memory leaves beside its interaction rows, is drawn without being kept. +pub const KEPT_VIEW_BYTES: usize = crate::lod::CACHE_BYTES; + +#[derive(Default)] +pub(super) struct KeptView { + source: Option>, + /// What its geometry was drawn for: the projection ([`crate::Projection::code`]) and the + /// datum grids there were then, as the renderer names them. + key: String, + /// The longitude/latitude box it was read for: every feature whose box meets it. + read: Extent, + /// The chunks drawn from it in turn, in the source's order. + chunks: Arc>, + /// What the chunks hold ([`Layer::view_cache_bytes`]). + bytes: usize, + /// The coarsest resolution (map units a pixel) a view's read was found too large to keep at, + /// for this key: views as coarse or coarser read only what they draw, and keep nothing. + too_large_at: Option, +} + +impl KeptView { + /// Forgets everything kept for another source or key. + fn follow(&mut self, source: &Arc, key: &str) { + let same = self.source.as_ref().and_then(Weak::upgrade).is_some_and(|old| Arc::ptr_eq(&old, source)); + if !same || self.key != key { + *self = KeptView { source: Some(Arc::downgrade(source)), key: key.into(), ..KeptView::default() }; + } + } + + /// Forgets the chunks, keeping what was learnt of sizes. + fn drop_chunks(&mut self) { + self.read = Extent::EMPTY; + self.chunks = Arc::default(); + self.bytes = 0; + } + + /// The kept chunks, when they were read for a box holding `near` and hold at most `room` + /// bytes; ones holding more (the source's share shrank) are let go. + pub(super) fn get(&mut self, source: &Arc, key: &str, near: &Extent, room: usize) -> Option>> { + self.follow(source, key); + if self.bytes > room { + self.drop_chunks(); + } + let r = &self.read; + let holds = + !self.chunks.is_empty() && r.min_x <= near.min_x && r.min_y <= near.min_y && r.max_x >= near.max_x && r.max_y >= near.max_y; + holds.then(|| Arc::clone(&self.chunks)) + } + + /// Lets the chunks go when they hold more than `room` bytes. + pub(super) fn trim(&mut self, room: usize) { + if self.bytes > room { + self.drop_chunks(); + } + } + + /// Whether a view at resolution `res` is worth reading wider than it draws to keep: not + /// when one as coarse or coarser was already too large to keep. + pub(super) fn worth_keeping(&mut self, source: &Arc, key: &str, res: f64) -> bool { + self.follow(source, key); + self.too_large_at.is_none_or(|at| res < at) + } + + /// Keeps `chunks` of `bytes`, read for `read`, in place of what was kept; `None` when they + /// came to more than may be kept at resolution `res`, which is remembered. + pub(super) fn put(&mut self, source: &Arc, key: &str, read: Extent, res: f64, chunks: Option<(Vec, usize)>) { + self.follow(source, key); + match chunks { + Some((chunks, bytes)) => { + self.read = read; + self.chunks = Arc::new(chunks); + self.bytes = bytes; + } + None => { + self.drop_chunks(); + self.too_large_at = Some(self.too_large_at.map_or(res, |at| at.min(res))); + } + } + } + + /// Puts `chunks` of `bytes` (the kept ones drawn again, with the geometry that drawing made, + /// a finer level of detail say) in place of `drawn`, when those are still what is kept; + /// another source or key kept since is left as it is. + pub(super) fn refresh( + &mut self, + source: &Arc, + key: &str, + drawn: &Arc>, + chunks: Vec, + bytes: usize, + ) { + let same = self.source.as_ref().and_then(Weak::upgrade).is_some_and(|old| Arc::ptr_eq(&old, source)); + if same && self.key == key && Arc::ptr_eq(&self.chunks, drawn) { + self.chunks = Arc::new(chunks); + self.bytes = bytes; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rustgis_data::source::{Batch, Request, SourceInfo}; + + struct Empty(SourceInfo); + impl FeatureSource for Empty { + fn info(&self) -> &SourceInfo { + &self.0 + } + fn read(&self, _: &Request) -> rustgis_data::Result { + Ok(Batch::default()) + } + } + + /// A view too large to keep stops wider reads at its resolution and coarser ones, not at + /// finer ones; another projection or source starts afresh. + #[test] + fn a_view_too_large_to_keep_stops_wide_reads_as_coarse_or_coarser() { + let info = SourceInfo { + name: "s".into(), + format: "test", + geometry_type: rustgis_data::GeometryType::Point, + fields: Vec::new(), + extent: Extent::EMPTY, + count: Some(0), + crs: "EPSG:4326".into(), + indexed: true, + notes: Vec::new(), + zm_dropped: false, + }; + let source: Arc = Arc::new(Empty(info.clone())); + let mut kept = KeptView::default(); + assert!(kept.worth_keeping(&source, "3857", 100.0)); + kept.put(&source, "3857", Extent::new(0.0, 0.0, 1.0, 1.0), 100.0, None); + assert!(!kept.worth_keeping(&source, "3857", 100.0)); + assert!(!kept.worth_keeping(&source, "3857", 200.0)); + assert!(kept.worth_keeping(&source, "3857", 50.0)); + assert!(kept.get(&source, "3857", &Extent::new(0.2, 0.2, 0.4, 0.4), usize::MAX).is_none(), "nothing kept"); + assert!(kept.worth_keeping(&source, "robinson", 100.0), "another projection"); + let other: Arc = Arc::new(Empty(info)); + assert!(kept.worth_keeping(&other, "3857", 100.0), "another source"); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 95b11ad703..3ba5613899 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -405,6 +405,11 @@ pub const MAX_SIDE: u32 = 8192; /// How far past each side of the view (a fraction of its size) features are still drawn. pub const CULL_MARGIN: f64 = 0.05; +/// How far past each side of the view (a fraction of its size) a streamed layer's view is read +/// when it is kept for the frames after ([`rustgis_map::source::SourceLayer::kept_view`]): a pan +/// of a fifth of the view still draws from it. +const KEEP_MARGIN: f64 = 0.25; + /// The share of a streamed layer's extent a view's box covers past which the whole layer is read /// in file order rather than through its index ([`covers_most`]). const READ_ALL_OVER: f64 = 0.5; @@ -6403,6 +6408,7 @@ fn render_frame( // which fall back to the CPU. And a box over most of the layer reads it all, in file // order: asking the index which records nearly all of them are costs more than // reading the few left over. + let partial = |e: &Extent| !covers_most(e, &source.info().extent); let near = (globe.is_none() && !gpu && matches!(flat, rustgis_map::projection::Flat::Mercator) @@ -6413,24 +6419,83 @@ fn render_frame( && draws_in_view_only(&chunk, !display.paused, shore.is_some())) .then(|| lonlat_box(&flat, &ctx.cull)) .flatten() - .filter(|e| !covers_most(e, &source.info().extent)); + .filter(partial); // The source's long loops that only look at Cancel see the frame's stop too. let _stop = cancel::current().map(rustgis_data::progress::also_stop_when); - let result = visit_within(source.as_ref(), near, &mut |features| { - // A frame no longer wanted reads no further (see `cancel`). - if cancel::requested() { - return Err(rustgis_data::DataError::Cancelled); + // A view read this way is kept with the geometry drawn from it, for the frames of the + // views inside it: the same view again, a short pan, a zoom in, a restyle, an export. + // It is read a margin wider than it draws, so a short pan still finds it, unless a view + // this coarse was too large to keep. It is kept for the projection and the datum grids + // the frame drew with, within what the source's share of the map's view memory leaves + // beside its interaction rows. + let res = view.camera.res; + let owner = layer.source.as_ref(); + let grids = rustgis_data::raster::crs::grid_generation(); + let kept_key = format!("{key} {grids}"); + let room = owner.map_or(0, |o| o.budget().saturating_sub(layer.view_cache_bytes()).min(rustgis_map::source::KEPT_VIEW_BYTES)); + let kept = near.and_then(|n| owner?.kept_view(&kept_key, &n, room)); + let wide = cull_extent(view, KEEP_MARGIN); + let keep = (near.is_some() + && kept.is_none() + && within_mercator_lats(&wide) + && owner.is_some_and(|o| o.view_worth_keeping(&kept_key, res))) + .then(|| lonlat_box(&flat, &wide)) + .flatten() + .filter(partial); + let mut keeping: Option<(Vec, usize)> = (keep.is_some() || kept.is_some()).then(|| (Vec::new(), 0)); + let mut draw_rows = |chunk: &mut rustgis_map::Layer| -> rustgis_data::Result<()> { + chunk.selection = chunk + .dataset + .features + .iter() + .enumerate() + .filter_map(|(r, f)| selected_order.contains_key(&f.id).then_some(r)) + .collect(); + draw_chunk(chunk)?; + if let Some((chunks, bytes)) = &mut keeping { + *bytes = bytes.saturating_add(chunk.view_cache_bytes()); + if *bytes <= room { + chunks.push(chunk.clone()); + } else { + chunks.clear(); + } } chunk.clear_cache(); - chunk.selection = - features.iter().enumerate().filter_map(|(r, f)| selected_order.contains_key(&f.id).then_some(r)).collect(); - chunk.dataset.features = features.into(); - chunk.touch_geometry(); - draw_chunk(&mut chunk)?; - chunk.clear_cache(); chunk.dataset.features = Vec::new().into(); Ok(()) - }); + }; + let result = match &kept { + Some(kept) => kept.iter().try_for_each(|rows| { + // A frame no longer wanted draws no further (see `cancel`). + if cancel::requested() { + return Err(rustgis_data::DataError::Cancelled); + } + chunk.draw_rows_of(rows); + draw_rows(&mut chunk) + }), + None => visit_within(source.as_ref(), keep.or(near), &mut |features| { + // A frame no longer wanted reads no further (see `cancel`). + if cancel::requested() { + return Err(rustgis_data::DataError::Cancelled); + } + chunk.clear_cache(); + chunk.dataset.features = features.into(); + chunk.touch_geometry(); + draw_rows(&mut chunk) + }) + .map(|_| ()), + }; + // Kept only when drawn whole, for the datum grids there still are. + if let (Ok(()), Some(owner), Some((chunks, bytes))) = (&result, owner, keeping) + && rustgis_data::raster::crs::grid_generation() == grids + { + let fits = bytes <= room; + match (keep, &kept) { + (Some(read), _) => owner.keep_view(&kept_key, read, res, fits.then_some((chunks, bytes))), + (None, Some(drawn)) if fits => owner.refresh_kept_view(&kept_key, drawn, chunks, bytes), + _ => {} + } + } // Declined (`pictureless`): no frame, whatever the source made of the stop. if declined { return None; diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 309d2b0830..9abb7e7b58 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -1853,7 +1853,7 @@ fn a_streamed_layer_reads_only_the_view_when_nothing_it_draws_reaches_in() { if near { let e = drawn.unwrap_or_else(|| panic!("case {n}: the whole source was read")); let read = features.iter().filter(|f| f.geometry.as_ref().is_some_and(|g| g.extent().intersects(&e))).count(); - assert!(read * 10 < total, "case {n}, {view:?}: {read} of {total} features read for a view of a few"); + assert!(read * 5 < total, "case {n}, {view:?}: {read} of {total} features read for a view of a few"); } else { assert_eq!(drawn, None, "case {n}: a layer reaching in from beyond the view reads everything"); } @@ -1898,3 +1898,72 @@ fn a_streamed_layer_reads_only_the_view_when_nothing_it_draws_reaches_in() { assert_eq!(asked.lock().unwrap().last().copied().flatten(), None, "all by area {all_by_area}: reads everything"); } } + +/// A streamed layer's view is kept with the geometry drawn from it: the same view again, a short +/// pan, a zoom in and a restyle draw from it without reading the source, as the layer held in +/// memory draws; a pan out of it or the source reset reads again (#1065). +#[test] +fn a_kept_view_draws_the_frames_inside_it_without_reading_the_source() { + use std::sync::{Arc, Mutex}; + let mut squares = Dataset::new("squares", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); + for i in 0..40 { + for j in 0..40 { + let (x, y) = (i as f64 - 20.0, j as f64 - 20.0); + let ring = + vec![Coord::new(x, y), Coord::new(x + 0.6, y), Coord::new(x + 0.6, y + 0.6), Coord::new(x, y + 0.6), Coord::new(x, y)]; + squares.push(Some(Geometry::Polygon(vec![vec![ring]])), vec![Value::Text(format!("s{i}-{j}"))]); + } + } + let mut base = Map::new("kept"); + base.basemap = rustgis_map::Basemap::Blank; + base.add_dataset(squares.clone()); + let asked = Arc::new(Mutex::new(Vec::new())); + let mut actual = base.clone(); + let mut layer = streamed(&base.layers[0], usize::MAX); + let info = layer.source.as_ref().unwrap().info().unwrap().clone(); + layer.source = Some(SourceLayer::from_path( + "kept.shp", + None, + Box::new(Near { chunks: Chunks { info, ds: squares, size: usize::MAX }, asked: asked.clone(), all_by_area: true }), + )); + actual.layers[0] = layer; + let camera = Camera::new(rustgis_geom::lonlat_to_merc(Coord::new(0.3, 0.3)), 2_000.0); + let mut view = View { width: 320.0, height: 240.0, pixels_per_point: 1.0, camera, sky: false }; + // What drawing `view` reads from the source: the boxes asked for, none for a kept view. + let frame = |base: &mut Map, actual: &mut Map, view: &View, what: &str| -> Vec { + let before = asked.lock().unwrap().len(); + let expected = render(&mut base.clone(), view).unwrap(); + let Some(RenderOutput::Cpu(got)) = render_with_backend(&mut actual.clone(), view, true, Backend::Cpu) else { + panic!("{what}: a complete frame"); + }; + assert!(got.pixmap.data() == expected.pixmap.data(), "{what}: the pixels changed"); + let asked = asked.lock().unwrap(); + // Each read: whether by area. A whole read is the thinning decision's, made once a + // projection and level of detail, or a frame reading everything. + asked[before..].iter().map(Option::is_some).collect() + }; + assert_eq!(frame(&mut base, &mut actual, &view, "first"), [false, true], "the first frame reads the view"); + assert_eq!(frame(&mut base, &mut actual, &view, "again"), [false; 0], "the same view draws from the kept one"); + view.camera.center.x += view.width * view.camera.res * 0.1; + assert_eq!(frame(&mut base, &mut actual, &view, "short pan"), [false; 0], "a short pan draws from the kept view"); + view.camera.res /= 2.0; + assert_eq!(frame(&mut base, &mut actual, &view, "zoom in"), [false], "a zoom in decides its level and draws from the kept view"); + for map in [&mut base, &mut actual] { + map.layers[0].renderer = + Renderer::Single(Symbol { fill: Rgba::new(30, 160, 90, 200), ..Symbol::default_for(GeometryType::Polygon, map.layers[0].id) }); + } + assert_eq!(frame(&mut base, &mut actual, &view, "restyle"), [false; 0], "a restyled layer draws from the kept view"); + view.camera.center.x += view.width * view.camera.res * 3.0; + assert_eq!(frame(&mut base, &mut actual, &view, "far pan"), [true], "a pan out of the kept view reads again"); + // Robinson reads everything (no box), and leaves the Web Mercator view kept. + for map in [&mut base, &mut actual] { + map.projection = rustgis_map::Projection::Custom("robinson".into()); + } + assert_eq!(frame(&mut base, &mut actual, &view, "robinson"), [false, false], "another projection decides and reads everything"); + for map in [&mut base, &mut actual] { + map.projection = rustgis_map::Projection::default(); + } + assert_eq!(frame(&mut base, &mut actual, &view, "back"), [false; 0], "the Web Mercator view is still kept"); + actual.layers[0].source.as_mut().unwrap().reset(); + assert_eq!(frame(&mut base, &mut actual, &view, "reset"), [false, true], "a reset source reads again"); +} From e0e6753954080b9f84b7b2bbda6c0b0ba8241119 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 02:41:39 -0600 Subject: [PATCH 2/6] fix(map): trim a kept view after the interaction rows are read (#1065) --- crates/map/src/lib.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 2347761acd..29b2bca0a8 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -3099,17 +3099,19 @@ impl Map { src.saved_selection = selected; } } - // A view kept for its frames fits in what its share leaves beside the rows it - // holds, hidden or not: a share shrunk by another streamed layer lets it go. - let room = bytes.saturating_sub(layer.view_cache_bytes()); - if let Some(src) = &layer.source { - src.trim_kept_view(room); - } } } for l in self.layers.iter_mut().filter(|l| l.is_streamed() && l.visible && l.in_scale_range(scale) && !held.contains(&l.id)) { pending |= l.sync_source_with(view, block, env); } + // A view kept for its frames fits in what its share leaves beside the rows it holds now, + // hidden or not: a share shrunk by another streamed layer, or a larger view installed, + // lets it go. + for l in &self.layers { + if let Some(src) = &l.source { + src.trim_kept_view(bytes.saturating_sub(l.view_cache_bytes())); + } + } pending } From 8b178babed51429a9d423b01fe47488c1e032679 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 05:43:49 -0600 Subject: [PATCH 3/6] test(map): build the kept view test's source info with the notes type main now has --- crates/map/src/source/render_view.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/map/src/source/render_view.rs b/crates/map/src/source/render_view.rs index 95f38b5178..6e2509b20b 100644 --- a/crates/map/src/source/render_view.rs +++ b/crates/map/src/source/render_view.rs @@ -138,7 +138,7 @@ mod tests { count: Some(0), crs: "EPSG:4326".into(), indexed: true, - notes: Vec::new(), + notes: Default::default(), zm_dropped: false, }; let source: Arc = Arc::new(Empty(info.clone())); From c929a12b27c31da80192134bb80ee8c15a00a1e9 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 06:45:42 -0600 Subject: [PATCH 4/6] fix(render): draw from a kept view only while its Shapefile is as it was opened (#1065) A frame inside a kept view didn't look at the source, so a Shapefile moved away or written again went on drawing as it was. Before drawing from a kept view, the frame now opens both files, as a read does, and compares their sizes and modification times with those at opening: a file gone fails as a read of it would, and one changed reads the view again. The selection takes the rows' ids through their accessors (one fewer direct row use). --- crates/data/src/source/mod.rs | 6 ++++++ crates/data/src/source/shp.rs | 14 +++++++++++++- crates/data/src/source/shp/tests.rs | 20 ++++++++++++++++++++ crates/render/src/lib.rs | 19 ++++++++++++++++--- crates/render/src/stream_tests.rs | 3 +++ xtask/row-uses.txt | 2 +- 6 files changed, 59 insertions(+), 5 deletions(-) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 946d58cf11..20c37512ec 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -389,6 +389,12 @@ pub trait FeatureSource: Send + Sync { fn finds_all_by_area(&self) -> bool { false } + /// Whether the source is as it was when opened, judged cheaply (its files' sizes and + /// modification times), for what was read from it and kept beside it: `Ok(false)` when it + /// changed or the source can't say, and the error a read would give when it can't be read. + fn same_as_opened(&self) -> Result { + Ok(false) + } /// Whether a complete bounded traversal for a geographic extent is available. This also /// covers readers whose view and whole-export paths still use their existing sample or /// whole-read contracts. diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 03b2f9282e..489144aa42 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -74,6 +74,9 @@ pub struct ShpSource { /// trust: [`BOXES_UNKNOWN`] until a whole read has looked, then [`BOXES_HOLD`] or /// [`BOXES_DONT`]. boxes: AtomicU8, + /// The `.shp`'s and the `.dbf`'s sizes and modification times as opened + /// ([`FeatureSource::same_as_opened`]). + stamps: [Option<(u64, u128)>; 2], } /// Not yet looked at ([`ShpSource::boxes`]). @@ -227,7 +230,8 @@ impl ShpSource { } // Points too: each record's own type is read, whatever the header says. let boxes = AtomicU8::new(BOXES_UNKNOWN); - Ok(ShpSource { info, shp: path.to_path_buf(), dbf, index, table, encoding, reproject, boxes }) + let stamps = [super::external::stamp(path).ok(), super::external::stamp(&dbf).ok()]; + Ok(ShpSource { info, shp: path.to_path_buf(), dbf, index, table, encoding, reproject, boxes, stamps }) } } @@ -379,6 +383,14 @@ impl FeatureSource for ShpSource { fn finds_all_by_area(&self) -> bool { self.index.unboxed == 0 && self.boxes.load(Relaxed) == BOXES_HOLD } + /// Both files opened as a read opens them, so one gone gives a read's error, then their sizes + /// and modification times compared with those at opening. + fn same_as_opened(&self) -> Result { + drop(crate::provenance::open(&self.shp)?); + drop(crate::provenance::open(&self.dbf)?); + let now = [super::external::stamp(&self.shp).ok(), super::external::stamp(&self.dbf).ok()]; + Ok(self.stamps.iter().all(Option::is_some) && now == self.stamps) + } /// Visits located shapes in a spatial request; geometry-less rows belong only to whole reads. /// Counts scanned records and checks Cancel before filtering them. fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index f652fe48ef..46883a8e11 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -888,3 +888,23 @@ fn reads_by_area_find_every_shape_once_a_whole_read_has_seen_the_boxes_hold() { assert!(s.finds_all_by_area(), "each point is its own box"); }); } + +/// A Shapefile says whether it is as it was opened (#1065): yes until it is written again, and a +/// read's error once it is gone. +#[test] +fn a_shapefile_says_whether_it_is_as_it_was_opened() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("pts.shp"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![]); + ds.push(Some(Geometry::Point(Coord::new(1.0, 1.0))), vec![]); + write_shapefile(&ds, &path); + cache::with_index_dir(tmp.path().join("cache"), || { + let s = ShpSource::open_path(&path, "pts").unwrap(); + assert!(s.same_as_opened().unwrap(), "as opened"); + ds.push(Some(Geometry::Point(Coord::new(2.0, 2.0))), vec![]); + write_shapefile(&ds, &path); + assert!(!s.same_as_opened().unwrap(), "written again"); + std::fs::remove_file(&path).unwrap(); + assert!(s.same_as_opened().is_err(), "gone"); + }); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 3ba5613899..3cb4d38779 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6429,11 +6429,24 @@ fn render_frame( // the frame drew with, within what the source's share of the map's view memory leaves // beside its interaction rows. let res = view.camera.res; + // Only while the source is as it was opened: a file changed since reads again, and + // one gone fails as a read of it would. + let unchanged = match near.map(|_| source.same_as_opened()) { + Some(Err(e)) => { + if let Some(s) = &mut layer.source { + s.error = Some(e.to_string()); + } + *failed_source = Some(layer.instance_id()); + return None; + } + Some(Ok(same)) => same, + None => false, + }; let owner = layer.source.as_ref(); let grids = rustgis_data::raster::crs::grid_generation(); let kept_key = format!("{key} {grids}"); let room = owner.map_or(0, |o| o.budget().saturating_sub(layer.view_cache_bytes()).min(rustgis_map::source::KEPT_VIEW_BYTES)); - let kept = near.and_then(|n| owner?.kept_view(&kept_key, &n, room)); + let kept = near.filter(|_| unchanged).and_then(|n| owner?.kept_view(&kept_key, &n, room)); let wide = cull_extent(view, KEEP_MARGIN); let keep = (near.is_some() && kept.is_none() @@ -6447,9 +6460,9 @@ fn render_frame( chunk.selection = chunk .dataset .features - .iter() + .rows() .enumerate() - .filter_map(|(r, f)| selected_order.contains_key(&f.id).then_some(r)) + .filter_map(|(r, row)| selected_order.contains_key(&row.id()).then_some(r)) .collect(); draw_chunk(chunk)?; if let Some((chunks, bytes)) = &mut keeping { diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 9abb7e7b58..00526d30d3 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -1761,6 +1761,9 @@ impl FeatureSource for Near { fn finds_all_by_area(&self) -> bool { self.all_by_area } + fn same_as_opened(&self) -> rustgis_data::Result { + Ok(true) + } /// Keeps `extent`, then gives the features whose boxes meet it (all of them for `None`), in /// file order. fn visit_chunks( diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 52f6c8cedc..effca51f21 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 781 +count = 780 From e11a11500d31b673bfb1c34849b8fd39d11141de Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 07:31:43 -0600 Subject: [PATCH 5/6] fix(render): keep a view only from a Shapefile as it was opened, stamped before it is read (#1065) A changed source no longer reads a wider view to keep it, as it can't be drawn from. The stamps are taken before the files are read, and hold the modification time as it is with, on Unix, the file's identity and change time, so a write of the same size within the clock's step is seen. No modification time, no reuse. --- crates/data/src/source/shp.rs | 39 ++++++++++++++++++++++++----- crates/data/src/source/shp/tests.rs | 13 ++++++++-- crates/render/src/lib.rs | 1 + crates/render/src/stream_tests.rs | 1 + 4 files changed, 46 insertions(+), 8 deletions(-) diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 489144aa42..eb857cc1fa 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -74,9 +74,35 @@ pub struct ShpSource { /// trust: [`BOXES_UNKNOWN`] until a whole read has looked, then [`BOXES_HOLD`] or /// [`BOXES_DONT`]. boxes: AtomicU8, - /// The `.shp`'s and the `.dbf`'s sizes and modification times as opened + /// The `.shp`'s and the `.dbf`'s versions as opened /// ([`FeatureSource::same_as_opened`]). - stamps: [Option<(u64, u128)>; 2], + stamps: [Option; 2], +} + +/// What a file's metadata says of its version ([`FeatureSource::same_as_opened`]): its size and +/// modification time and, on Unix, its identity and change time, which a write of the same size +/// within the clock's step still moves. `None` without a modification time: then no copy of what +/// was read is trusted. +#[derive(PartialEq, Eq)] +struct Stamp { + len: u64, + modified: std::time::SystemTime, + #[cfg(unix)] + identity_and_change: (u64, u64, i64, i64), +} + +impl Stamp { + fn of(path: &Path) -> Option { + #[cfg(unix)] + use std::os::unix::fs::MetadataExt; + let m = std::fs::metadata(path).ok()?; + Some(Stamp { + len: m.len(), + modified: m.modified().ok()?, + #[cfg(unix)] + identity_and_change: (m.dev(), m.ino(), m.ctime(), m.ctime_nsec()), + }) + } } /// Not yet looked at ([`ShpSource::boxes`]). @@ -116,6 +142,8 @@ impl ShpSource { if !dbf.is_file() { return Err(bad(format!("{} is missing", dbf.display()))); } + // Taken before anything is read, so a file written while it opens is seen as changed. + let stamps = [Stamp::of(path), Stamp::of(&dbf)]; let mut notes = Vec::new(); let table = read_table(&dbf)?; let cpg = crate::dbf::read_cpg(path, &mut notes); @@ -230,7 +258,6 @@ impl ShpSource { } // Points too: each record's own type is read, whatever the header says. let boxes = AtomicU8::new(BOXES_UNKNOWN); - let stamps = [super::external::stamp(path).ok(), super::external::stamp(&dbf).ok()]; Ok(ShpSource { info, shp: path.to_path_buf(), dbf, index, table, encoding, reproject, boxes, stamps }) } } @@ -383,12 +410,12 @@ impl FeatureSource for ShpSource { fn finds_all_by_area(&self) -> bool { self.index.unboxed == 0 && self.boxes.load(Relaxed) == BOXES_HOLD } - /// Both files opened as a read opens them, so one gone gives a read's error, then their sizes - /// and modification times compared with those at opening. + /// Both files opened as a read opens them, so one gone gives a read's error, then their + /// versions ([`Stamp`]) compared with those at opening. fn same_as_opened(&self) -> Result { drop(crate::provenance::open(&self.shp)?); drop(crate::provenance::open(&self.dbf)?); - let now = [super::external::stamp(&self.shp).ok(), super::external::stamp(&self.dbf).ok()]; + let now = [Stamp::of(&self.shp), Stamp::of(&self.dbf)]; Ok(self.stamps.iter().all(Option::is_some) && now == self.stamps) } /// Visits located shapes in a spatial request; geometry-less rows belong only to whole reads. diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index 46883a8e11..29e7504e95 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -889,8 +889,8 @@ fn reads_by_area_find_every_shape_once_a_whole_read_has_seen_the_boxes_hold() { }); } -/// A Shapefile says whether it is as it was opened (#1065): yes until it is written again, and a -/// read's error once it is gone. +/// A Shapefile says whether it is as it was opened (#1065): yes until it is written again (on Unix +/// at the same size and time too), and a read's error once it is gone. #[test] fn a_shapefile_says_whether_it_is_as_it_was_opened() { let tmp = tempfile::tempdir().unwrap(); @@ -901,6 +901,15 @@ fn a_shapefile_says_whether_it_is_as_it_was_opened() { cache::with_index_dir(tmp.path().join("cache"), || { let s = ShpSource::open_path(&path, "pts").unwrap(); assert!(s.same_as_opened().unwrap(), "as opened"); + // The same size, its time set back: the change time still moves. + let dbf = path.with_extension("dbf"); + let modified = std::fs::metadata(&dbf).unwrap().modified().unwrap(); + let bytes = std::fs::read(&dbf).unwrap(); + std::fs::write(&dbf, &bytes).unwrap(); + std::fs::File::options().write(true).open(&dbf).unwrap().set_modified(modified).unwrap(); + #[cfg(unix)] + assert!(!s.same_as_opened().unwrap(), "written again at the same size and time"); + let s = ShpSource::open_path(&path, "pts").unwrap(); ds.push(Some(Geometry::Point(Coord::new(2.0, 2.0))), vec![]); write_shapefile(&ds, &path); assert!(!s.same_as_opened().unwrap(), "written again"); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 3cb4d38779..8a7c18634b 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6449,6 +6449,7 @@ fn render_frame( let kept = near.filter(|_| unchanged).and_then(|n| owner?.kept_view(&kept_key, &n, room)); let wide = cull_extent(view, KEEP_MARGIN); let keep = (near.is_some() + && unchanged && kept.is_none() && within_mercator_lats(&wide) && owner.is_some_and(|o| o.view_worth_keeping(&kept_key, res))) diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 00526d30d3..97094b04ec 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -1856,6 +1856,7 @@ fn a_streamed_layer_reads_only_the_view_when_nothing_it_draws_reaches_in() { if near { let e = drawn.unwrap_or_else(|| panic!("case {n}: the whole source was read")); let read = features.iter().filter(|f| f.geometry.as_ref().is_some_and(|g| g.extent().intersects(&e))).count(); + // A fifth: the view is read a quarter of its size wider on each side, to be kept. assert!(read * 5 < total, "case {n}, {view:?}: {read} of {total} features read for a view of a few"); } else { assert_eq!(drawn, None, "case {n}: a layer reaching in from beyond the view reads everything"); From 80c8384a8b79ecdd9fadab9e6b8c2d3d4aca0d8a Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 08:03:55 -0600 Subject: [PATCH 6/6] fix(map): keep a view read with nothing in it, so its frames read nothing again (#1065) --- crates/map/src/source/render_view.rs | 5 +++-- crates/render/src/stream_tests.rs | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/map/src/source/render_view.rs b/crates/map/src/source/render_view.rs index 6e2509b20b..106a7427f6 100644 --- a/crates/map/src/source/render_view.rs +++ b/crates/map/src/source/render_view.rs @@ -55,8 +55,9 @@ impl KeptView { self.drop_chunks(); } let r = &self.read; - let holds = - !self.chunks.is_empty() && r.min_x <= near.min_x && r.min_y <= near.min_y && r.max_x >= near.max_x && r.max_y >= near.max_y; + // A view read with nothing in it is kept too (no chunks): its frames draw nothing. With + // nothing kept, `read` is empty and holds no box. + let holds = r.min_x <= near.min_x && r.min_y <= near.min_y && r.max_x >= near.max_x && r.max_y >= near.max_y; holds.then(|| Arc::clone(&self.chunks)) } diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 97094b04ec..c1eef6f042 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -1970,4 +1970,8 @@ fn a_kept_view_draws_the_frames_inside_it_without_reading_the_source() { assert_eq!(frame(&mut base, &mut actual, &view, "back"), [false; 0], "the Web Mercator view is still kept"); actual.layers[0].source.as_mut().unwrap().reset(); assert_eq!(frame(&mut base, &mut actual, &view, "reset"), [false, true], "a reset source reads again"); + // A view of nowhere in the layer, past the grid's east edge, is kept with nothing in it. + view.camera.center = rustgis_geom::lonlat_to_merc(Coord::new(30.0, 0.3)); + assert_eq!(frame(&mut base, &mut actual, &view, "empty"), [true], "an empty view is read"); + assert_eq!(frame(&mut base, &mut actual, &view, "empty again"), [false; 0], "and kept, with nothing in it"); }