From 4f7e442ddb63ff5959c8932576b0a00fc0044bac Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 15:03:20 -0600 Subject: [PATCH 1/6] fix(data): large Shapefile and GeoJSON files open off the UI thread, with progress and Cancel (#2446) A file too large to load is read in place, and its first open reads it whole: a Shapefile's records go into its spatial index, a GeoJSON file is scanned for its features. Add Data's background read left these files out, so on the desktop the window stopped responding for minutes on a file of millions of features. Add Data now opens them on its read thread (in_place_ahead), and the command takes the opened source by a key of the path and coordinate system. The index build and the GeoJSON scan count their progress in bytes and look at Cancel every few thousand records or features. Closes #2446 Co-Authored-By: Claude Opus 5.5 --- crates/data/src/io.rs | 8 ++ crates/data/src/source/geojson.rs | 47 ++++++++- crates/data/src/source/shp/index.rs | 13 +++ crates/engine/src/cmd/layer.rs | 125 +++++++++++++++++++----- crates/engine/src/tests.rs | 15 +-- crates/engine/src/tests/cancellation.rs | 6 ++ 6 files changed, 181 insertions(+), 33 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index b50e1fd0b7..74bfd98096 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1389,6 +1389,10 @@ pub(crate) trait FeatureSink { fn restart(&mut self); /// One element of `"features"`, as its text. fn feature(&mut self, raw: &str); + /// Whether the read is to stop now (Cancel pressed): it then ends with an error. + fn stopped(&self) -> bool { + false + } } /// Reads a GeoJSON document's top level, handing each element of `"features"` to `sink` as it is @@ -1457,9 +1461,13 @@ impl<'de> serde::de::Visitor<'de> for Features<'_> { f.write_str("an array of features") } + /// Hands each element to the sink as its text, ending with an error once the sink is stopped. fn visit_seq>(self, mut seq: A) -> std::result::Result<(), A::Error> { while let Some(raw) = seq.next_element::<&'de serde_json::value::RawValue>()? { self.sink.feature(raw.get()); + if self.sink.stopped() { + return Err(serde::de::Error::custom("cancelled")); + } } Ok(()) } diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 6902a3f0b5..fccef836e7 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -66,9 +66,30 @@ struct Scan { swapped: usize, /// The places of features whose heights reading drops. zm: Vec, + /// Features [`paced`](Scan::pace) so far, and the byte the progress was counted to. + paced: usize, + paced_to: u64, + /// Cancel was pressed: the scan stops. + stopped: bool, } +/// Features between looks at Cancel (and progress counts) while a file is scanned or converted. +const PACE: usize = 4096; + impl Scan { + /// Says the scan has come `at` bytes into the file, and looks at Cancel: at the first feature + /// and every [`PACE`] after it (#2446). + fn pace(&mut self, at: u64) -> Result<()> { + let n = self.paced; + self.paced += 1; + if !n.is_multiple_of(PACE) { + return Ok(()); + } + let done = at.saturating_sub(self.paced_to); + self.paced_to = self.paced_to.max(at); + crate::progress::step(usize::try_from(done).unwrap_or(usize::MAX)) + } + /// One element of `"features"`, read from `len` bytes at `offset` (with the comma and /// whitespace before it). fn feature(&mut self, f: &Json, offset: u64, len: u64) { @@ -146,20 +167,25 @@ impl GeoJsonSource { pub(crate) fn open_with(path: &Path, name: &str, in_memory: u64) -> Result { use serde::de::DeserializeSeed; let mut scan = Scan::default(); - let rest = if std::fs::metadata(path)?.len() <= in_memory { + let size = std::fs::metadata(path)?.len(); + // How far the scan has come, in bytes of the file; Cancel stops it, said as such rather than + // as the JSON error it ends with. + crate::progress::begin(usize::try_from(size).unwrap_or(usize::MAX)); + let failed = |e: serde_json::Error| if crate::progress::check().is_err() { DataError::Cancelled } else { bad(e) }; + let rest = if size <= in_memory { let text = crate::provenance::read_to_string(path)?; // Its objects and vertices would all become a JSON tree, only to be refused below. if crate::cityjson::looks_like_cityjson(&text) { return Err(DataError::Unsupported("only GeoJSON FeatureCollections are read in place".into())); } - crate::io::stream_features(&text, &mut InText { scan: &mut scan, start: text.as_ptr() as usize }).map_err(bad)? + crate::io::stream_features(&text, &mut InText { scan: &mut scan, start: text.as_ptr() as usize }).map_err(failed)? } else { let read = std::rc::Rc::new(std::cell::Cell::new(0u64)); let file = Counting { inner: BufReader::with_capacity(BUFFER, crate::provenance::open(path)?), read: read.clone() }; let mut de = serde_json::Deserializer::from_reader(file); - let rest = Top { scan: &mut scan, read }.deserialize(&mut de).map_err(bad)?; + let rest = Top { scan: &mut scan, read }.deserialize(&mut de).map_err(failed)?; // Only whitespace may follow, as when read whole. - de.end().map_err(bad)?; + de.end().map_err(failed)?; rest }; if rest.get("type").and_then(Json::as_str) != Some("FeatureCollection") { @@ -380,6 +406,9 @@ fn convert_pass(path: &Path, places: &[Place], t: &crate::raster::Transformer) - let (mut pos, mut buf) = (0u64, Vec::new()); let mut pass = Pass { failed: Vec::new(), dropped: [0; 3], extent: Extent::EMPTY }; for (i, place) in places.iter().enumerate() { + if i.is_multiple_of(PACE) { + crate::progress::check()?; + } // A feature that can't be read now is left to the reads, which skip it. if let Some(json) = read_place(&mut f, &mut pos, &mut buf, place) && let Ok(Some(g)) = geojson_geometry(&json) @@ -476,11 +505,13 @@ impl<'de> serde::de::Visitor<'de> for Elements<'_> { f.write_str("an array of features") } + /// Scans each feature with its place in the file, ending with an error once Cancel is pressed. fn visit_seq>(self, mut seq: A) -> std::result::Result<(), A::Error> { loop { let start = self.read.get(); let Some(f) = seq.next_element::()? else { break }; self.scan.feature(&f, start, self.read.get().saturating_sub(start)); + self.scan.pace(self.read.get()).map_err(|_| serde::de::Error::custom("cancelled"))?; } Ok(()) } @@ -498,6 +529,7 @@ impl FeatureSink for InText<'_> { *self.scan = Scan::default(); } + /// Scans one feature, its place where its text is in the file's; Cancel pressed stops the read. fn feature(&mut self, raw: &str) { let offset = (raw.as_ptr() as usize).saturating_sub(self.start) as u64; match serde_json::from_str::(raw) { @@ -505,5 +537,12 @@ impl FeatureSink for InText<'_> { // Valid JSON, but with a number that doesn't fit. Err(_) => self.scan.skipped += 1, } + if self.scan.pace(offset + raw.len() as u64).is_err() { + self.scan.stopped = true; + } + } + + fn stopped(&self) -> bool { + self.scan.stopped } } diff --git a/crates/data/src/source/shp/index.rs b/crates/data/src/source/shp/index.rs index 4ce3c6b5bb..aeadc631e8 100644 --- a/crates/data/src/source/shp/index.rs +++ b/crates/data/src/source/shp/index.rs @@ -30,9 +30,15 @@ fn connect(path: &Path, write: bool) -> Result { } impl DiskIndex { + /// The `.shp`'s index from the cache when one was built for this file as it is now, else built + /// there by scanning its records (looking at Cancel and counting progress as it goes); an error + /// when neither can be had, for [`Index::open`] to scan the records instead. pub fn open(path: &Path, len: u64, notes: &mut Vec) -> Result { use super::cache; use crate::source::external::{fnv1a, stamp}; + // Cancel is looked at once even when the index is reused, so an opening can always be + // stopped before the layer is added (#2446). + crate::progress::check()?; let canonical = path.canonicalize()?; let signature = format!("shp-index-v7:{canonical:?}:{:?}", stamp(path)?); let mut dir = cache::index_dir(); @@ -94,7 +100,14 @@ impl DiskIndex { let (count, note) = { let mut record = tx.prepare("INSERT INTO records VALUES(?1,?2,?3)").map_err(sql)?; let mut bounds = tx.prepare("INSERT INTO bounds VALUES(?1,?2,?3,?4,?5)").map_err(sql)?; + // How far the build has come, in bytes of the .shp, every so many records (#2446). + crate::progress::begin(usize::try_from(len).unwrap_or(usize::MAX)); + let mut paced = 0u32; scan_boxed(path, len, |id, place, b| { + if id.is_multiple_of(4096) { + crate::progress::step(place.offset.saturating_sub(paced) as usize)?; + paced = place.offset; + } record.execute(params![id, place.offset, place.len]).map_err(sql)?; if union(&mut all_bounds, b) { let [x0, y0, x1, y1] = b; diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index f759fa7f8e..a90a09bafe 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2064,13 +2064,14 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { && !rustgis_data::cityjson::is_cityjson_name(path) // One read whole ahead keeps that route, though the file grew since. && !super::reads::placed_for(s, &whole_key(path)) - && b(p, "stream").unwrap_or_else(|| { - std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() > rustgis_data::source::geojson::IN_PLACE_ABOVE) - }) + && streams_geojson(p, path) { let name = Path::new(path).file_stem().and_then(|n| n.to_str()).unwrap_or("layer"); - match rustgis_data::source::geojson::GeoJsonSource::open_path(Path::new(path), name) { - Ok(src) => return add_source_with(s, p, Origin::Path(path), Some(Box::new(src)), None), + // Opened ahead in the desktop app ([`in_place_ahead`]). + let opened = super::reads::take::(s, &in_place_key(path, None)) + .unwrap_or_else(|| Ok(Box::new(rustgis_data::source::geojson::GeoJsonSource::open_path(Path::new(path), name)?))); + match opened { + Ok(src) => return add_source_with(s, p, Origin::Path(path), Some(src), None), // Not a FeatureCollection: read whole below, on this thread (the UI thread in the // desktop app, as only small GeoJSON files are read ahead), so within the size every // computer reads, as before #2408, not the larger limit: the window isn't held longer. @@ -2101,12 +2102,14 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { { let crs = super::parse_crs(s, crs)?; let name = Path::new(path).file_stem().and_then(|n| n.to_str()).unwrap_or("layer"); - let stream = b(p, "stream").unwrap_or_else(|| { - rustgis_data::source::shp::record_count(Path::new(path)).is_some_and(|n| n > rustgis_map::source::STREAM_ABOVE) - }); + let stream = streams_shapefile(p, path); if stream { - let src = rustgis_data::source::shp::ShpSource::open_path_in(Path::new(path), name, Some(crs)).map_err(|e| e.to_string())?; - return add_source_with(s, p, Origin::Path(path), Some(Box::new(src)), None); + // Opened ahead in the desktop app ([`in_place_ahead`]), in the same system. + let key = in_place_key(path, ps(p, "crs").map(str::trim)); + let src = super::reads::take::(s, &key) + .unwrap_or_else(|| Ok(Box::new(rustgis_data::source::shp::ShpSource::open_path_in(Path::new(path), name, Some(crs))?))) + .map_err(|e| e.to_string())?; + return add_source_with(s, p, Origin::Path(path), Some(src), None); } // Read ahead in the desktop app ([`add_data_ahead`]). let read = match super::reads::take(s, &whole_key(path)) { @@ -2117,12 +2120,12 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { } // A large Shapefile is read in place, as a GeoPackage is; smaller ones are loaded whole. #[cfg(not(target_arch = "wasm32"))] - if path.to_ascii_lowercase().ends_with(".shp") - && b(p, "stream").unwrap_or_else(|| { - rustgis_data::source::shp::record_count(Path::new(path)).is_some_and(|n| n > rustgis_map::source::STREAM_ABOVE) - }) - { - return add_source(s, p, Origin::Path(path), None); + if path.to_ascii_lowercase().ends_with(".shp") && streams_shapefile(p, path) { + // Opened ahead in the desktop app ([`in_place_ahead`]). + return match super::reads::take::(s, &in_place_key(path, None)) { + Some(opened) => add_source_with(s, p, Origin::Path(path), Some(opened.map_err(|e| format!("{path}: {e}"))?), None), + None => add_source(s, p, Origin::Path(path), None), + }; } // A PMTiles archive is a tile layer (raster or vector, as its header says). if path.to_ascii_lowercase().ends_with(".pmtiles") { @@ -2468,12 +2471,83 @@ fn read_synced(path: &str, read: impl FnOnce() -> WholeRead) -> WholeRead { Ok((ds, report)) } +/// Whether Add Data reads the Shapefile at `path` in place: as `p` says (with +/// [`past_cap_shapefile`] applied), else when it holds more records than +/// [`STREAM_ABOVE`](rustgis_map::source::STREAM_ABOVE). +#[cfg(not(target_arch = "wasm32"))] +fn streams_shapefile(p: &Value, path: &str) -> bool { + b(p, "stream") + .unwrap_or_else(|| rustgis_data::source::shp::record_count(Path::new(path)).is_some_and(|n| n > rustgis_map::source::STREAM_ABOVE)) +} + +/// Whether Add Data reads the GeoJSON file at `path` in place (when it is a FeatureCollection): as +/// `p` says, else when it is larger than +/// [`IN_PLACE_ABOVE`](rustgis_data::source::geojson::IN_PLACE_ABOVE). +#[cfg(not(target_arch = "wasm32"))] +fn streams_geojson(p: &Value, path: &str) -> bool { + b(p, "stream") + .unwrap_or_else(|| std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() > rustgis_data::source::geojson::IN_PLACE_ABOVE)) +} + +/// A large Shapefile or GeoJSON file, read in place, as Add Data opens it (#2446). +#[cfg(not(target_arch = "wasm32"))] +type Opened = Result, rustgis_data::DataError>; + +/// The key of Add Data's opening of `path` in place, in the coordinate system `crs` names (see +/// [`super::reads`]). +#[cfg(not(target_arch = "wasm32"))] +fn in_place_key(path: &str, crs: Option<&str>) -> String { + format!("in-place:{}", json!([path, crs])) +} + +/// The opening of a large Shapefile or GeoJSON file that Add Data reads in place, made ahead on a +/// thread of its own (#2446): it reads the whole file once, to index a Shapefile's records or +/// find a GeoJSON file's features, which takes minutes for a file of millions. As [`add_data`] +/// decides ([`streams_geojson`], [`streams_shapefile`]), but a `.json` given a coordinate system +/// or a layer, which may be a city model told as it is added, so it is opened there as before. +/// Cancel is looked at every few thousand features or records; a file read into memory to be +/// scanned (a GeoJSON file of at most 256 MiB) is read in one step without a look. +#[cfg(not(target_arch = "wasm32"))] +fn in_place_ahead(p: &Value, path: &str) -> Option { + const NAME: &str = "Add Data"; + let lower = path.to_ascii_lowercase(); + let name = Path::new(path).file_stem().and_then(|n| n.to_str()).unwrap_or("layer").to_string(); + let given = |k: &str| ps(p, k).is_some_and(|v| !v.trim().is_empty()); + if is_geojson(path) + && !rustgis_data::cityjson::is_cityjson_name(path) + && !(lower.ends_with(".json") && (given("crs") || given("layer"))) + && streams_geojson(p, path) + { + let path = path.to_string(); + return Some(super::reads::ahead(NAME, in_place_key(&path, None), move || -> Opened { + Ok(Box::new(rustgis_data::source::geojson::GeoJsonSource::open_path(Path::new(&path), &name)?)) + })); + } + if !lower.ends_with(".shp") { + return None; + } + let q = past_cap_shapefile(path, p).unwrap_or_else(|| p.clone()); + let stream = streams_shapefile(&q, path); + if !stream { + return None; + } + let text = ps(&q, "crs").map(str::trim).filter(|c| !c.is_empty()); + // One add_data can't parse it refuses as it runs. + let crs = text.map(rustgis_data::raster::Crs::parse).transpose().ok()?; + let (key, path) = (in_place_key(path, text), path.to_string()); + Some(super::reads::ahead(NAME, key, move || -> Opened { + Ok(Box::new(rustgis_data::source::shp::ShpSource::open_path_in(Path::new(&path), &name, crs)?)) + })) +} + /// Add Data's read of the file `p` names, made before it runs ([`super::reads`]): a raster read /// whole or converted by GDAL, a GeoJSON read whole, delimited text, a spreadsheet or a city model -/// (CityJSON or CityGML) or DXF drawing read into its layers, a Shapefile read whole, or a -/// standalone dBASE table. `None` for any other file, which [`add_data`] reads as it adds it. Each is picked only where `add_data` -/// takes that read, so a read made is never wasted; a few it makes whole are left to it (a `.json` -/// with a coordinate system or layer given, a large GeoJSON that isn't a FeatureCollection). +/// (CityJSON or CityGML) or DXF drawing read into its layers, a Shapefile read whole, a large +/// Shapefile or GeoJSON file opened in place ([`in_place_ahead`]), or a standalone dBASE table. +/// `None` for any other file, which [`add_data`] reads as it adds it. Each is picked only where +/// `add_data` takes that read, so a read made is never wasted; a few it makes whole are left to it +/// (a `.json` with a coordinate system or layer given, a large GeoJSON that isn't a +/// FeatureCollection). #[cfg(not(target_arch = "wasm32"))] pub(crate) fn add_data_ahead(p: &Value) -> Option { use super::reads::ahead; @@ -2482,8 +2556,15 @@ pub(crate) fn add_data_ahead(p: &Value) -> Option { if let Some(shp) = rustgis_data::io::shapefile_for_dbf(Path::new(&path)) { let mut q = p.clone(); q["path"] = json!(shp.display().to_string()); + // Opened in place, it is taken by its own key as add_data goes on to the Shapefile. + if let Some(work) = in_place_ahead(&q, &shp.display().to_string()) { + return Some(work); + } return add_data_ahead(&q).map(|work| work.with_key(dbf_shapefile_key(&path))); } + if let Some(work) = in_place_ahead(p, &path) { + return Some(work); + } let scan = super::raster::wants_scan(p, &path).ok()?; if !scan && rustgis_data::photo::is_photo_name(&path) && !rustgis_data::raster::world::places(Path::new(&path)) { return None; @@ -2528,9 +2609,7 @@ pub(crate) fn add_data_ahead(p: &Value) -> Option { // past the whole-file reader's cap, or with more records than it takes, is read in place). if lower.ends_with(".shp") { let q = past_cap_shapefile(&path, p).unwrap_or_else(|| p.clone()); - let stream = b(&q, "stream").unwrap_or_else(|| { - rustgis_data::source::shp::record_count(Path::new(&path)).is_some_and(|n| n > rustgis_map::source::STREAM_ABOVE) - }); + let stream = streams_shapefile(&q, &path); if stream { return None; } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1aaeecd753..eb496a6bc5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -48424,17 +48424,19 @@ fn reads_made_ahead_are_taken_by_the_command() { assert!(r.get("layer").is_some() || r.get("layers").is_some(), "{name}: {r}"); } assert_eq!(s.map().layers.len(), 4, "{:?}", s.map().layers.iter().map(|l| &l.name).collect::>()); - // A file read in place (and any the command reads differently) reads as it runs. + // A GeoPackage, which opens without reading it whole (and any file the command reads + // differently), reads as it runs. let gpkg = json!({"path": dir.join("table.gpkg").display().to_string()}); assert!(!crate::cmd::reads::read_ahead(&mut s, "layer.addData", &gpkg).unwrap().reads()); // Load All's read, on a copy of the streamed layer. let path = dir.join("streamed.geojson"); std::fs::write(&path, points).unwrap(); - let inline = + let opening = crate::cmd::reads::read_ahead(&mut s, "layer.addData", &json!({"path": path.display().to_string(), "stream": true})).unwrap(); - assert!(!inline.reads(), "an in-place opening still owns its original inline command"); - let id = crate::cmd::reads::read_land(&mut s, inline.run(&Control::new()).unwrap()).unwrap()["layer"].as_u64().unwrap(); + assert!(opening.reads(), "a file read in place is opened ahead too (#2446)"); + let id = crate::cmd::reads::read_land(&mut s, opening.run(&Control::new()).unwrap()).unwrap()["layer"].as_u64().unwrap(); + assert!(s.read_ahead.is_none(), "the opening was taken"); assert!(s.map().layer(id as u32).unwrap().is_streamed()); let p = json!({"layer": id}); let read = crate::cmd::reads::read_ahead(&mut s, "layer.loadAll", &p).unwrap().run(&Control::new()).unwrap(); @@ -54576,12 +54578,13 @@ fn standalone_dbf_add_data_uses_tables_and_companion_shapefile() { ) .unwrap(); } - // Read-ahead and dispatch must agree on the SHP path, including the streamed route. + // Read-ahead and dispatch must agree on the SHP path, including the streamed route, which is + // opened ahead too (#2446). for stream in [false, true] { let mut paired = Session::new(Project::default()); let p = json!({"path": path, "stream": stream}); let ahead = crate::cmd::reads::read_ahead(&mut paired, "layer.addData", &p).unwrap(); - assert_eq!(ahead.reads(), !stream); + assert!(ahead.reads(), "stream {stream}: the companion Shapefile is read ahead"); let read = ahead.run(&rustgis_analysis::control::Control::new()).unwrap(); if !stream { std::fs::remove_file(&shp).unwrap(); diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 136012457b..196dd3779d 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -178,6 +178,12 @@ pub(super) fn long_commands(boundaries: bool) { assert!(control.looked() > 0, "edit.previewShapeConversion never looks at Cancel"); assert!(contents(&shapes.project) == before, "edit.previewShapeConversion changed the project after Cancel"); } + // A Shapefile and a GeoJSON file read in place are opened on the same queue: the Shapefile's + // records indexed, the GeoJSON file's features found, Cancel looked at as they go (#2446). + for file in ["in-place.shp", "in-place.geojson"] { + s.run("share.exportLayer", &json!({"layer": "Cities", "path": out(file)})).unwrap(); + exercise(&s, "layer.addData", &json!({"path": out(file), "stream": true}), Kind::Read, &dir.0, boundaries); + } // A PDF's page is read on the same queue: the file, then its drawing, Cancel looked at between // (#2336). s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); From ca7de7027d60263a0d0fe05cabaf069c6a065ace Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 17:30:27 -0600 Subject: [PATCH 2/6] fix(data): review fixes for opening large files off the UI thread (#2446) - An opening made ahead of a file changed before the command lands is set aside and the file opened again, so a layer's places and boxes are those of what the file holds (size and modification time compared). - A large GeoJSON file of few enough features, loaded rather than kept in place, is read whole on the read thread too. - A .json given a coordinate system or layer is opened ahead past the 256 MiB that Add Data reads first to tell a city model. - The record scan made when a Shapefile's index can't be cached counts its progress as the index build does. - The cancel sweep covers the GeoJSON scan's look at Cancel past its first 4,096 features. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/source/shp/index.rs | 44 +++++++-- crates/engine/src/cmd/layer.rs | 119 +++++++++++++++++++----- crates/engine/src/tests.rs | 24 +++++ crates/engine/src/tests/cancellation.rs | 6 ++ 4 files changed, 160 insertions(+), 33 deletions(-) diff --git a/crates/data/src/source/shp/index.rs b/crates/data/src/source/shp/index.rs index aeadc631e8..4715eec7ef 100644 --- a/crates/data/src/source/shp/index.rs +++ b/crates/data/src/source/shp/index.rs @@ -31,8 +31,10 @@ fn connect(path: &Path, write: bool) -> Result { impl DiskIndex { /// The `.shp`'s index from the cache when one was built for this file as it is now, else built - /// there by scanning its records (looking at Cancel and counting progress as it goes); an error - /// when neither can be had, for [`Index::open`] to scan the records instead. + /// there by scanning its records (looking at Cancel and counting progress as it goes). + /// [`DataError::Cancelled`](crate::DataError::Cancelled) when Cancel was pressed, which + /// [`Index::open`] passes on; any other error when neither can be had, for it to scan the + /// records instead. pub fn open(path: &Path, len: u64, notes: &mut Vec) -> Result { use super::cache; use crate::source::external::{fnv1a, stamp}; @@ -100,14 +102,9 @@ impl DiskIndex { let (count, note) = { let mut record = tx.prepare("INSERT INTO records VALUES(?1,?2,?3)").map_err(sql)?; let mut bounds = tx.prepare("INSERT INTO bounds VALUES(?1,?2,?3,?4,?5)").map_err(sql)?; - // How far the build has come, in bytes of the .shp, every so many records (#2446). - crate::progress::begin(usize::try_from(len).unwrap_or(usize::MAX)); - let mut paced = 0u32; + let mut paced = Paced::begin(len); scan_boxed(path, len, |id, place, b| { - if id.is_multiple_of(4096) { - crate::progress::step(place.offset.saturating_sub(paced) as usize)?; - paced = place.offset; - } + paced.at(id, place)?; record.execute(params![id, place.offset, place.len]).map_err(sql)?; if union(&mut all_bounds, b) { let [x0, y0, x1, y1] = b; @@ -255,6 +252,31 @@ fn union(all: &mut Option<[f32; 4]>, b: [f32; 4]) -> bool { true } +/// The progress of a scan made as a Shapefile is opened (an index built, or the records counted +/// when none can be), in bytes of the `.shp` (#2446). +struct Paced { + to: u32, +} + +impl Paced { + /// Starts counting a scan of a `.shp` of `len` bytes. + fn begin(len: u64) -> Self { + crate::progress::begin(usize::try_from(len).unwrap_or(usize::MAX)); + Self { to: 0 } + } + + /// Counts the bytes up to record `id`, at `place`, every so many records; stops once Cancel + /// was pressed. + fn at(&mut self, id: u32, place: Place) -> Result<()> { + if !id.is_multiple_of(4096) { + return Ok(()); + } + let done = place.offset.saturating_sub(self.to); + self.to = self.to.max(place.offset); + crate::progress::step(usize::try_from(done).unwrap_or(usize::MAX)) + } +} + /// What scanning the records' headers gathers, as a disk index holds it, for when none can be /// written. pub(super) struct Scanned { @@ -269,7 +291,9 @@ pub(super) struct Scanned { /// isn't one. pub(super) fn scanned(path: &Path, len: u64) -> Result { let (mut bounds, mut unboxed) = (None, 0u32); - let (count, note) = scan_boxed(path, len, |_, _, b| { + let mut paced = Paced::begin(len); + let (count, note) = scan_boxed(path, len, |id, place, b| { + paced.at(id, place)?; if !union(&mut bounds, b) && not_a_box(b) { unboxed += 1; } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index a90a09bafe..b1ea21c2f9 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2068,10 +2068,11 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { { let name = Path::new(path).file_stem().and_then(|n| n.to_str()).unwrap_or("layer"); // Opened ahead in the desktop app ([`in_place_ahead`]). - let opened = super::reads::take::(s, &in_place_key(path, None)) - .unwrap_or_else(|| Ok(Box::new(rustgis_data::source::geojson::GeoJsonSource::open_path(Path::new(path), name)?))); - match opened { - Ok(src) => return add_source_with(s, p, Origin::Path(path), Some(src), None), + let Opened { source, whole, .. } = take_opened(s, path, None).unwrap_or_else(|| { + Opened::here(|| Ok(Box::new(rustgis_data::source::geojson::GeoJsonSource::open_path(Path::new(path), name)?))) + }); + match source { + Ok(src) => return add_source_read(s, p, Origin::Path(path), Some(src), whole, None), // Not a FeatureCollection: read whole below, on this thread (the UI thread in the // desktop app, as only small GeoJSON files are read ahead), so within the size every // computer reads, as before #2408, not the larger limit: the window isn't held longer. @@ -2105,11 +2106,10 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { let stream = streams_shapefile(p, path); if stream { // Opened ahead in the desktop app ([`in_place_ahead`]), in the same system. - let key = in_place_key(path, ps(p, "crs").map(str::trim)); - let src = super::reads::take::(s, &key) - .unwrap_or_else(|| Ok(Box::new(rustgis_data::source::shp::ShpSource::open_path_in(Path::new(path), name, Some(crs))?))) - .map_err(|e| e.to_string())?; - return add_source_with(s, p, Origin::Path(path), Some(src), None); + let Opened { source, whole, .. } = take_opened(s, path, ps(p, "crs").map(str::trim)).unwrap_or_else(|| { + Opened::here(|| Ok(Box::new(rustgis_data::source::shp::ShpSource::open_path_in(Path::new(path), name, Some(crs))?))) + }); + return add_source_read(s, p, Origin::Path(path), Some(source.map_err(|e| e.to_string())?), whole, None); } // Read ahead in the desktop app ([`add_data_ahead`]). let read = match super::reads::take(s, &whole_key(path)) { @@ -2122,8 +2122,10 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { #[cfg(not(target_arch = "wasm32"))] if path.to_ascii_lowercase().ends_with(".shp") && streams_shapefile(p, path) { // Opened ahead in the desktop app ([`in_place_ahead`]). - return match super::reads::take::(s, &in_place_key(path, None)) { - Some(opened) => add_source_with(s, p, Origin::Path(path), Some(opened.map_err(|e| format!("{path}: {e}"))?), None), + return match take_opened(s, path, None) { + Some(Opened { source, whole, .. }) => { + add_source_read(s, p, Origin::Path(path), Some(source.map_err(|e| format!("{path}: {e}"))?), whole, None) + } None => add_source(s, p, Origin::Path(path), None), }; } @@ -2489,9 +2491,60 @@ fn streams_geojson(p: &Value, path: &str) -> bool { .unwrap_or_else(|| std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() > rustgis_data::source::geojson::IN_PLACE_ABOVE)) } -/// A large Shapefile or GeoJSON file, read in place, as Add Data opens it (#2446). +/// A large Shapefile or GeoJSON file, read in place, as Add Data opens it ahead (#2446). +#[cfg(not(target_arch = "wasm32"))] +struct Opened { + /// The file's size and modification time as it was opened: an opening of a file changed + /// since isn't taken, as its features' places and boxes are those of what it held then. + stamp: Option<(u64, std::time::SystemTime)>, + source: Result, rustgis_data::DataError>, + /// Its features read whole, when Add Data loads the file instead of keeping it in place (it + /// holds few enough, and `"stream"` isn't given), so the window doesn't wait for that read. + whole: Option>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Opened { + /// Opens a file where the command runs (the command line, Python, or no opening made ahead). + fn here(open: impl FnOnce() -> rustgis_data::Result>) -> Self { + Self { stamp: None, source: open(), whole: None } + } + + /// Opens `path` on the read thread, and reads its features whole there too when `may_load` + /// and it holds no more than [`STREAM_ABOVE`](rustgis_map::source::STREAM_ABOVE), as + /// [`add_source_read`] then loads it rather than keeping it in place. + fn ahead( + path: &str, + may_load: bool, + open: impl FnOnce() -> rustgis_data::Result>, + ) -> Self { + let stamp = file_stamp(path); + let source = open(); + let whole = match &source { + Ok(src) if may_load && src.info().count.is_some_and(|c| c <= rustgis_map::source::STREAM_ABOVE) => { + Some(rustgis_data::source::materialize(src.as_ref())) + } + _ => None, + }; + Self { stamp, source, whole } + } +} + +/// A file's size and modification time, when both can be read. #[cfg(not(target_arch = "wasm32"))] -type Opened = Result, rustgis_data::DataError>; +fn file_stamp(path: &str) -> Option<(u64, std::time::SystemTime)> { + let m = std::fs::metadata(path).ok()?; + Some((m.len(), m.modified().ok()?)) +} + +/// Add Data's opening of `path` in the system `crs` names, made ahead in the desktop app +/// ([`in_place_ahead`]), while the file is as it was then; `None` otherwise (the command line, +/// Python, or a file changed since), for the command to open it itself. +#[cfg(not(target_arch = "wasm32"))] +fn take_opened(s: &mut Session, path: &str, crs: Option<&str>) -> Option { + let opened = super::reads::take::(s, &in_place_key(path, crs))?; + (opened.stamp.is_some() && opened.stamp == file_stamp(path)).then_some(opened) +} /// The key of Add Data's opening of `path` in place, in the coordinate system `crs` names (see /// [`super::reads`]). @@ -2503,8 +2556,9 @@ fn in_place_key(path: &str, crs: Option<&str>) -> String { /// The opening of a large Shapefile or GeoJSON file that Add Data reads in place, made ahead on a /// thread of its own (#2446): it reads the whole file once, to index a Shapefile's records or /// find a GeoJSON file's features, which takes minutes for a file of millions. As [`add_data`] -/// decides ([`streams_geojson`], [`streams_shapefile`]), but a `.json` given a coordinate system -/// or a layer, which may be a city model told as it is added, so it is opened there as before. +/// decides ([`streams_geojson`], [`streams_shapefile`]), but a `.json` of at most 256 MiB given a +/// coordinate system or a layer, which may be a city model told as it is added, so it is opened +/// there as before. /// Cancel is looked at every few thousand features or records; a file read into memory to be /// scanned (a GeoJSON file of at most 256 MiB) is read in one step without a look. #[cfg(not(target_arch = "wasm32"))] @@ -2515,12 +2569,18 @@ fn in_place_ahead(p: &Value, path: &str) -> Option { let given = |k: &str| ps(p, k).is_some_and(|v| !v.trim().is_empty()); if is_geojson(path) && !rustgis_data::cityjson::is_cityjson_name(path) - && !(lower.ends_with(".json") && (given("crs") || given("layer"))) + // Up to the size every computer reads, add_data reads such a .json whole first to tell a + // city model; a larger one it opens in place, as here. + && !(lower.ends_with(".json") + && (given("crs") || given("layer")) + && std::fs::metadata(path).is_ok_and(|m| m.len() <= rustgis_data::io::BYTES_FLOOR)) && streams_geojson(p, path) { - let path = path.to_string(); - return Some(super::reads::ahead(NAME, in_place_key(&path, None), move || -> Opened { - Ok(Box::new(rustgis_data::source::geojson::GeoJsonSource::open_path(Path::new(&path), &name)?)) + let (path, may_load) = (path.to_string(), b(p, "stream").is_none()); + return Some(super::reads::ahead(NAME, in_place_key(&path, None), move || { + Opened::ahead(&path, may_load, || { + Ok(Box::new(rustgis_data::source::geojson::GeoJsonSource::open_path(Path::new(&path), &name)?)) + }) })); } if !lower.ends_with(".shp") { @@ -2534,9 +2594,9 @@ fn in_place_ahead(p: &Value, path: &str) -> Option { let text = ps(&q, "crs").map(str::trim).filter(|c| !c.is_empty()); // One add_data can't parse it refuses as it runs. let crs = text.map(rustgis_data::raster::Crs::parse).transpose().ok()?; - let (key, path) = (in_place_key(path, text), path.to_string()); - Some(super::reads::ahead(NAME, key, move || -> Opened { - Ok(Box::new(rustgis_data::source::shp::ShpSource::open_path_in(Path::new(&path), &name, crs)?)) + let (key, path, may_load) = (in_place_key(path, text), path.to_string(), b(&q, "stream").is_none()); + Some(super::reads::ahead(NAME, key, move || { + Opened::ahead(&path, may_load, || Ok(Box::new(rustgis_data::source::shp::ShpSource::open_path_in(Path::new(&path), &name, crs)?))) })) } @@ -3107,10 +3167,23 @@ pub(crate) fn add_source(s: &mut Session, p: &Value, origin: Origin<'_>, zoom: O /// [`add_source`], with the source already open (its one table). fn add_source_with( + s: &mut Session, + p: &Value, + origin: Origin<'_>, + opened: Option>, + zoom: Option, +) -> CmdResult { + add_source_read(s, p, origin, opened, None, zoom) +} + +/// [`add_source_with`], with the open source's features already read whole (`whole`, made ahead +/// on the read thread, #2446) when it is loaded rather than kept in place. +fn add_source_read( s: &mut Session, p: &Value, origin: Origin<'_>, mut opened: Option>, + mut whole: Option>, zoom: Option, ) -> CmdResult { use rustgis_data::source; @@ -3254,7 +3327,7 @@ fn add_source_with( false, ); } else { - let (mut ds, report) = source::materialize(src.as_ref()).map_err(err)?; + let (mut ds, report) = whole.take().unwrap_or_else(|| source::materialize(src.as_ref())).map_err(err)?; ds.name = name; ds.source = Some(label.clone()); features += ds.features.len() as u64; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index eb496a6bc5..ff3019ac38 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -48392,6 +48392,30 @@ fn ortho_mosaic_is_made_in_its_images_projected_system() { /// Add Data's and Load All's reads made before the command runs (the desktop app's, on a thread /// of their own) are the ones the command takes: it adds what they read, without reading again. +/// A file read in place that changes between its opening ahead and the command landing it is +/// opened again, so the layer's places and boxes are those of what the file holds now (#2446). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_opening_made_ahead_of_a_file_changed_since_is_made_again() { + use rustgis_analysis::control::Control; + let dir = std::env::temp_dir().join(format!("rustgis-changed-ahead-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + // The file's length changes too, so the change is seen whatever the clock's resolution. + let path = dir.join("changing.geojson"); + let point = |x: f64| json!({"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [x, 2.0]}}); + std::fs::write(&path, json!({"type": "FeatureCollection", "features": [point(1.0)]}).to_string()).unwrap(); + let mut s = Session::new(Project::default()); + let p = json!({"path": path.display().to_string(), "stream": true}); + let ahead = crate::cmd::reads::read_ahead(&mut s, "layer.addData", &p).unwrap(); + assert!(ahead.reads()); + let read = ahead.run(&Control::new()).unwrap(); + std::fs::write(&path, json!({"type": "FeatureCollection", "features": [point(8.0), point(9.0)]}).to_string()).unwrap(); + let r = crate::cmd::reads::read_land(&mut s, read).unwrap(); + assert_eq!(r["features"], 2, "{r}"); + assert!(s.read_ahead.is_none(), "the stale opening was set aside"); + let _ = std::fs::remove_dir_all(dir); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn reads_made_ahead_are_taken_by_the_command() { diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 196dd3779d..2f7b61dfc7 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -184,6 +184,12 @@ pub(super) fn long_commands(boundaries: bool) { s.run("share.exportLayer", &json!({"layer": "Cities", "path": out(file)})).unwrap(); exercise(&s, "layer.addData", &json!({"path": out(file), "stream": true}), Kind::Read, &dir.0, boundaries); } + // Past the first few thousand features, the GeoJSON scan looks at Cancel again. + let many: Vec = (0..4097) + .map(|i| json!({"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [10.0 + f64::from(i) * 1e-4, 45.0]}})) + .collect(); + std::fs::write(out("many.geojson"), json!({"type": "FeatureCollection", "features": many}).to_string()).unwrap(); + exercise(&s, "layer.addData", &json!({"path": out("many.geojson"), "stream": true}), Kind::Read, &dir.0, boundaries); // A PDF's page is read on the same queue: the file, then its drawing, Cancel looked at between // (#2336). s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); From eea180ecaa5f3e9d4d62c192feae0b77c5e5d283 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 18:16:38 -0600 Subject: [PATCH 3/6] fix(data): an opening made ahead is set aside when a Shapefile's .dbf, .prj or .cpg changes; a whole GeoJSON read looks at Cancel (#2446) The landing check compared only the opened file. A Shapefile's opening also reads its .dbf (fields, row count, encoding), .cpg and .prj, so the files beside it of its name are compared too. A GeoJSON file read whole (Add Data loading it on the read thread) looks at Cancel every 4,096 features, as its opening scan does. Tests: a .dbf replaced between the opening and the landing lands with the new fields; a large GeoJSON file of few features is loaded on the read thread and lands as a loaded layer. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/source/geojson.rs | 7 +++-- crates/engine/src/cmd/layer.rs | 31 +++++++++++++----- crates/engine/src/tests.rs | 52 +++++++++++++++++++++++++++++-- 3 files changed, 78 insertions(+), 12 deletions(-) diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index fccef836e7..0c3df90d12 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -283,7 +283,8 @@ impl FeatureSource for GeoJsonSource { } /// Reads a bounded sample; when native bounds are refused, filters geometry before sampling, - /// counting records and checking Cancel between them. + /// counting records and checking Cancel between them. Otherwise Cancel is looked at every + /// [`PACE`] features read, so a whole read (Add Data loading the file) stops between them. fn read(&self, req: &Request) -> Result { let limit = clamp_limit(req.limit); // Counted first, then sampled, unless the native box is refused: no list of every match. @@ -305,9 +306,11 @@ impl FeatureSource for GeoJsonSource { if late { crate::progress::begin(matched); } - for i in self.matches(extent).step_by(step).take(if late { usize::MAX } else { limit }) { + for (n, i) in self.matches(extent).step_by(step).take(if late { usize::MAX } else { limit }).enumerate() { if late { crate::progress::step(1)?; + } else if n.is_multiple_of(PACE) { + crate::progress::check()?; } let Some(place) = self.places.get(i as usize) else { continue }; let Some(json) = read_place(&mut f, &mut pos, &mut buf, place) else { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index b1ea21c2f9..9112eb7c5a 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2494,9 +2494,10 @@ fn streams_geojson(p: &Value, path: &str) -> bool { /// A large Shapefile or GeoJSON file, read in place, as Add Data opens it ahead (#2446). #[cfg(not(target_arch = "wasm32"))] struct Opened { - /// The file's size and modification time as it was opened: an opening of a file changed - /// since isn't taken, as its features' places and boxes are those of what it held then. - stamp: Option<(u64, std::time::SystemTime)>, + /// The size and modification time of the file and those beside it of its name (a + /// Shapefile's `.dbf`, `.prj` and `.cpg`) as it was opened: an opening of files changed since + /// isn't taken, as its features' places, boxes and fields are those of what they held then. + stamp: Option>, source: Result, rustgis_data::DataError>, /// Its features read whole, when Add Data loads the file instead of keeping it in place (it /// holds few enough, and `"stream"` isn't given), so the window doesn't wait for that read. @@ -2530,11 +2531,27 @@ impl Opened { } } -/// A file's size and modification time, when both can be read. +/// The size and modification time of `path` and of the files beside it with the same name before +/// the extension, in any case (a Shapefile's parts), by name; `None` when any can't be read. #[cfg(not(target_arch = "wasm32"))] -fn file_stamp(path: &str) -> Option<(u64, std::time::SystemTime)> { - let m = std::fs::metadata(path).ok()?; - Some((m.len(), m.modified().ok()?)) +fn file_stamp(path: &str) -> Option> { + let path = Path::new(path); + let stem = path.file_stem()?.to_str()?; + let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + let mut stamp = Vec::new(); + for entry in std::fs::read_dir(dir).ok()? { + let entry = entry.ok()?; + let name = entry.file_name(); + if !Path::new(&name).file_stem().and_then(|n| n.to_str()).is_some_and(|n| n.eq_ignore_ascii_case(stem)) { + continue; + } + let m = entry.metadata().ok()?; + if m.is_file() { + stamp.push((name, m.len(), m.modified().ok()?)); + } + } + stamp.sort(); + Some(stamp) } /// Add Data's opening of `path` in the system `crs` names, made ahead in the desktop app diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ff3019ac38..0c5125bd05 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -48390,10 +48390,9 @@ fn ortho_mosaic_is_made_in_its_images_projected_system() { assert_eq!((w.crs, w.projected_cell_size, w.cell_size), (Some(Crs::WebMercator), Some(30.0), Some(0.0005))); } -/// Add Data's and Load All's reads made before the command runs (the desktop app's, on a thread -/// of their own) are the ones the command takes: it adds what they read, without reading again. /// A file read in place that changes between its opening ahead and the command landing it is -/// opened again, so the layer's places and boxes are those of what the file holds now (#2446). +/// opened again, so the layer's places, boxes and fields are those of what the files hold now: a +/// GeoJSON file rewritten, and a Shapefile's `.dbf` replaced (#2446). #[cfg(not(target_arch = "wasm32"))] #[test] fn an_opening_made_ahead_of_a_file_changed_since_is_made_again() { @@ -48413,9 +48412,56 @@ fn an_opening_made_ahead_of_a_file_changed_since_is_made_again() { let r = crate::cmd::reads::read_land(&mut s, read).unwrap(); assert_eq!(r["features"], 2, "{r}"); assert!(s.read_ahead.is_none(), "the stale opening was set aside"); + // A Shapefile whose .dbf is replaced (other fields) after its opening ahead. + let mut w = world(); + let shp = dir.join("towns.shp").display().to_string(); + w.run("share.exportLayer", &json!({"layer": "Cities", "path": shp})).unwrap(); + w.run("share.exportLayer", &json!({"layer": "Countries", "path": dir.join("other.shp").display().to_string()})).unwrap(); + let ahead = crate::cmd::reads::read_ahead(&mut s, "layer.addData", &json!({"path": shp, "stream": true})).unwrap(); + let read = ahead.run(&Control::new()).unwrap(); + std::fs::copy(dir.join("other.dbf"), dir.join("towns.dbf")).unwrap(); + let id = crate::cmd::reads::read_land(&mut s, read).unwrap()["layer"].as_u64().unwrap() as u32; + let fields = |l: &rustgis_map::Layer| l.dataset.fields.iter().map(|f| f.name.clone()).collect::>(); + let mut other = Session::new(Project::default()); + let other_id = + other.run("layer.addData", &json!({"path": dir.join("other.shp").display().to_string(), "stream": true})).unwrap()["layer"] + .as_u64() + .unwrap() as u32; + let replaced = fields(other.map().layer(other_id).unwrap()); + assert_eq!(fields(s.map().layer(id).unwrap()), replaced, "the replaced .dbf's fields"); let _ = std::fs::remove_dir_all(dir); } +/// A GeoJSON file past the size read whole, but of few enough features that Add Data loads it +/// rather than keeping it in place, is read whole on the read thread too (#2446): the command +/// lands a loaded layer of all its features. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_large_file_of_few_features_is_loaded_ahead() { + use rustgis_analysis::control::Control; + let dir = std::env::temp_dir().join(format!("rustgis-loaded-ahead-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("padded.geojson"); + // A thousand points, each with a long note: past `IN_PLACE_ABOVE` in all. + let note = "x".repeat(usize::try_from(rustgis_data::source::geojson::IN_PLACE_ABOVE / 1000).unwrap() + 100); + let features: Vec = (0..1000) + .map(|i| json!({"type": "Feature", "properties": {"n": i, "note": note}, "geometry": {"type": "Point", "coordinates": [f64::from(i) * 0.01, 1.0]}})) + .collect(); + std::fs::write(&path, json!({"type": "FeatureCollection", "features": features}).to_string()).unwrap(); + let mut s = Session::new(Project::default()); + let ahead = crate::cmd::reads::read_ahead(&mut s, "layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + assert!(ahead.reads(), "opened ahead"); + let read = ahead.run(&Control::new()).unwrap(); + let id = crate::cmd::reads::read_land(&mut s, read).unwrap()["layer"].as_u64().unwrap() as u32; + assert!(s.read_ahead.is_none(), "the read was taken"); + let layer = s.map().layer(id).unwrap(); + assert!(!layer.is_streamed(), "loaded, not kept in place"); + assert_eq!(layer.dataset.features.len(), 1000); + let _ = std::fs::remove_dir_all(dir); +} + +/// Add Data's and Load All's reads made before the command runs (the desktop app's, on a thread +/// of their own) are the ones the command takes: it adds what they read, without reading again. #[cfg(not(target_arch = "wasm32"))] #[test] fn reads_made_ahead_are_taken_by_the_command() { From c5b7df11cb380c98333a0574d85fdfa97e8c11e5 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 19:22:38 -0600 Subject: [PATCH 4/6] fix(data): an opening made ahead follows links when it stamps its files (#2446) A linked file or companion is stamped by the file it names, so a change to that file sets the opening aside too. The test of a large file of few features checks it is read whole before the command lands it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layer.rs | 7 ++++--- crates/engine/src/cmd/reads.rs | 6 ++++++ crates/engine/src/tests.rs | 4 ++++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 9112eb7c5a..08b9b6d5d2 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2493,7 +2493,7 @@ fn streams_geojson(p: &Value, path: &str) -> bool { /// A large Shapefile or GeoJSON file, read in place, as Add Data opens it ahead (#2446). #[cfg(not(target_arch = "wasm32"))] -struct Opened { +pub(crate) struct Opened { /// The size and modification time of the file and those beside it of its name (a /// Shapefile's `.dbf`, `.prj` and `.cpg`) as it was opened: an opening of files changed since /// isn't taken, as its features' places, boxes and fields are those of what they held then. @@ -2501,7 +2501,7 @@ struct Opened { source: Result, rustgis_data::DataError>, /// Its features read whole, when Add Data loads the file instead of keeping it in place (it /// holds few enough, and `"stream"` isn't given), so the window doesn't wait for that read. - whole: Option>, + pub(crate) whole: Option>, } #[cfg(not(target_arch = "wasm32"))] @@ -2545,7 +2545,8 @@ fn file_stamp(path: &str) -> Option(s: &mut Session, key: &str) -> Option { read.value.downcast::().ok().map(|v| *v) } +/// What `read` prepared, when it is a `T`, for a test to look at before it lands. +#[cfg(test)] +pub(crate) fn prepared(read: &Read) -> Option<&T> { + read.ready.as_ref()?.value.downcast_ref::() +} + /// Whether a read is placed for `key`, without taking it. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn placed_for(s: &Session, key: &str) -> bool { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0c5125bd05..75086980e5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -48452,6 +48452,10 @@ fn a_large_file_of_few_features_is_loaded_ahead() { let ahead = crate::cmd::reads::read_ahead(&mut s, "layer.addData", &json!({"path": path.display().to_string()})).unwrap(); assert!(ahead.reads(), "opened ahead"); let read = ahead.run(&Control::new()).unwrap(); + // Read whole on the read thread, before the command lands it. + let opened = crate::cmd::reads::prepared::(&read).expect("an opening made ahead"); + let whole = opened.whole.as_ref().expect("read whole ahead").as_ref().unwrap(); + assert_eq!(whole.0.features.len(), 1000); let id = crate::cmd::reads::read_land(&mut s, read).unwrap()["layer"].as_u64().unwrap() as u32; assert!(s.read_ahead.is_none(), "the read was taken"); let layer = s.map().layer(id).unwrap(); From 29aed271035066da40882efe8ecc722a2927420c Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 20:17:20 -0600 Subject: [PATCH 5/6] fix(data): a dangling link beside a file opened ahead is left out of its stamp; whole GeoJSON reads count progress (#2446) A name that names no file, or a file system without modification times, no longer turns off taking an opening made ahead. A whole GeoJSON read and the pass converting a declared coordinate system count their progress. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/source/geojson.rs | 17 +++++++++++------ crates/engine/src/cmd/layer.rs | 24 ++++++++++++++---------- crates/engine/src/cmd/reads.rs | 3 ++- 3 files changed, 27 insertions(+), 17 deletions(-) diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 0c3df90d12..21c4009615 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -283,8 +283,9 @@ impl FeatureSource for GeoJsonSource { } /// Reads a bounded sample; when native bounds are refused, filters geometry before sampling, - /// counting records and checking Cancel between them. Otherwise Cancel is looked at every - /// [`PACE`] features read, so a whole read (Add Data loading the file) stops between them. + /// counting records and checking Cancel between them. A whole read (no extent, every match: + /// Add Data loading the file) counts and looks at Cancel likewise; other reads look at Cancel + /// every [`PACE`] features. fn read(&self, req: &Request) -> Result { let limit = clamp_limit(req.limit); // Counted first, then sampled, unless the native box is refused: no list of every match. @@ -303,11 +304,13 @@ impl FeatureSource for GeoJsonSource { let mut buf = Vec::new(); let mut features = Vec::with_capacity(matched.div_ceil(step).min(limit)); let mut skipped = 0; - if late { - crate::progress::begin(matched); + // A whole read counts its features as a refused box does; a view's sample only looks. + let counted = late || (req.extent.is_none() && step == 1); + if counted { + crate::progress::begin(if late { matched } else { matched.min(limit) }); } for (n, i) in self.matches(extent).step_by(step).take(if late { usize::MAX } else { limit }).enumerate() { - if late { + if counted { crate::progress::step(1)?; } else if n.is_multiple_of(PACE) { crate::progress::check()?; @@ -408,9 +411,11 @@ fn convert_pass(path: &Path, places: &[Place], t: &crate::raster::Transformer) - let mut f = BufReader::with_capacity(BUFFER, crate::provenance::open(path)?); let (mut pos, mut buf) = (0u64, Vec::new()); let mut pass = Pass { failed: Vec::new(), dropped: [0; 3], extent: Extent::EMPTY }; + // Counted as a step of its own, a feature at a time every so many. + crate::progress::begin(places.len()); for (i, place) in places.iter().enumerate() { if i.is_multiple_of(PACE) { - crate::progress::check()?; + crate::progress::step(if i == 0 { 0 } else { PACE })?; } // A feature that can't be read now is left to the reads, which skip it. if let Some(json) = read_place(&mut f, &mut pos, &mut buf, place) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 08b9b6d5d2..eb6c1d732d 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2473,7 +2473,7 @@ fn read_synced(path: &str, read: impl FnOnce() -> WholeRead) -> WholeRead { Ok((ds, report)) } -/// Whether Add Data reads the Shapefile at `path` in place: as `p` says (with +/// Whether Add Data reads the Shapefile at `path` in place: as `p` says (the callers pass it with /// [`past_cap_shapefile`] applied), else when it holds more records than /// [`STREAM_ABOVE`](rustgis_map::source::STREAM_ABOVE). #[cfg(not(target_arch = "wasm32"))] @@ -2497,7 +2497,7 @@ pub(crate) struct Opened { /// The size and modification time of the file and those beside it of its name (a /// Shapefile's `.dbf`, `.prj` and `.cpg`) as it was opened: an opening of files changed since /// isn't taken, as its features' places, boxes and fields are those of what they held then. - stamp: Option>, + stamp: Option)>>, source: Result, rustgis_data::DataError>, /// Its features read whole, when Add Data loads the file instead of keeping it in place (it /// holds few enough, and `"stream"` isn't given), so the window doesn't wait for that read. @@ -2531,10 +2531,12 @@ impl Opened { } } -/// The size and modification time of `path` and of the files beside it with the same name before -/// the extension, in any case (a Shapefile's parts), by name; `None` when any can't be read. +/// The size and modification time (where the file system keeps one) of `path` and of the files +/// beside it with the same name before the extension, in any case (a Shapefile's parts), by name. +/// One that names no file (a dangling link) is left out, as the opening can't read it either; +/// `None` when the folder can't be listed or another can't be looked at. #[cfg(not(target_arch = "wasm32"))] -fn file_stamp(path: &str) -> Option> { +fn file_stamp(path: &str) -> Option)>> { let path = Path::new(path); let stem = path.file_stem()?.to_str()?; let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); @@ -2546,9 +2548,11 @@ fn file_stamp(path: &str) -> Option stamp.push((name, m.len(), m.modified().ok())), + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return None, } } stamp.sort(); @@ -2577,8 +2581,8 @@ fn in_place_key(path: &str, crs: Option<&str>) -> String { /// decides ([`streams_geojson`], [`streams_shapefile`]), but a `.json` of at most 256 MiB given a /// coordinate system or a layer, which may be a city model told as it is added, so it is opened /// there as before. -/// Cancel is looked at every few thousand features or records; a file read into memory to be -/// scanned (a GeoJSON file of at most 256 MiB) is read in one step without a look. +/// Cancel is looked at every few thousand features or records; reading a GeoJSON file of at most +/// 256 MiB into memory, before its text is scanned, is one step without a look. #[cfg(not(target_arch = "wasm32"))] fn in_place_ahead(p: &Value, path: &str) -> Option { const NAME: &str = "Add Data"; diff --git a/crates/engine/src/cmd/reads.rs b/crates/engine/src/cmd/reads.rs index f92882ad9d..b70249c85e 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -1,6 +1,7 @@ //! Reads the desktop app makes on a thread of its own before a command adds what they read //! (#1291 step 3): Add Data's whole-file reads (a raster, a raster GDAL converts, a GeoJSON, -//! delimited text or spreadsheet read whole, a ZIP or CityJSON/CityGML model's layers), Repair/Reload Data, Load All +//! delimited text or spreadsheet read whole, a ZIP or CityJSON/CityGML model's layers, the opening +//! of a large Shapefile or GeoJSON file read in place, #2446), Repair/Reload Data, Load All //! Features, Convert To Annotation's read of a layer read in place, native models or scripts, the //! Error Inspector's topology check (#1291), Source File State's hashing of a layer's file and Column Statistics' count of a column. [`read_ahead`] //! takes what the read needs of the session, [`ReadAhead::run`] reads on the thread, and [`read_land`] From 8ccd7599e0dd2050f6fc171586f5746714151fdc Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 20:34:07 -0600 Subject: [PATCH 6/6] fix(data): the conversion pass looks at Cancel again after the merge with main (#2446) main made convert_pass return its pass directly; it returns a Result again so its look at Cancel stops the opening. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/source/geojson.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 9e2af0c371..43fb694783 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -238,7 +238,7 @@ impl GeoJsonSource { let mut extent = scan.extent; if let Some(t) = reproject.transformer() { file.rewind()?; - let pass = convert_pass(&mut file, &scan.places, t); + let pass = convert_pass(&mut file, &scan.places, t)?; extent = pass.extent; for (kept, lost) in scan.kinds.iter_mut().zip(pass.dropped) { *kept = kept.saturating_sub(lost); @@ -487,7 +487,7 @@ struct Pass { } /// A second pass over the file, made only for a declared coordinate system. -fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transformer) -> Pass { +fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transformer) -> Result { let mut f = BufReader::with_capacity(BUFFER, file); let (mut pos, mut buf) = (0u64, Vec::new()); let mut pass = Pass { failed: Vec::new(), dropped: [0; 3], extent: Extent::EMPTY }; @@ -512,7 +512,7 @@ fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transforme } } } - pass + Ok(pass) } /// A reader counting the bytes read through it, for features' places in the file. The JSON reader