From c7d2676a006a7073d33445011e17ed1e2c4786c4 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 12:29:36 -0600 Subject: [PATCH 1/3] perf(data): Add Field copies a shared layer once, at its new length Adding a field to a layer an Undo step shares copied every row and then grew each row's values by one slot. The second allocation left the first as a gap that rows of the same length can't fill, so the layer was held about twice over. A shared layer's rows are now copied once, each at its new length (`Features::add_columns`, `try_add_columns`), and `Dataset::ensure_fields` adds several missing fields in one pass, which Calculate Geometry uses for its two fields. On the Hennepin County parcels (448,126 features, 121 fields) Add Field peaks at 3,676 MiB instead of 4,921, and Calculate Geometry at 3,725 instead of 4,969. `cargo xtask memory`'s calculate scenario drops from 3.06 to 2.74 times the baseline; its limit comes down to 2.98. Part of #2431. --- crates/analysis/src/tools.rs | 6 +-- crates/data/src/lib.rs | 14 ++++++ crates/data/src/row_access.rs | 92 +++++++++++++++++++++++++++++++++-- crates/engine/src/cmd/edit.rs | 14 +++--- xtask/memory-limits.txt | 2 +- xtask/row-uses.txt | 2 +- 6 files changed, 111 insertions(+), 19 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 97f20a8753..f6e2057d02 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -6398,8 +6398,7 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result } match ds.geometry_type { GeometryType::Polygon => { - let fa = out.ensure_field("area_km2", FieldType::Double); - let fp = out.ensure_field("perimeter_km", FieldType::Double); + let [fa, fp] = out.ensure_fields([("area_km2", FieldType::Double), ("perimeter_km", FieldType::Double)]); // Each feature's measures made on several cores for many (#1252), placed in their order. crate::control::begin(ds.features.len()); let measured = crate::parallel::try_map( @@ -6457,8 +6456,7 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result } } _ => { - let fx = out.ensure_field("point_x", FieldType::Double); - let fy = out.ensure_field("point_y", FieldType::Double); + let [fx, fy] = out.ensure_fields([("point_x", FieldType::Double), ("point_y", FieldType::Double)]); for f in &mut out.features { let c = f.geometry.as_ref().and_then(|g| g.label_point()); if let Some(v) = f.attrs.get_mut(fx) { diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index e9319f24c3..00f7a3230a 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -1384,6 +1384,20 @@ impl Dataset { self.fields.len() - 1 } + /// [`Dataset::ensure_field`] for several fields, returning their indices in order. The missing + /// ones are added together, so each row changes once however many there are. + pub fn ensure_fields(&mut self, fields: [(&str, FieldType); N]) -> [usize; N] { + let before = self.fields.len(); + let at = fields.map(|(name, ty)| { + self.field_index(name).unwrap_or_else(|| { + self.fields.push(Field::new(name, ty)); + self.fields.len() - 1 + }) + }); + self.features.add_columns(self.fields.len() - before, Value::Null); + at + } + /// The features `rows` keeps, by position; a row past its end counts, so `&[]` keeps them all. pub fn kept_features<'a>(&'a self, rows: &'a [bool]) -> impl Iterator { self.features.iter().enumerate().filter(|(r, _)| rows.get(*r).copied().unwrap_or(true)).map(|(_, f)| f) diff --git a/crates/data/src/row_access.rs b/crates/data/src/row_access.rs index 8ad36651fd..bf8c1ef35f 100644 --- a/crates/data/src/row_access.rs +++ b/crates/data/src/row_access.rs @@ -102,11 +102,49 @@ impl Features { /// Adds a column after the last, holding `value` in every row (Add Field): one new column /// when values are kept by column, not a change to every row. pub fn add_column(&mut self, value: Value) { - for f in self.rows_mut() { - // Exactly one more slot: a doubled capacity in every row would cost more than the column. - f.attrs.reserve_exact(1); - f.attrs.push(value.clone()); + self.add_columns(1, value); + } + + /// Adds `n` columns after the last, each holding `value` in every row: several fields added at + /// once, with each row changed once rather than once per field. + pub fn add_columns(&mut self, n: usize, value: Value) { + let done: Result<(), std::convert::Infallible> = self.try_add_columns(n, value, || Ok(())); + let Ok(()) = done; + } + + /// [`Features::add_columns`], calling `step` before each row (for progress and Cancel); its + /// error ends the change there, leaving shared rows as they were and rows of its own with the + /// columns in the rows before. + /// + /// Rows another owner shares (an Undo snapshot) are copied once, each at its new length. Copied + /// first and then grown, every row would take a second allocation and leave the first as a gap + /// that rows of the same length can't fill: on a large layer, about one more copy of it held + /// (#2431). Rows of its own grow in place by exactly `n`. + pub fn try_add_columns(&mut self, n: usize, value: Value, mut step: impl FnMut() -> Result<(), E>) -> Result<(), E> { + if n == 0 { + return Ok(()); + } + let added = std::iter::repeat_n(value, n); + if let Some(rows) = Arc::get_mut(&mut self.rows) { + for f in rows { + step()?; + // Exactly `n` more slots: a doubled capacity in every row would cost more than the columns. + f.attrs.reserve_exact(n); + f.attrs.extend(added.clone()); + } + return Ok(()); } + self.before_copy(); + let mut copy = Vec::with_capacity(self.rows.len()); + for f in self.rows.iter() { + step()?; + let mut attrs = Vec::with_capacity(f.attrs.len().saturating_add(n)); + attrs.extend_from_slice(&f.attrs); + attrs.extend(added.clone()); + copy.push(Feature { id: f.id, geometry: f.geometry.clone(), attrs }); + } + self.rows = Arc::new(copy); + Ok(()) } /// Removes column `field` from every row that has it (Delete Field). @@ -178,7 +216,8 @@ impl Features { } /// The rows for a change, copied first when another owner (an Undo snapshot) shares them. - /// Every change goes through it, so the hook [`crate::before_rows_copy`] sets runs before a + /// Every change goes through it, or calls `before_copy` itself where it copies the rows its own + /// way ([`Features::try_add_columns`]), so the hook [`crate::before_rows_copy`] sets runs before a /// copy, as it does through `DerefMut`. fn rows_mut(&mut self) -> &mut Vec { self.before_copy(); @@ -316,6 +355,49 @@ mod tests { assert_eq!(ds.features.row(2).map(|r| r.values().cloned().collect::>()), Some(vec![Value::Int(9), Value::Null])); } + #[test] + fn a_column_stopped_part_way_leaves_shared_rows_as_they_were() { + let ds = layer(); + let mut copy = ds.features.clone(); + // Cancelled at the second row. + let mut asked = 0; + let step = || { + asked += 1; + if asked == 2 { Err("cancelled") } else { Ok(()) } + }; + assert_eq!(copy.try_add_columns(1, Value::Int(0), step), Err("cancelled")); + assert!(copy.shares(&ds.features)); + // Rows of its own take the column in place. + let mut own: Features = ds.features.to_rows().into(); + own.add_column(Value::Int(0)); + assert!(own.rows().all(|r| r.value(2) == &Value::Int(0))); + // Shared rows are copied at their new length, with the same values. + copy.add_column(Value::Int(0)); + assert!(!copy.shares(&ds.features)); + assert_eq!(copy.to_rows(), own.to_rows()); + assert!(copy.iter().all(|f| f.attrs.len() == f.attrs.capacity())); + assert!(ds.features.rows().all(|r| r.values().len() == 2)); + } + + #[test] + fn fields_added_together_change_each_row_once() { + let mut ds = layer(); + let shared = ds.features.clone(); + // A name already there keeps its index; one given twice is added once. + assert_eq!( + ds.ensure_fields([("a", FieldType::Double), ("n", FieldType::Text), ("b", FieldType::Double), ("a", FieldType::Text)]), + [2, 1, 3, 2] + ); + assert_eq!(ds.fields.len(), 4); + assert!(ds.features.rows().all(|r| r.values().len() == 4 && r.value(2).is_null() && r.value(3).is_null())); + assert!(ds.features.iter().all(|f| f.attrs.len() == f.attrs.capacity())); + assert!(shared.rows().all(|r| r.values().len() == 2)); + // Nothing missing: nothing changes, and the rows stay shared. + let shared = ds.features.clone(); + assert_eq!(ds.ensure_fields([("b", FieldType::Double)]), [3]); + assert!(ds.features.shares(&shared)); + } + #[test] fn removing_rows_keeps_them_dense_and_ids_fresh() { let mut ds = layer(); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9070f2437a..d52dfc07e0 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1080,14 +1080,12 @@ fn add_field(s: &mut Session, p: &Json) -> CmdResult { if table { rustgis_data::progress::begin(ds.features.len()); } - for row in &mut ds.features { - if table { - rustgis_data::progress::step(1).map_err(|e| e.to_string())?; - } - // Adding one column to shared rows should not double every row's attribute capacity. - row.attrs.reserve_exact(1); - row.attrs.push(Value::Null); - } + // A table's runs ahead on a worker, with progress and Cancel ([`table_ahead`]). + ds.features.try_add_columns( + 1, + Value::Null, + || if table { rustgis_data::progress::step(1).map_err(|e| e.to_string()) } else { Ok(()) }, + )?; Ok(Json::Null) } diff --git a/xtask/memory-limits.txt b/xtask/memory-limits.txt index 111553abd6..a016b80139 100644 --- a/xtask/memory-limits.txt +++ b/xtask/memory-limits.txt @@ -7,7 +7,7 @@ # ratio divides by, so a loader that held more can't pass by lowering them. load_mib = 200.00 join = 2.10 -calculate = 3.15 +calculate = 2.98 export = 1.75 edits_2 = 2.75 edits_24 = 17.85 diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 5eff209857..9b9e9b2c53 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 766 +count = 764 From 05c54f7b4d85e0346dd3151b2da8f1f690fc63fc Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 13:00:38 -0600 Subject: [PATCH 2/3] fix(data): rows under a cache's key take a column in place, not by copy Arc::get_mut refuses while any weak reference lives, and map caches hold the rows' allocation_key, so a layer no other owner shared was copied whole. Branch on the strong count instead: with one owner the rows move out from under the key uncopied, as Arc::make_mut did before. --- crates/data/src/row_access.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/data/src/row_access.rs b/crates/data/src/row_access.rs index bf8c1ef35f..c481851ec1 100644 --- a/crates/data/src/row_access.rs +++ b/crates/data/src/row_access.rs @@ -108,6 +108,7 @@ impl Features { /// Adds `n` columns after the last, each holding `value` in every row: several fields added at /// once, with each row changed once rather than once per field. pub fn add_columns(&mut self, n: usize, value: Value) { + // A step that never fails: the change can't stop part way. let done: Result<(), std::convert::Infallible> = self.try_add_columns(n, value, || Ok(())); let Ok(()) = done; } @@ -119,14 +120,17 @@ impl Features { /// Rows another owner shares (an Undo snapshot) are copied once, each at its new length. Copied /// first and then grown, every row would take a second allocation and leave the first as a gap /// that rows of the same length can't fill: on a large layer, about one more copy of it held - /// (#2431). Rows of its own grow in place by exactly `n`. + /// (#2431). Rows of its own grow in place by exactly `n`, even while a cache holds their + /// [`Features::allocation_key`]: that key stops matching, and nothing is copied. pub fn try_add_columns(&mut self, n: usize, value: Value, mut step: impl FnMut() -> Result<(), E>) -> Result<(), E> { if n == 0 { return Ok(()); } let added = std::iter::repeat_n(value, n); - if let Some(rows) = Arc::get_mut(&mut self.rows) { - for f in rows { + // The strong count, not `Arc::get_mut`, which also refuses while a cache's weak key is + // alive: with no other owner, `rows_mut` moves the rows out from under the key uncopied. + if Arc::strong_count(&self.rows) == 1 { + for f in self.rows_mut() { step()?; // Exactly `n` more slots: a doubled capacity in every row would cost more than the columns. f.attrs.reserve_exact(n); @@ -379,6 +383,18 @@ mod tests { assert!(ds.features.rows().all(|r| r.values().len() == 2)); } + #[test] + fn a_column_added_to_rows_of_its_own_under_a_cache_key_copies_nothing() { + let mut ds = layer(); + let rows = ds.features.as_slice().as_ptr(); + let key = ds.features.allocation_key(); + ds.features.add_column(Value::Null); + // The same rows, moved rather than copied, and the key no longer matches them. + assert_eq!(ds.features.as_slice().as_ptr(), rows); + assert!(!std::sync::Weak::ptr_eq(&key, &ds.features.allocation_key())); + assert!(ds.features.rows().all(|r| r.values().len() == 3)); + } + #[test] fn fields_added_together_change_each_row_once() { let mut ds = layer(); From 5410d03aa804791df1c5bf2dd15d6c2cf914b668 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 13:30:42 -0600 Subject: [PATCH 3/3] docs(data): say where adding fields can't stop part way Calculate Geometry's doc names its field copy as a step without a Cancel check, and try_add_columns says a caller that added the fields first drops the dataset on an error. --- crates/analysis/src/tools.rs | 3 ++- crates/data/src/row_access.rs | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index f6e2057d02..dc1e932c95 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -6366,7 +6366,8 @@ fn merc_area_perimeter(mp: &MultiPolygon) -> (f64, f64) { /// Calculate Geometry Attributes: adds `area_km2` and `perimeter_km` to a polygon layer (see /// [`ground_area_perimeter`]), `length_km` to a line layer, and `point_x`/`point_y` (a label point) /// to any other, updating the layer in place. Polygon measurements and ambiguity counts check -/// Cancel between features; measuring one feature's rings is an uninterruptible step. +/// Cancel between features; measuring one feature's rings is an uninterruptible step, and so is +/// adding the fields, which copies the layer's rows once when another owner shares them. /// /// In a layer's own projected system ([`Inputs::work_crs`]) the point's x and y are that system's, /// in its unit, as the layer holds them; areas and lengths are still measured on the ground, each diff --git a/crates/data/src/row_access.rs b/crates/data/src/row_access.rs index c481851ec1..7054da05ec 100644 --- a/crates/data/src/row_access.rs +++ b/crates/data/src/row_access.rs @@ -115,7 +115,8 @@ impl Features { /// [`Features::add_columns`], calling `step` before each row (for progress and Cancel); its /// error ends the change there, leaving shared rows as they were and rows of its own with the - /// columns in the rows before. + /// columns in the rows before. A caller that added the fields first drops the dataset on an + /// error, as Add Field's table edit does with its copy. /// /// Rows another owner shares (an Undo snapshot) are copied once, each at its new length. Copied /// first and then grown, every row would take a second allocation and leave the first as a gap