Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4333,7 +4333,7 @@ pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option<usize>, t
Ok(match ext {
"csv" => {
// Of the longitude/latitude the file is written in.
let ds = ds.in_lonlat().map_err(DataError::Format)?;
let ds = ds.in_lonlat().map_err(DataError::of_conversion)?;
let losses = CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)?;
let mut notes = losses.notes(&ds.fields, target);
notes.extend(losses.coordinates_note(&ds.fields, target));
Expand Down
150 changes: 115 additions & 35 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,14 @@ pub enum DataError {

pub type Result<T> = std::result::Result<T, DataError>;

impl DataError {
/// A coordinate conversion's error ([`Dataset::in_lonlat`], [`Dataset::hold_in`], …, which
/// say it in words): [`DataError::Cancelled`] when it stopped for Cancel, else a format error.
pub fn of_conversion(e: String) -> Self {
if e == DataError::Cancelled.to_string() { DataError::Cancelled } else { DataError::Format(e) }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quality (confidence about 40%): cancel is recognised by comparing the error text.

of_conversion (and sync_error in crates/engine/src/cmd/workspace.rs) decide "this was a cancel" by e == DataError::Cancelled.to_string(). That works today because stop_when_asked produces the same string, but it means the classification depends on an #[error("cancelled")] display string staying in sync, and any other Format error with that exact text would be misread as a cancel.

This is not a bug at present, and the string return type of in_lonlat / hold_in probably makes a typed error a larger change than this PR should carry. Worth a follow-up: return DataError from the conversion helpers, or keep the string but match on a shared constant rather than on the rendered message.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed it's string-based, kept deliberately: in_lonlat/hold_in return String like the other conversion helpers, and the text compared is DataError::Cancelled's own display, not a copy, so they can't drift apart; no other conversion error reads "cancelled". A typed error for the conversion helpers is a wider change than this PR; noted for C2.

}
}

/// An I/O error, or [`DataError::Cancelled`] when it carries one: a write that only returns I/O
/// errors stops with it for a cancelled run ([`progress`]).
impl From<std::io::Error> for DataError {
Expand Down Expand Up @@ -448,8 +456,8 @@ impl Dataset {
/// Drawing converts geometry from it ([`raster::Crs::to`]), so a dataset that keeps the
/// coordinates it was read in can say so here without the map changing. Longitude/latitude
/// never fails to convert, and [`Dataset::hold_in`] only holds a dataset where every place
/// converts. A place that can't be converted isn't drawn, and the session says so
/// ([`Dataset::unplaced_in_lonlat`]).
/// converts. A place that can't be converted isn't drawn, and the session says so (the map
/// counts them as it draws, `Layer::unplaced`).
pub fn coord_crs(&self) -> raster::Crs {
self.held_in
}
Expand All @@ -466,8 +474,11 @@ impl Dataset {
let to = self.held_in.to(crs)?;
if !to.is_identity() {
let lonlat = self.lonlat_conversion()?;
// Before the rows are copied (by the first change), which a cancelled command needn't.
stop_when_asked(0)?;
let mut features = self.features.clone();
for f in &mut features {
for (i, f) in features.iter_mut().enumerate() {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
stop_when_asked(i)?;
if let Some(g) = &f.geometry {
let mut past = false;
if crs == raster::Crs::WebMercator {
Expand Down Expand Up @@ -978,30 +989,6 @@ impl Dataset {
}
}

/// How many of its features have a place that can't be given in longitude/latitude, which
/// the map, the globe and the drawings made from either leave out: none while its coordinates
/// are longitude/latitude, as every dataset's are today. Refused, naming its system, when the
/// system can't be converted at all (then none of it is drawn). It reads every place through
/// the conversion, on the calling thread, with no Cancel: as long as converting the layer
/// takes.
pub fn unplaced_in_lonlat(&self) -> std::result::Result<usize, String> {
let to = self.lonlat_conversion()?;
if to.is_identity() {
return Ok(0);
}
// Counted, not converted: a place that isn't a number is kept, as a conversion keeps it.
let unplaced = |g: &Geometry| {
let lost = std::cell::Cell::new(false);
g.for_each_coord(|c| {
if !lost.get() && c.is_finite() && to.point(c).is_none() {
lost.set(true);
}
});
lost.get()
};
Ok(self.features.rows().filter_map(|r| r.geometry()).filter(|g| unplaced(g)).count())
}

/// The dataset in longitude/latitude, the space analysis tools work in: borrowed while its
/// coordinates are longitude/latitude ([`Dataset::coord_crs`]), as every dataset's are today;
/// otherwise a copy with every geometry converted, missing coordinates kept. Refused, naming
Expand All @@ -1012,9 +999,11 @@ impl Dataset {
if to.is_identity() {
return Ok(Cow::Borrowed(self));
}
stop_when_asked(0)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question on behaviour (about 35% confidence): Serialize for a held dataset can now fail with a cancel.

in_lonlat now honours Cancel, and Dataset::serialize (crates/data/src/lib.rs around L606) calls in_lonlat() for every held, non-windowed dataset, mapping the error with serde::ser::Error::custom. So a save or other serialization that runs while the thread's progress is cancelled now fails with the text cancelled inside a serde error. Before this PR it always succeeded, and the error is no longer DataError::Cancelled, so the of_conversion mapping used elsewhere doesn't apply.

I could not trace every caller from here. Please check whether any serialization runs under an installed progress (a cancellable command, a background copy) and whether it should report a cancel as a cancel. If so, a serialization path that must not stop should ignore Cancel, or the error should be mapped back to DataError::Cancelled.

@pick2510 pick2510 Nov 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intended, no change. Cancel is installed only around a cancellable write (progress::install: a save, an export, a background copy), so a serialization that sees it is one the user asked to stop, and failing it is what Cancel means: a save stopped part-way leaves no file half-written. A save's error is shown as its text, "cancelled", as for the other writes. Serialization outside such a write (undo, the clipboard, a project read back in memory) has no progress installed and never stops.

let mut out = self.clone();
out.held_in = raster::Crs::LonLat;
for f in &mut out.features {
for (i, f) in out.features.iter_mut().enumerate() {
stop_when_asked(i)?;
if let Some(g) = &mut f.geometry {
*g = convert_keeping_missing(&to, g, &HeldPlaces::default()).ok_or_else(|| {
format!(
Expand Down Expand Up @@ -1056,12 +1045,16 @@ impl Dataset {
let mut held = HeldPlaces::default();
let edits: Vec<&Geometry> = results.features.rows().filter_map(|r| r.geometry()).collect();
if !edits.is_empty() {
held.want_only(&edits);
for g in self.features.rows().filter_map(|r| r.geometry()) {
held.want_only_checking(&edits, stop_when_asked)?;
for (i, g) in self.features.rows().filter_map(|r| r.geometry()).enumerate() {
stop_when_asked(i)?;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
self.hold_places(g, None, &mut held);
}
}
for f in &mut results.features {
// Before the rows are copied out of what shares them.
stop_when_asked(0)?;
for (i, f) in results.features.iter_mut().enumerate() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance (about 35% confidence): Cancel is checked after the rows are copied here too.

results.features.iter_mut() goes through DerefMut, which copies shared rows before the first stop_when_asked(i) in the loop. hold_in and in_lonlat were fixed for this, but results_from_lonlat and merged_from_lonlat (about line 1093) weren't. A cancelled write whose results or merged shares rows with another owner copies the whole layer before it stops. Rows that are not shared cost nothing, so the impact is limited.

Small fix, same as in hold_in:

Suggested change
for (i, f) in results.features.iter_mut().enumerate() {
stop_when_asked(0)?;
for (i, f) in results.features.iter_mut().enumerate() {

Apply the same line before for (i, f) in merged.features.iter_mut().enumerate() { in merged_from_lonlat.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 456fb98: results_from_lonlat and merged_from_lonlat check Cancel before the copy loop, as hold_in and in_lonlat do.

stop_when_asked(i)?;
if let Some(g) = f.geometry.take() {
f.geometry = Some(self.edit_from_lonlat(g, &held).map_err(|e| format!("{}: feature {}: {e}", self.name, f.id))?);
}
Expand Down Expand Up @@ -1093,12 +1086,16 @@ impl Dataset {
// edits would bound.
let mut held = HeldPlaces::default();
if !edits.is_empty() {
held.want_only(&edits);
for g in self.features.iter().filter_map(|f| f.geometry.as_ref()) {
held.want_only_checking(&edits, stop_when_asked)?;
for (i, g) in self.features.iter().filter_map(|f| f.geometry.as_ref()).enumerate() {
stop_when_asked(i)?;
self.hold_places(g, None, &mut held);
}
}
for f in &mut merged.features {
// Before the rows are copied out of what shares them.
stop_when_asked(0)?;
for (i, f) in merged.features.iter_mut().enumerate() {
stop_when_asked(i)?;
if is_changed(f.id) {
if let Some(g) = f.geometry.take() {
f.geometry = Some(self.edit_from_lonlat(g, &held).map_err(|e| format!("{}: feature {}: {e}", self.name, f.id))?);
Expand Down Expand Up @@ -1218,15 +1215,27 @@ impl HeldPlaces {
/// From now on, holds only places that one of `edited`'s (in longitude/latitude) reads as and
/// that isn't held yet: a search of many stored places keeps only those an edit asks for.
pub fn want_only(&mut self, edited: &[&Geometry]) {
self.want_only_checking(edited, |_| Ok(())).unwrap_or_default();
}

/// [`HeldPlaces::want_only`], stopping when `check` (given each edit's index) says so, the
/// places wanted left as they were.
fn want_only_checking(
&mut self,
edited: &[&Geometry],
mut check: impl FnMut(usize) -> std::result::Result<(), String>,
) -> std::result::Result<(), String> {
let mut wanted = std::collections::HashSet::new();
for g in edited {
for (i, g) in edited.iter().enumerate() {
check(i)?;
g.for_each_coord(|c| {
if c.is_finite() && self.get(c).is_none() {
wanted.insert(Self::key(c));
}
});
}
self.wanted = Some(wanted);
Ok(())
}

/// The held place that reads exactly as `c` in longitude/latitude.
Expand All @@ -1243,6 +1252,17 @@ impl HeldPlaces {
}
}

/// Stops a conversion of a whole layer once the command running it was asked to (looked at every
/// 256 features): a layer's conversion takes as long as the layer is large. A single feature
/// converts whole between looks, however many vertices it has (a long coastline is not stopped
/// partway).
fn stop_when_asked(i: usize) -> std::result::Result<(), String> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quality / error classification (medium-low confidence, about 50%). stop_when_asked returns the cancel as a String ("cancelled"), so Dataset::in_lonlat and hold_in now return a plain error for a cancelled run. Some callers wrap that string in a different error. crates/data/src/io.rs:4328 (export_losses_notes) maps it to DataError::Format, and crates/data/src/publish.rs:305 reports it as a refusal. Code that matches DataError::Cancelled directly (for example crates/data/src/sync.rs:207 and io.rs:3222) won't recognise these as cancels. The display text is still "cancelled", so users see the same words, but the classification is lost.

Consider having those callers check progress::check() after an Err and return DataError::Cancelled, or converting the cancel to a typed error on this path. Not a blocker.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 07523b4: DataError::of_conversion maps the cancel back to DataError::Cancelled (any other text stays Format), and the callers that wrapped the string (io.rs export notes, publish.rs) go through it. Tested in crates/data/src/lib.rs.

if i.is_multiple_of(256) {
progress::check().map_err(|e| e.to_string())?;
}
Ok(())
}

/// An edit `g` in longitude/latitude in the target system, as [`convert_keeping_missing`], a held
/// place written as held; `None` also when it reaches past 85.05° for Web Mercator, which would
/// hold the place at 85.05°, where it ends, rather than refuse it.
Expand Down Expand Up @@ -1309,6 +1329,66 @@ mod tests {
assert_eq!(window.coord_crs(), raster::Crs::LonLat);
}

/// A whole layer's conversion stops once its command is cancelled, part-way through as well as
/// before it starts, leaving the dataset as it was; without a cancel it runs to the end.
#[test]
fn a_whole_layer_conversion_stops_when_cancelled() {
use std::sync::atomic::Ordering;
let utm = raster::Crs::Epsg(32632);
let mut ds = Dataset::new("held", GeometryType::Point, vec![]);
for i in 0..600 {
ds.push(Some(Geometry::Point(Coord::new(11.0 + f64::from(i) * 1e-4, 48.7))), vec![]);
}
let plain = ds.clone();
// Cancelled before it starts, or once asked `n` times.
let before = || {
let probe = std::sync::Arc::new(progress::tests::Counted::default());
probe.cancel.store(true, Ordering::Relaxed);
progress::install(Some(probe))
};
let at =
|n: u64| progress::install(Some(std::sync::Arc::new(progress::tests::Counted { after_checks: Some(n), ..Default::default() })));
// A conversion checks before its loop, then at features 0, 256 and 512: the third check
// stops it at feature 256, part-way.
let midway = || at(2);
// A write-back first looks over its edits (checks at edits 0, 256 and 512 of 600; at the
// one edit of a merge changing one feature), reads the held places (checks at features
// 0, 256 and 512), then checks before its copy and at features 0 and 256 of it: the copy
// stops at feature 256, part-way.
let results_midway = || at(8);
let merge_midway = || at(6);
for cancel in [&before as &dyn Fn() -> progress::Installed, &midway] {
let _cancelled = cancel();
assert!(ds.hold_in(utm).is_err());
assert_eq!(ds, plain, "a cancelled hold leaves the dataset as it was");
}
ds.hold_in(utm).unwrap();
let held = ds.clone();
let merged = ds.in_lonlat().unwrap().into_owned();
type Cancel<'a> = &'a dyn Fn() -> progress::Installed;
for (cancel, results, merge) in
[(&before as Cancel, &before as Cancel, &before as Cancel), (&midway, &results_midway, &merge_midway)]
{
{
let _cancelled = cancel();
assert!(ds.in_lonlat().is_err());
}
{
let _cancelled = results();
assert!(ds.results_from_lonlat(merged.clone()).is_err());
}
{
let _cancelled = merge();
assert!(ds.merged_from_lonlat(merged.clone(), &std::collections::HashSet::from([1])).is_err());
}
assert_eq!(ds, held);
}
let _cancelled = before();
// Said in words, read back as a cancel by those that wrap it.
assert!(matches!(ds.in_lonlat().map_err(DataError::of_conversion), Err(DataError::Cancelled)));
assert!(matches!(DataError::of_conversion("no such system".into()), DataError::Format(_)));
}

/// A merge in longitude/latitude written back to a held dataset: what it left as it was stays
/// as stored, a changed feature keeps the places it didn't move, and only a moved or new place
/// is converted.
Expand Down
12 changes: 9 additions & 3 deletions crates/data/src/progress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,17 @@ pub(crate) mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

/// A probe that counts, and is cancelled when told or (with `after`) once that many items
/// were counted.
/// A probe that counts, and is cancelled when told, (with `after`) once that many items
/// were counted, or (with `after_checks`) once asked that many times, for a loop that only
/// checks.
#[derive(Default)]
pub(crate) struct Counted {
pub(crate) cancel: AtomicBool,
pub(crate) done: AtomicU64,
pub(crate) total: AtomicU64,
pub(crate) after: Option<u64>,
pub(crate) after_checks: Option<u64>,
pub(crate) checks: AtomicU64,
}

impl Counted {
Expand All @@ -120,7 +123,10 @@ pub(crate) mod tests {

impl Probe for Counted {
fn cancelled(&self) -> bool {
self.cancel.load(Ordering::Relaxed) || self.after.is_some_and(|n| self.done.load(Ordering::Relaxed) >= n)
let asked = self.checks.fetch_add(1, Ordering::Relaxed);
self.cancel.load(Ordering::Relaxed)
|| self.after.is_some_and(|n| self.done.load(Ordering::Relaxed) >= n)
|| self.after_checks.is_some_and(|n| asked >= n)
}
fn begin(&self, total: u64) {
self.total.store(total, Ordering::Relaxed);
Expand Down
5 changes: 4 additions & 1 deletion crates/data/src/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,10 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result<Published
let (read_back, _) = crate::io::read_shapefile_parts(back, &name, crs)?;
// Read back in longitude/latitude, so compared with the layer in it, whatever system the
// layer holds its coordinates in.
let in_lonlat = ds.in_lonlat().map_err(|e| refused(path, e))?;
let in_lonlat = ds.in_lonlat().map_err(|e| match DataError::of_conversion(e) {
DataError::Format(e) => refused(path, e),
cancelled => cancelled,
})?;
if let Some(why) = same_rows(&in_lonlat, &read_back, if crs.is_some() { PROJECTED_TOLERANCE } else { 0.0 }) {
return Err(refused(path, format!("the file couldn't hold the layer as it is: {why}")));
}
Expand Down
83 changes: 83 additions & 0 deletions crates/engine/examples/held_bench.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
//! Times a large line layer held in longitude/latitude against the same layer held in UTM 32N
//! (#2032 C2): holding it, converting it back for a tool, the first frame, a change of
//! projection, panning and zooming:
//! `cargo run --release -p rustgis-engine --example held_bench -- [vertices, default 1000000]`.
use rustgis_data::raster::Crs;
use rustgis_data::{Coord, Dataset, Geometry, GeometryType};
use rustgis_engine::render::{View, render};
use rustgis_engine::{Project, Session};
use rustgis_geom::extent_to_merc;
use rustgis_map::Camera;
use serde_json::json;
use std::time::Instant;

/// Lines of 1000 vertices each, zigzagging across a degree around 11.5°E 48.7°N.
fn lines(vertices: usize) -> Dataset {
let mut d = Dataset::new("lines", GeometryType::Polyline, vec![]);
let per = 1000;
for k in 0..vertices.div_ceil(per) {
let y = 48.2 + (k as f64 * 0.618_033).fract();
// The last line has what is left, so the layer has the vertices asked for.
let n = (vertices - k * per).min(per);
let run = (0..n).map(|i| Coord::new(11.0 + i as f64 / per as f64, y + if i % 2 == 0 { 1e-4 } else { -1e-4 })).collect();
d.push(Some(Geometry::Line(vec![run])), vec![]);
}
d
}

fn ms(t: Instant) -> f64 {
t.elapsed().as_secs_f64() * 1000.0
}

fn main() -> Result<(), String> {
let vertices: usize = std::env::args().nth(1).and_then(|v| v.parse().ok()).unwrap_or(1_000_000);
println!("{vertices} vertices; times in ms");
println!("{:<34}{:>12}{:>12}", "", "lon/lat", "UTM 32N");
let mut rows: Vec<(&str, [f64; 2])> = Vec::new();
let mut put = |what: &'static str, i: usize, v: f64| match rows.iter_mut().find(|r| r.0 == what) {
Some(r) => r.1[i] = v,
None => {
let mut r = (what, [f64::NAN; 2]);
r.1[i] = v;
rows.push(r);
}
};
for (i, crs) in [Crs::LonLat, Crs::Epsg(32632)].into_iter().enumerate() {
let mut d = lines(vertices);
let t = Instant::now();
d.hold_in(crs)?;
put("hold in its system", i, ms(t));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AGENTS.md (no unwrap()/expect() in non-test code), low-medium confidence (~45%). The bench has five of them: here (hold_in), line 52 (in_lonlat), line 65 (render(...).expect), and lines 74–75 (s.run). If the maintainers treat examples as exempt, ignore this. Otherwise make main return Result<(), String> and use ?, mapping the Option from render to an error:

fn main() -> Result<(), String> {

and replace each .unwrap() with ? (for render, .ok_or("a frame")?).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1492a4e: main returns Result<(), String>, each step uses ?, and a missing frame is an error (ok_or).

let t = Instant::now();
let back = d.in_lonlat()?;
put("in longitude/latitude (a tool)", i, ms(t));
drop(back);
let mut s = Session::new(Project::default());
s.map_mut().layers.clear();
s.map_mut().add_dataset(d);
let e = extent_to_merc(&s.map().full_extent());
let (w, h) = (1600.0, 1000.0);
let res = (e.width() / w).max(e.height() / h);
let mut camera = Camera { center: Coord::new((e.min_x + e.max_x) / 2.0, (e.min_y + e.max_y) / 2.0), res, bearing: 0.0, pitch: 0.0 };
let frame = |s: &mut Session, camera: Camera| {
let view = View { width: w, height: h, pixels_per_point: 1.0, camera, sky: false };
let t = Instant::now();
render(s.map_mut(), &view).ok_or("no frame")?;
Ok::<_, String>(ms(t))
};
put("first frame (Web Mercator)", i, frame(&mut s, camera)?);
put("next frame", i, frame(&mut s, camera)?);
camera.center.x += e.width() / 10.0;
put("pan", i, frame(&mut s, camera)?);
camera.res /= 4.0;
put("zoom in 4x", i, frame(&mut s, camera)?);
s.run("map.projection", &json!({"type": "epsg:3035"}))?;
s.run("layer.zoomTo", &json!({"layer": "lines"}))?;
let camera = s.map().camera;
put("first frame after projection change", i, frame(&mut s, camera)?);
put("next frame (EPSG:3035)", i, frame(&mut s, camera)?);
}
for (what, [a, b]) in rows {
println!("{what:<34}{a:>12.1}{b:>12.1}");
}
Ok(())
}
Loading
Loading