From 6440e8c8dcfbb3ad6eafc29464b727339a2051aa Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 12:35:27 -0600 Subject: [PATCH 1/4] perf(data): an export to longitude/latitude converts each place once, on several threads Exporting a layer held in a projected system to longitude/latitude converted every vertex twice on one thread: once for the layer's box (lonlat_extent) and again to write the file (project_each_leaving_out). The conversion that writes the file now also gives the box, converts each geometry where it lies instead of copying it, and runs on several threads from 8192 features on (rustgis_data::threads; one thread below that and in the browser). Each thread looks at Cancel between pieces of 512 features and counts them toward the progress. The file written is unchanged, and the box is exactly lonlat_extent's: places that can't be converted are left out of it. --- crates/data/src/export.rs | 2 +- crates/data/src/geometry.rs | 10 ++ crates/data/src/io.rs | 188 +++++++++++++++++++++----- crates/data/src/unplaced_out_tests.rs | 47 +++++++ crates/engine/src/cmd/share.rs | 9 +- 5 files changed, 217 insertions(+), 39 deletions(-) diff --git a/crates/data/src/export.rs b/crates/data/src/export.rs index 3bd5de4ce8..392e38bf3a 100644 --- a/crates/data/src/export.rs +++ b/crates/data/src/export.rs @@ -303,7 +303,7 @@ fn write_chunks_as( if let Some(t) = &t { // Counted by the source scan, so only stopped on a cancel here. A feature with a // place the export's system can't hold is written without its geometry, and said. - unplaced = unplaced.saturating_add(project_each_leaving_out(&mut chunk, t, false)?); + unplaced = unplaced.saturating_add(project_each_leaving_out(&mut chunk, t, false)?.0); } total = total.saturating_add(chunk.len()); null_numbers = null_numbers.saturating_add(numbers_written_as_null(&chunk, &layer.fields, ext)); diff --git a/crates/data/src/geometry.rs b/crates/data/src/geometry.rs index 7a6b26266b..faa7df5a06 100644 --- a/crates/data/src/geometry.rs +++ b/crates/data/src/geometry.rs @@ -164,6 +164,16 @@ impl Geometry { } } + /// Calls `f` with every coordinate, to change it where it lies. + pub fn for_each_coord_mut(&mut self, mut f: impl FnMut(&mut Coord)) { + match self { + Geometry::Point(c) => f(c), + Geometry::MultiPoint(v) => v.iter_mut().for_each(f), + Geometry::Line(parts) => parts.iter_mut().flatten().for_each(f), + Geometry::Polygon(polys) => polys.iter_mut().flatten().flatten().for_each(f), + } + } + /// Whether every coordinate is a number: none is NaN (which some writers use for an empty /// point) or infinite, which have no place and which a saved project can't hold (#1985). pub fn is_finite(&self) -> bool { diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 6db7769c20..aa9ba8aa81 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -708,58 +708,155 @@ pub(crate) fn project_features(features: &mut [crate::Feature], to: &crate::rast /// written without its geometry, rather than failing the export; returns how many were /// ([`unplaced_export_note`]). pub fn project_leaving_out(ds: &Dataset, crs: Crs) -> Result<(Dataset, usize)> { + project_leaving_out_placed(ds, crs).map(|(out, unplaced, _)| (out, unplaced)) +} + +/// [`project_leaving_out`], also giving the box of the places converted, in `crs`: `None` when +/// nothing was converted (the dataset is in `crs`, or the conversion is the identity). +fn project_leaving_out_placed(ds: &Dataset, crs: Crs) -> Result<(Dataset, usize, Option)> { let from = ds.coord_crs(); if crs == from { - return Ok((ds.clone(), 0)); + return Ok((ds.clone(), 0, None)); } let mut out = ds.clone(); let to = from.to(crs).map_err(DataError::Format)?; crate::progress::begin(out.features.len()); - let unplaced = project_each_leaving_out(&mut out.features, &to, true)?; + let (unplaced, placed) = project_each_leaving_out(&mut out.features, &to, true)?; out.held_in = crs; - Ok((out, unplaced)) + Ok((out, unplaced, (!to.is_identity()).then_some(placed))) } /// [`project_each`] for an export: a feature with a place the target can't hold loses its -/// geometry rather than failing; returns how many did. A coordinate that is missing already (NaN, -/// infinite) stays missing, as [`crate::Dataset::in_lonlat`] keeps it, and loses nothing. -pub(crate) fn project_each_leaving_out(features: &mut [crate::Feature], to: &crate::raster::Reprojection, count: bool) -> Result { +/// geometry rather than failing; returns how many did, and the box of every place converted +/// ([`Reprojection::point`] of each coordinate, a missing one included, leaving out those that +/// can't be converted): for a target of longitude/latitude, exactly +/// [`crate::Dataset::lonlat_extent_of`] the features as they were, so an export takes it from this +/// one conversion. A coordinate that is missing already (NaN, infinite) stays missing, as +/// [`crate::Dataset::in_lonlat`] keeps it, and loses nothing. +/// +/// From [`PARALLEL_FEATURES`] features on, the features are converted on several threads +/// ([`crate::threads::max`]), each written as one thread would write it, so the output is the +/// same bit for bit; one thread below that and in the browser. Each thread looks at Cancel +/// between its pieces, and counts them toward the progress when `count` is set. +/// +/// [`Reprojection::point`]: crate::raster::Reprojection::point +pub(crate) fn project_each_leaving_out( + features: &mut [crate::Feature], + to: &crate::raster::Reprojection, + count: bool, +) -> Result<(usize, rustgis_geom::Extent)> { + let threads = conversion_threads(features.len()); + #[cfg(not(target_arch = "wasm32"))] + if threads > 1 { + return project_pieces_leaving_out(features, to, count, threads); + } + let _ = threads; let mut unplaced = 0usize; + let mut placed = rustgis_geom::Extent::EMPTY; for f in features { if count { crate::progress::step(1)?; } else { crate::progress::check()?; } - if let Some(g) = f.geometry.take() { - // A coordinate that isn't a number is kept as it is: converting it could give it a - // place (Web Mercator takes an infinite latitude to 85.05°). - let out = if to.is_identity() { - g.clone() - } else { - g.map_coords(&|c| if c.is_finite() { to.point(c).unwrap_or(Coord::new(f64::NAN, f64::NAN)) } else { c }) - }; - if lost_a_place(&g, &out) { - unplaced += 1; - } else { - f.geometry = Some(out); + unplaced += usize::from(leave_out_unplaced(f, to, &mut placed)); + } + Ok((unplaced, placed)) +} + +/// The features from which [`project_each_leaving_out`] converts on several threads: about a +/// millisecond of a point layer's work, so a thread's start costs little against its share. +const PARALLEL_FEATURES: usize = 8192; +/// The features a thread of [`project_each_leaving_out`] takes at a time. +#[cfg(not(target_arch = "wasm32"))] +const PIECE_FEATURES: usize = 512; + +/// The threads to convert `n` features on: one below [`PARALLEL_FEATURES`] and in the browser, +/// else [`crate::threads::max`], no more than one per [`PARALLEL_FEATURES`] / 4 features. +fn conversion_threads(n: usize) -> usize { + if cfg!(target_arch = "wasm32") || n < PARALLEL_FEATURES { 1 } else { crate::threads::max().min(n / (PARALLEL_FEATURES / 4)).max(1) } +} + +/// [`project_each_leaving_out`] on `threads` threads, this one among them: each takes the next +/// [`PIECE_FEATURES`] features until none are left, one has failed or the run is cancelled (the +/// run's probe installed on each). The boxes of the pieces are joined in their order. A thread +/// the OS refuses leaves its share to the others; one that panics passes its panic on. +#[cfg(not(target_arch = "wasm32"))] +fn project_pieces_leaving_out( + features: &mut [crate::Feature], + to: &crate::raster::Reprojection, + count: bool, + threads: usize, +) -> Result<(usize, rustgis_geom::Extent)> { + use std::sync::Mutex; + use std::sync::atomic::{AtomicBool, Ordering}; + let pieces = features.len().div_ceil(PIECE_FEATURES); + let next = Mutex::new(features.chunks_mut(PIECE_FEATURES).enumerate()); + let done: Mutex> = Mutex::new(vec![(0, rustgis_geom::Extent::EMPTY); pieces]); + let failure: Mutex> = Mutex::new(None); + let failed = AtomicBool::new(false); + let probe = crate::progress::current(); + let work = || { + let _probe = crate::progress::install(probe.clone()); + while !failed.load(Ordering::Relaxed) { + // The lock is held only to take a piece; a poisoned one means a thread panicked. + let Some((k, piece)) = next.lock().ok().and_then(|mut n| n.next()) else { break }; + let looked = if count { crate::progress::step(piece.len()) } else { crate::progress::check() }; + if let Err(e) = looked { + failed.store(true, Ordering::Relaxed); + if let Ok(mut f) = failure.lock() { + f.get_or_insert(e); + } + break; + } + let mut placed = rustgis_geom::Extent::EMPTY; + let unplaced = piece.iter_mut().map(|f| usize::from(leave_out_unplaced(f, to, &mut placed))).sum(); + if let Some(slot) = done.lock().ok().as_mut().and_then(|d| d.get_mut(k)) { + *slot = (unplaced, placed); + } + } + }; + std::thread::scope(|scope| { + let others: Vec<_> = (1..threads).filter_map(|_| std::thread::Builder::new().spawn_scoped(scope, work).ok()).collect(); + work(); + for h in others { + if let Err(p) = h.join() { + std::panic::resume_unwind(p); } } + }); + if let Some(e) = failure.into_inner().ok().flatten() { + return Err(e); } - Ok(unplaced) + let done = done.into_inner().map_err(|_| DataError::Format("the features couldn't be converted".into()))?; + Ok(done.iter().fold((0, rustgis_geom::Extent::EMPTY), |(n, e), (u, p)| (n + u, e.union(p)))) } -/// Whether `out`, `g` converted place for place, lost a place: one that was a number in `g` and -/// isn't in `out`. -fn lost_a_place(g: &Geometry, out: &Geometry) -> bool { - let mut was = Vec::new(); - g.for_each_coord(|c| was.push(c.is_finite())); - let mut k = 0usize; +/// Converts `f`'s geometry with `to`, place for place where it lies, or leaves it out when a place +/// that was a number has none in the target, returning whether it was; `placed` takes in every +/// place converted, as [`project_each_leaving_out`] says. +fn leave_out_unplaced(f: &mut crate::Feature, to: &crate::raster::Reprojection, placed: &mut rustgis_geom::Extent) -> bool { + let Some(g) = f.geometry.as_mut() else { return false }; + if to.is_identity() { + return false; + } let mut lost = false; - out.for_each_coord(|c| { - lost |= was.get(k).copied().unwrap_or(true) && !c.is_finite(); - k += 1; + g.for_each_coord_mut(|c| { + let p = to.point(*c); + if let Some(p) = p { + placed.expand(p); + } + // A coordinate that isn't a number is kept as it is: converting it could give it a place + // (Web Mercator takes an infinite latitude to 85.05°). It still counts for the box, as + // `lonlat_extent_of` converts every coordinate. + if c.is_finite() { + *c = p.unwrap_or(Coord::new(f64::NAN, f64::NAN)); + lost |= !c.is_finite(); + } }); + if lost { + f.geometry = None; + } lost } @@ -959,7 +1056,7 @@ pub struct GpkgWritten { /// [`write_bytes_in`]). Refused on a place `crs` can't hold, naming its feature, as it gives no /// notes to say it; [`write_path_to`] writes the feature without its geometry instead, and says so. pub fn write_path_in(ds: &Dataset, path: &Path, crs: Crs) -> Result { - write_path_as(ds, path, crs, &GpkgTable::default(), false).map(|(left_out, _, _)| left_out) + write_path_as(ds, path, crs, &GpkgTable::default(), false).map(|(left_out, _, _, _)| left_out) } /// As [`write_path_in`], a GeoPackage's table placed as `gpkg` says (other formats ignore it): @@ -968,18 +1065,36 @@ pub fn write_path_in(ds: &Dataset, path: &Path, crs: Crs) -> Result { /// can't hold is written without its geometry, and the notes say how many /// ([`unplaced_export_note`]). pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> Result<(usize, Option, Vec)> { - write_path_as(ds, path, crs, gpkg, true) + write_path_as(ds, path, crs, gpkg, true).map(|(left_out, table, notes, _)| (left_out, table, notes)) +} + +/// [`write_path_to`], also giving the dataset's [`Dataset::lonlat_extent`]: taken from the +/// places converted for the file when it is written in longitude/latitude from another system, +/// so each is converted once, and otherwise from the dataset after the write. +pub fn write_path_placed( + ds: &Dataset, + path: &Path, + crs: Crs, + gpkg: &GpkgTable, +) -> Result<(usize, Option, Vec, rustgis_geom::Extent)> { + let (left_out, table, notes, placed) = write_path_as(ds, path, crs, gpkg, true)?; + let extent = match placed { + Some(e) if crs == Crs::LonLat => e, + _ => ds.lonlat_extent(), + }; + Ok((left_out, table, notes, extent)) } /// [`write_path_to`], leaving out a geometry `crs` can't hold (`leaving_out`, said in the notes) -/// or refusing it ([`write_path_in`]). +/// or refusing it ([`write_path_in`]); also the box, in `crs`, of the places converted when they +/// were left out that way ([`project_each_leaving_out`]), `None` when none were converted. fn write_path_as( ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable, leaving_out: bool, -) -> Result<(usize, Option, Vec)> { +) -> Result<(usize, Option, Vec, Option)> { let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); if crs != Crs::LonLat && PROJECTED_FORMATS.contains(&ext.as_str()) { check_projected(&ext, crs)?; @@ -989,10 +1104,11 @@ fn write_path_as( // when that is `crs`, and when `crs` is one the format can't hold, which is refused below. A // feature with a place `crs` can't hold is written without its geometry, and said. let mut unplaced = 0; + let mut placed = None; let ds = if crs == ds.coord_crs() || (crs != Crs::LonLat && !holds_a_system(&ext)) { ds } else { - (projected, unplaced) = if leaving_out { project_leaving_out(ds, crs)? } else { (project(ds, crs)?, 0) }; + (projected, unplaced, placed) = if leaving_out { project_leaving_out_placed(ds, crs)? } else { (project(ds, crs)?, 0, None) }; &projected }; let unplaced = unplaced_export_note(&path.display().to_string(), &ds.name, unplaced, crs); @@ -1004,7 +1120,7 @@ fn write_path_as( // Every feature is written: a layer of several kinds of geometry gets a GEOMETRY // column, and one that declares no type takes its geometry's. let table = crate::source::gpkg::write_table_in(ds, path, crs, gpkg)?; - Ok((0, Some(table), unplaced.into_iter().collect())) + Ok((0, Some(table), unplaced.into_iter().collect(), placed)) } #[cfg(target_arch = "wasm32")] { @@ -1017,7 +1133,7 @@ fn write_path_as( let (parts, left_out) = shapefile_parts_in(ds, crs)?; let parts: Vec<(std::path::PathBuf, Vec)> = parts.into_iter().map(|(e, bytes)| (shapefile_part(path, e), bytes)).collect(); let kept = place_shapefile(path, &stage_shapefile(&parts)?)?; - Ok((left_out, None, unplaced.into_iter().chain(kept_backups_note(path, &kept)).collect())) + Ok((left_out, None, unplaced.into_iter().chain(kept_backups_note(path, &kept)).collect(), placed)) } _ if crs != Crs::LonLat && !holds_a_system(&ext) => { Err(DataError::Unsupported(format!(".{ext} in {} (it holds longitude/latitude only)", crs.label()))) @@ -1025,7 +1141,7 @@ fn write_path_as( _ => { let (bytes, left_out) = projected_bytes(ds, &ext, crs)?; write_atomic(path, &bytes)?; - Ok((left_out, None, unplaced.into_iter().collect())) + Ok((left_out, None, unplaced.into_iter().collect(), placed)) } } } diff --git a/crates/data/src/unplaced_out_tests.rs b/crates/data/src/unplaced_out_tests.rs index 5fde69ecac..92af83a31e 100644 --- a/crates/data/src/unplaced_out_tests.rs +++ b/crates/data/src/unplaced_out_tests.rs @@ -223,3 +223,50 @@ fn a_streamed_shapefile_keeps_what_a_whole_read_keeps() { let view = crate::source::FeatureSource::read(&src, &crate::source::Request { extent: Some(paris), limit: 10, own: None }).unwrap(); assert_eq!(view.features.len(), 1); } + +/// An export converts each place once and takes the layer's box from that conversion (#2032): +/// the box is [`Dataset::lonlat_extent`]'s exactly, a feature left out for a place it can't give +/// still counting its others, and a layer large enough for several threads is written as one +/// thread writes it, its threads stopping on Cancel. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_export_takes_its_box_from_its_one_conversion_on_any_number_of_threads() { + use crate::progress::tests::Counted; + let mut ds = lines(false); + for i in 0..30_000u32 { + let x = 300_000.0 + f64::from(i % 997) * 400.0; + let y = 4_000_000.0 + f64::from(i / 997) * 30_000.0; + let mut part = vec![Coord::new(x, y), Coord::new(x + 50.0, y + 75.0)]; + match i % 1000 { + // A place with no longitude/latitude: the feature is left out, its other place kept in the box. + 7 => part.push(Coord::new(1e9, y)), + // A missing place, kept as it is. + 11 => part.push(Coord::new(f64::NAN, f64::NAN)), + _ => {} + } + ds.push(Some(Geometry::Line(vec![part])), vec![Value::Text(i.to_string())]); + } + let to = ds.lonlat_conversion().unwrap(); + let mut threaded = ds.features.to_vec(); + let (unplaced, placed) = crate::io::project_each_leaving_out(&mut threaded, &to, true).unwrap(); + assert_eq!(unplaced, 30, "one feature in a thousand has a place it can't give"); + assert_eq!(placed, ds.lonlat_extent(), "the box lonlat_extent gives, from the one conversion"); + // The one-thread path, a piece too small for threads at a time, gives the same bit for bit. + let mut one = ds.features.to_vec(); + let mut by_one = (0, rustgis_geom::Extent::EMPTY); + for piece in one.chunks_mut(1000) { + let (n, e) = crate::io::project_each_leaving_out(piece, &to, false).unwrap(); + by_one = (by_one.0 + n, by_one.1.union(&e)); + } + assert_eq!(by_one, (unplaced, placed)); + assert_eq!(format!("{threaded:?}"), format!("{one:?}")); + // Cancel reaches the threads: the run stops after the pieces under way, short of the end. + let probe = Counted::cancelling_after(1); + let _g = crate::progress::install(Some(probe.clone())); + crate::progress::begin(ds.features.len()); + let mut cancelled = ds.features.to_vec(); + let e = crate::io::project_each_leaving_out(&mut cancelled, &to, true).unwrap_err(); + assert!(matches!(e, crate::DataError::Cancelled), "{e}"); + let done = probe.done.load(std::sync::atomic::Ordering::Relaxed); + assert!(done < ds.features.len() as u64, "stopped short of the end: {done}"); +} diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 6fc42dd184..236c37e0d3 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -722,6 +722,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: // Whether a CSV has coordinate columns: a streamed layer that declares no type takes its // first geometry's, which the chunks written say. let mut csv_points = ds.geometry_type == rustgis_data::GeometryType::Point; + let mut lonlat_extent = None; let (written, left_out, skipped, table, unfit, null_numbers, moved, format_notes, dates) = match &chunks { Some((src, layer)) => { let (e, table) = rustgis_data::export::write_source_filtered(src.as_ref(), layer, Path::new(&path), crs, &gpkg, query) @@ -767,7 +768,11 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: None => { let mut format_notes = rustgis_data::io::export_losses_notes_in(ds, &ext, rustgis_data::io::name_field(ds), path, crs) .map_err(|e| e.to_string())?; - let (left_out, table, placed) = rustgis_data::io::write_path_to(ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())?; + // The layer's box in longitude/latitude comes back with the write, taken from the places + // converted for the file when it is written there, so each is converted once. + let (left_out, table, placed, lonlat) = + rustgis_data::io::write_path_placed(ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())?; + lonlat_extent = Some(lonlat); // Old parts of a Shapefile written over that couldn't be removed. format_notes.extend(placed); let unfit = if parquet { rustgis_data::source::parquet::values_note(ds, path) } else { None }; @@ -781,7 +786,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: // a chunk at a time has none at hand: its vertices beyond 85.05° in Web Mercator are counted // as they're written (`e.beyond_web_mercator`), and its source's extent only serves the // out-of-place check. A raster layer's extent is its raster's, which the file doesn't hold. - let extent = if chunks.is_some() { l.extent() } else { ds.lonlat_extent() }; + let extent = lonlat_extent.unwrap_or_else(|| l.extent()); let mut notes: rustgis_data::loss::Notes = rustgis_data::export_notes([(ds, extent)], path, crs); coalesce_read_zm(&mut notes, path, ds, &unreadable); notes.extend(default_note); From ad492274ae63ad0c9caafb7c38a371137dedcf6b Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 13:33:54 -0600 Subject: [PATCH 2/4] fix(data): the threaded export conversion asks the first place first, stops between features and gives a download its box The first feature with a place is converted on the calling thread before any worker starts, so the conversion's advisory missing-grid check sees the same first place as one thread does. Workers look at Cancel and count between features, and once more after they finish, so a Cancel that comes once every piece is taken still stops the run. write_bytes_noted returns the layer's longitude/latitude box from its conversion, and the browser download uses it instead of converting again. --- crates/data/src/io.rs | 94 ++++++++++++++++++++------- crates/data/src/unplaced_out_tests.rs | 16 ++++- crates/ui-egui/src/lib.rs | 8 +-- 3 files changed, 89 insertions(+), 29 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index aa9ba8aa81..ea9db904b3 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -737,7 +737,7 @@ fn project_leaving_out_placed(ds: &Dataset, crs: Crs) -> Result<(Dataset, usize, /// From [`PARALLEL_FEATURES`] features on, the features are converted on several threads /// ([`crate::threads::max`]), each written as one thread would write it, so the output is the /// same bit for bit; one thread below that and in the browser. Each thread looks at Cancel -/// between its pieces, and counts them toward the progress when `count` is set. +/// between features, and counts each toward the progress when `count` is set. /// /// [`Reprojection::point`]: crate::raster::Reprojection::point pub(crate) fn project_each_leaving_out( @@ -751,6 +751,16 @@ pub(crate) fn project_each_leaving_out( return project_pieces_leaving_out(features, to, count, threads); } let _ = threads; + project_one_by_one(features, to, count) +} + +/// [`project_each_leaving_out`] on this thread, looking at Cancel before each feature and +/// counting it when `count` is set. +fn project_one_by_one( + features: &mut [crate::Feature], + to: &crate::raster::Reprojection, + count: bool, +) -> Result<(usize, rustgis_geom::Extent)> { let mut unplaced = 0usize; let mut placed = rustgis_geom::Extent::EMPTY; for f in features { @@ -779,8 +789,16 @@ fn conversion_threads(n: usize) -> usize { /// [`project_each_leaving_out`] on `threads` threads, this one among them: each takes the next /// [`PIECE_FEATURES`] features until none are left, one has failed or the run is cancelled (the -/// run's probe installed on each). The boxes of the pieces are joined in their order. A thread -/// the OS refuses leaves its share to the others; one that panics passes its panic on. +/// run's probe installed on each), looking at Cancel and counting between features, and once more +/// after they all finish, so a Cancel that comes once every piece is taken still stops the run. +/// The boxes of the pieces are joined in their order. A thread the OS refuses leaves its share to +/// the others; one that panics passes its panic on. +/// +/// The features up to the first with a place go first, on this thread, so the conversion is asked +/// first for the place one thread asks first: its advisory missing-grid check looks only at the +/// first place it converts (terrio's `note_missing_grid`), and for a custom system with no EPSG +/// code nothing else asks earlier, so the notice of a missing grid would otherwise depend on which +/// thread got there first. #[cfg(not(target_arch = "wasm32"))] fn project_pieces_leaving_out( features: &mut [crate::Feature], @@ -790,6 +808,18 @@ fn project_pieces_leaving_out( ) -> Result<(usize, rustgis_geom::Extent)> { use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; + let first = features + .iter() + .position(|f| { + f.geometry.as_ref().is_some_and(|g| { + let mut any = false; + g.for_each_coord(|_| any = true); + any + }) + }) + .map_or(features.len(), |k| k + 1); + let (head, features) = features.split_at_mut(first); + let (head_unplaced, head_placed) = project_one_by_one(head, to, count)?; let pieces = features.len().div_ceil(PIECE_FEATURES); let next = Mutex::new(features.chunks_mut(PIECE_FEATURES).enumerate()); let done: Mutex> = Mutex::new(vec![(0, rustgis_geom::Extent::EMPTY); pieces]); @@ -798,19 +828,28 @@ fn project_pieces_leaving_out( let probe = crate::progress::current(); let work = || { let _probe = crate::progress::install(probe.clone()); - while !failed.load(Ordering::Relaxed) { + let stop = |e: DataError| { + failed.store(true, Ordering::Relaxed); + if let Ok(mut f) = failure.lock() { + f.get_or_insert(e); + } + }; + 'pieces: while !failed.load(Ordering::Relaxed) { // The lock is held only to take a piece; a poisoned one means a thread panicked. let Some((k, piece)) = next.lock().ok().and_then(|mut n| n.next()) else { break }; - let looked = if count { crate::progress::step(piece.len()) } else { crate::progress::check() }; - if let Err(e) = looked { - failed.store(true, Ordering::Relaxed); - if let Ok(mut f) = failure.lock() { - f.get_or_insert(e); - } + if let Err(e) = crate::progress::check() { + stop(e); break; } - let mut placed = rustgis_geom::Extent::EMPTY; - let unplaced = piece.iter_mut().map(|f| usize::from(leave_out_unplaced(f, to, &mut placed))).sum(); + let (mut unplaced, mut placed) = (0usize, rustgis_geom::Extent::EMPTY); + for f in piece { + unplaced += usize::from(leave_out_unplaced(f, to, &mut placed)); + let looked = if count { crate::progress::step(1) } else { crate::progress::check() }; + if let Err(e) = looked { + stop(e); + break 'pieces; + } + } if let Some(slot) = done.lock().ok().as_mut().and_then(|d| d.get_mut(k)) { *slot = (unplaced, placed); } @@ -828,8 +867,10 @@ fn project_pieces_leaving_out( if let Some(e) = failure.into_inner().ok().flatten() { return Err(e); } + // A Cancel that came after the last piece was taken, which no thread may have seen. + crate::progress::check()?; let done = done.into_inner().map_err(|_| DataError::Format("the features couldn't be converted".into()))?; - Ok(done.iter().fold((0, rustgis_geom::Extent::EMPTY), |(n, e), (u, p)| (n + u, e.union(p)))) + Ok(done.iter().fold((head_unplaced, head_placed), |(n, e), (u, p)| (n + u, e.union(p)))) } /// Converts `f`'s geometry with `to`, place for place where it lies, or leaves it out when a place @@ -967,8 +1008,9 @@ pub fn write_bytes_in(ds: &Dataset, ext: &str, crs: Crs) -> Result<(Vec, usi /// [`write_bytes_in`] for an export (named `name` in its notes): a feature with a place `crs` /// can't hold is written without its geometry ([`project_leaving_out`]), and the notes say how -/// many ([`unplaced_export_note`]). -pub fn write_bytes_noted(ds: &Dataset, ext: &str, crs: Crs, name: &str) -> Result<(Vec, usize, Vec)> { +/// many ([`unplaced_export_note`]). Also gives the dataset's [`Dataset::lonlat_extent`], as +/// [`write_path_placed`] does, so a download converts each place once too. +pub fn write_bytes_noted(ds: &Dataset, ext: &str, crs: Crs, name: &str) -> Result<(Vec, usize, Vec, rustgis_geom::Extent)> { let ext = ext.to_ascii_lowercase(); if crs != Crs::LonLat { if !holds_a_system(&ext) { @@ -978,11 +1020,21 @@ pub fn write_bytes_noted(ds: &Dataset, ext: &str, crs: Crs, name: &str) -> Resul } if crs == ds.coord_crs() { let (bytes, left_out) = projected_bytes(ds, &ext, crs)?; - return Ok((bytes, left_out, Vec::new())); + return Ok((bytes, left_out, Vec::new(), ds.lonlat_extent())); } - let (projected, unplaced) = project_leaving_out(ds, crs)?; + let (projected, unplaced, placed) = project_leaving_out_placed(ds, crs)?; let (bytes, left_out) = projected_bytes(&projected, &ext, crs)?; - Ok((bytes, left_out, unplaced_export_note(name, &ds.name, unplaced, crs).into_iter().collect())) + let notes = unplaced_export_note(name, &ds.name, unplaced, crs).into_iter().collect(); + Ok((bytes, left_out, notes, lonlat_extent_placed(ds, crs, placed))) +} + +/// `ds`'s [`Dataset::lonlat_extent`]: `placed`, the box of the places converted to `crs` for an +/// export, when `crs` is longitude/latitude, else worked out from `ds`. +fn lonlat_extent_placed(ds: &Dataset, crs: Crs, placed: Option) -> rustgis_geom::Extent { + match placed { + Some(e) if crs == Crs::LonLat => e, + _ => ds.lonlat_extent(), + } } /// [`write_bytes_in`] for a dataset already in `crs`'s coordinates. @@ -1078,11 +1130,7 @@ pub fn write_path_placed( gpkg: &GpkgTable, ) -> Result<(usize, Option, Vec, rustgis_geom::Extent)> { let (left_out, table, notes, placed) = write_path_as(ds, path, crs, gpkg, true)?; - let extent = match placed { - Some(e) if crs == Crs::LonLat => e, - _ => ds.lonlat_extent(), - }; - Ok((left_out, table, notes, extent)) + Ok((left_out, table, notes, lonlat_extent_placed(ds, crs, placed))) } /// [`write_path_to`], leaving out a geometry `crs` can't hold (`leaving_out`, said in the notes) diff --git a/crates/data/src/unplaced_out_tests.rs b/crates/data/src/unplaced_out_tests.rs index 92af83a31e..83e4371ae0 100644 --- a/crates/data/src/unplaced_out_tests.rs +++ b/crates/data/src/unplaced_out_tests.rs @@ -84,14 +84,14 @@ fn an_export_writes_a_feature_it_cant_place_without_its_geometry_and_says_so() { #[test] fn a_download_writes_a_feature_it_cant_place_without_its_geometry_and_says_so() { - let (bytes, left_out, notes) = crate::io::write_bytes_noted(&lines(true), "geojson", Crs::LonLat, "lines.geojson").unwrap(); + let (bytes, left_out, notes, _) = crate::io::write_bytes_noted(&lines(true), "geojson", Crs::LonLat, "lines.geojson").unwrap(); assert_eq!(left_out, 0); assert_eq!(notes.len(), 1, "{notes:?}"); assert!(notes[0].starts_with("lines.geojson: 1 feature(s) of lines have a place"), "{}", notes[0]); let (back, _) = crate::io::read_geojson(std::str::from_utf8(&bytes).unwrap(), "lines").unwrap(); assert_eq!(back.features.len(), 2); assert!(back.features[1].geometry.is_none()); - let (_, _, notes) = crate::io::write_bytes_noted(&lines(false), "geojson", Crs::LonLat, "clean.geojson").unwrap(); + let (_, _, notes, _) = crate::io::write_bytes_noted(&lines(false), "geojson", Crs::LonLat, "clean.geojson").unwrap(); assert!(notes.is_empty()); // The strict writer still refuses it, naming the feature. let e = crate::io::write_bytes_in(&lines(true), "geojson", Crs::LonLat).unwrap_err().to_string(); @@ -269,4 +269,16 @@ fn an_export_takes_its_box_from_its_one_conversion_on_any_number_of_threads() { assert!(matches!(e, crate::DataError::Cancelled), "{e}"); let done = probe.done.load(std::sync::atomic::Ordering::Relaxed); assert!(done < ds.features.len() as u64, "stopped short of the end: {done}"); + // A Cancel once every piece is taken still stops the run: with one feature left (the threads + // look between features) and, on several threads, after the last (looked at once they finish). + let n = ds.features.len() as u64; + let after = if crate::threads::max() > 1 { vec![n - 1, n] } else { vec![n - 1] }; + for after in after { + let probe = Counted::cancelling_after(after); + let _g = crate::progress::install(Some(probe.clone())); + crate::progress::begin(ds.features.len()); + let mut cancelled = ds.features.to_vec(); + let e = crate::io::project_each_leaving_out(&mut cancelled, &to, true).unwrap_err(); + assert!(matches!(e, crate::DataError::Cancelled), "cancelled after {after}: {e}"); + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index dd31c685bb..b5f8fa0d35 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5598,7 +5598,7 @@ impl RustGisApp { use rustgis_engine::data::io; let (crs, default_note) = io::default_export_in(&ds, &name, self.session.project.coordinate_system); let written = io::write_bytes_noted(&ds, &ext, crs, &name).map_err(|e| e.to_string()); - let (bytes, left_out, unplaced) = match written { + let (bytes, left_out, unplaced, extent) = match written { Ok(w) => w, Err(e) => { self.session.notify(e.clone(), true); @@ -5607,9 +5607,9 @@ impl RustGisApp { }; let ext = download_ext; // The features written, read whole, give their own extent, in longitude/latitude - // (not a raster's, or the one a streamed layer's source declares). - let mut notes: rustgis_engine::data::loss::Notes = - rustgis_engine::data::export_notes([(ds.as_ref(), ds.lonlat_extent())], &name, crs); + // (not a raster's, or the one a streamed layer's source declares), taken from the + // places converted for the download when it is written there. + let mut notes: rustgis_engine::data::loss::Notes = rustgis_engine::data::export_notes([(ds.as_ref(), extent)], &name, crs); rustgis_engine::cmd::share::coalesce_read_zm(&mut notes, &name, &ds, &lost); notes.extend(unplaced); // Which system it is written in, where that isn't the layer's own, as share.exportLayer says. From 711c5e2191afcb124d0219f8887342321215a02b Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 13:37:52 -0600 Subject: [PATCH 3/4] fix(data): a poisoned lock fails the threaded export conversion rather than skipping a piece Its test also says when the computer has several cores but the conversion got one thread. --- crates/data/src/io.rs | 30 +++++++++++++++++++++------ crates/data/src/unplaced_out_tests.rs | 2 ++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index ea9db904b3..d366ed7cdb 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -826,8 +826,11 @@ fn project_pieces_leaving_out( let failure: Mutex> = Mutex::new(None); let failed = AtomicBool::new(false); let probe = crate::progress::current(); + // A poisoned lock (a thread panicked holding it) fails the run rather than skip what it holds. + let poisoned = || DataError::Format("the features couldn't be converted".into()); let work = || { let _probe = crate::progress::install(probe.clone()); + // A poisoned `failure` loses `e`, but is itself an error once the threads finish. let stop = |e: DataError| { failed.store(true, Ordering::Relaxed); if let Ok(mut f) = failure.lock() { @@ -835,8 +838,15 @@ fn project_pieces_leaving_out( } }; 'pieces: while !failed.load(Ordering::Relaxed) { - // The lock is held only to take a piece; a poisoned one means a thread panicked. - let Some((k, piece)) = next.lock().ok().and_then(|mut n| n.next()) else { break }; + // The lock is held only to take a piece. + let taken = match next.lock() { + Ok(mut n) => n.next(), + Err(_) => { + stop(poisoned()); + break; + } + }; + let Some((k, piece)) = taken else { break }; if let Err(e) = crate::progress::check() { stop(e); break; @@ -850,8 +860,16 @@ fn project_pieces_leaving_out( break 'pieces; } } - if let Some(slot) = done.lock().ok().as_mut().and_then(|d| d.get_mut(k)) { - *slot = (unplaced, placed); + match done.lock() { + Ok(mut d) => { + if let Some(slot) = d.get_mut(k) { + *slot = (unplaced, placed); + } + } + Err(_) => { + stop(poisoned()); + break; + } } } }; @@ -864,12 +882,12 @@ fn project_pieces_leaving_out( } } }); - if let Some(e) = failure.into_inner().ok().flatten() { + if let Some(e) = failure.into_inner().map_err(|_| poisoned())? { return Err(e); } // A Cancel that came after the last piece was taken, which no thread may have seen. crate::progress::check()?; - let done = done.into_inner().map_err(|_| DataError::Format("the features couldn't be converted".into()))?; + let done = done.into_inner().map_err(|_| poisoned())?; Ok(done.iter().fold((head_unplaced, head_placed), |(n, e), (u, p)| (n + u, e.union(p)))) } diff --git a/crates/data/src/unplaced_out_tests.rs b/crates/data/src/unplaced_out_tests.rs index 83e4371ae0..3e2919d36d 100644 --- a/crates/data/src/unplaced_out_tests.rs +++ b/crates/data/src/unplaced_out_tests.rs @@ -247,6 +247,8 @@ fn an_export_takes_its_box_from_its_one_conversion_on_any_number_of_threads() { ds.push(Some(Geometry::Line(vec![part])), vec![Value::Text(i.to_string())]); } let to = ds.lonlat_conversion().unwrap(); + // Several threads wherever the computer has them, so the threaded path is what is checked. + assert!(crate::threads::cores() == 1 || crate::threads::max() > 1, "threads: {}", crate::threads::max()); let mut threaded = ds.features.to_vec(); let (unplaced, placed) = crate::io::project_each_leaving_out(&mut threaded, &to, true).unwrap(); assert_eq!(unplaced, 30, "one feature in a thousand has a place it can't give"); From c99fdc000edb3786e5d19ebe3873de5e8f20f898 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 14:25:32 -0600 Subject: [PATCH 4/4] fix(data): the threaded export conversion converts first, in its loop, up to the first place it converts A feature with no geometry, or only places that are missing or can't be converted, never reaches the conversion's first-place missing-grid check, so it no longer ends the part converted on the calling thread. That part is chosen in the conversion loop itself, which looks at Cancel and counts between features, so there is no separate pass over the geometries. --- crates/data/src/io.rs | 47 ++++++++++++++------------- crates/data/src/unplaced_out_tests.rs | 38 ++++++++++++++++++++++ 2 files changed, 62 insertions(+), 23 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index d366ed7cdb..a577145109 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -751,27 +751,37 @@ pub(crate) fn project_each_leaving_out( return project_pieces_leaving_out(features, to, count, threads); } let _ = threads; - project_one_by_one(features, to, count) + project_one_by_one(features, to, count, false).map(|(_, unplaced, placed)| (unplaced, placed)) } /// [`project_each_leaving_out`] on this thread, looking at Cancel before each feature and -/// counting it when `count` is set. -fn project_one_by_one( +/// counting it when `count` is set; with `until_placed`, only up to and including the first +/// feature with a place converted (one [`Reprojection::point`] gives), or all of them when none +/// has one. Returns how many features it converted, with what +/// [`project_each_leaving_out`] returns for them. +/// +/// [`Reprojection::point`]: crate::raster::Reprojection::point +pub(crate) fn project_one_by_one( features: &mut [crate::Feature], to: &crate::raster::Reprojection, count: bool, -) -> Result<(usize, rustgis_geom::Extent)> { + until_placed: bool, +) -> Result<(usize, usize, rustgis_geom::Extent)> { let mut unplaced = 0usize; let mut placed = rustgis_geom::Extent::EMPTY; - for f in features { + for (k, f) in features.iter_mut().enumerate() { if count { crate::progress::step(1)?; } else { crate::progress::check()?; } unplaced += usize::from(leave_out_unplaced(f, to, &mut placed)); + // `point` gives only finite places, each of which the box takes in. + if until_placed && !placed.is_empty() { + return Ok((k + 1, unplaced, placed)); + } } - Ok((unplaced, placed)) + Ok((features.len(), unplaced, placed)) } /// The features from which [`project_each_leaving_out`] converts on several threads: about a @@ -794,11 +804,12 @@ fn conversion_threads(n: usize) -> usize { /// The boxes of the pieces are joined in their order. A thread the OS refuses leaves its share to /// the others; one that panics passes its panic on. /// -/// The features up to the first with a place go first, on this thread, so the conversion is asked -/// first for the place one thread asks first: its advisory missing-grid check looks only at the -/// first place it converts (terrio's `note_missing_grid`), and for a custom system with no EPSG -/// code nothing else asks earlier, so the notice of a missing grid would otherwise depend on which -/// thread got there first. +/// The features up to the first with a place converted go first, in order on this thread, so the +/// conversion meets first the place one thread meets first: its advisory missing-grid check looks +/// only at the first place it converts (terrio's `note_missing_grid`), and for a custom system with +/// no EPSG code nothing else asks earlier, so the notice of a missing grid would otherwise depend +/// on which thread got there first. Features with no geometry, or only places that are missing or +/// can't be converted, never reach that check, so they don't end this part. #[cfg(not(target_arch = "wasm32"))] fn project_pieces_leaving_out( features: &mut [crate::Feature], @@ -808,18 +819,8 @@ fn project_pieces_leaving_out( ) -> Result<(usize, rustgis_geom::Extent)> { use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; - let first = features - .iter() - .position(|f| { - f.geometry.as_ref().is_some_and(|g| { - let mut any = false; - g.for_each_coord(|_| any = true); - any - }) - }) - .map_or(features.len(), |k| k + 1); - let (head, features) = features.split_at_mut(first); - let (head_unplaced, head_placed) = project_one_by_one(head, to, count)?; + let (first, head_unplaced, head_placed) = project_one_by_one(features, to, count, true)?; + let features = features.get_mut(first..).unwrap_or_default(); let pieces = features.len().div_ceil(PIECE_FEATURES); let next = Mutex::new(features.chunks_mut(PIECE_FEATURES).enumerate()); let done: Mutex> = Mutex::new(vec![(0, rustgis_geom::Extent::EMPTY); pieces]); diff --git a/crates/data/src/unplaced_out_tests.rs b/crates/data/src/unplaced_out_tests.rs index 3e2919d36d..9e8316a018 100644 --- a/crates/data/src/unplaced_out_tests.rs +++ b/crates/data/src/unplaced_out_tests.rs @@ -284,3 +284,41 @@ fn an_export_takes_its_box_from_its_one_conversion_on_any_number_of_threads() { assert!(matches!(e, crate::DataError::Cancelled), "cancelled after {after}: {e}"); } } + +/// The features a threaded export converts first on its own thread run up to the first with a +/// place converted, past those that never reach the conversion's first-place check: an empty +/// geometry, none, one only missing places and one only places that can't be converted (#2032). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_threaded_export_converts_first_up_to_the_first_place_it_can_convert() { + let mut ds = Dataset::new("lines", crate::GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + ds.held_in = utm31(); + ds.crs = Some(utm31()); + ds.push(Some(Geometry::Line(vec![])), vec![Value::Text("empty".into())]); + ds.push(None, vec![Value::Text("none".into())]); + ds.push(Some(Geometry::Line(vec![vec![Coord::new(f64::NAN, f64::NAN)]])), vec![Value::Text("missing".into())]); + ds.push(Some(Geometry::Line(vec![vec![Coord::new(1e9, 4e6)]])), vec![Value::Text("far".into())]); + for i in 0..10_000u32 { + let x = 300_000.0 + f64::from(i % 997) * 400.0; + let part = vec![Coord::new(x, 4_000_000.0), Coord::new(x + 50.0, 4_000_075.0)]; + ds.push(Some(Geometry::Line(vec![part])), vec![Value::Text(i.to_string())]); + } + let to = ds.lonlat_conversion().unwrap(); + let mut head = ds.features.to_vec(); + let (first, unplaced, placed) = crate::io::project_one_by_one(&mut head, &to, false, true).unwrap(); + assert_eq!((first, unplaced), (5, 1), "up to and including the first feature with a place converted"); + assert!(!placed.is_empty()); + // With nothing to convert, all of them, and no box. + let mut none = ds.features.to_vec(); + none.truncate(4); + let (first, _, placed) = crate::io::project_one_by_one(&mut none, &to, false, true).unwrap(); + assert_eq!(first, 4); + assert!(placed.is_empty()); + // On several threads, as on one. + let mut threaded = ds.features.to_vec(); + let got = crate::io::project_each_leaving_out(&mut threaded, &to, false).unwrap(); + let mut one = ds.features.to_vec(); + let (_, n, e) = crate::io::project_one_by_one(&mut one, &to, false, false).unwrap(); + assert_eq!(got, (n, e)); + assert_eq!(format!("{threaded:?}"), format!("{one:?}")); +}