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
9 changes: 4 additions & 5 deletions crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6366,7 +6366,8 @@ fn merc_area_perimeter(mp: &MultiPolygon<f64>) -> (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
Expand Down Expand Up @@ -6398,8 +6399,7 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, String>
}
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(
Expand Down Expand Up @@ -6457,8 +6457,7 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, String>
}
}
_ => {
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) {
Expand Down
14 changes: 14 additions & 0 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<const N: usize>(&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<Item = &'a Feature> {
self.features.iter().enumerate().filter(|(r, _)| rows.get(*r).copied().unwrap_or(true)).map(|(_, f)| f)
Expand Down
109 changes: 104 additions & 5 deletions crates/data/src/row_access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,54 @@ 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) {
// 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;
}

/// [`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. 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
/// 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`, even while a cache holds their
/// [`Features::allocation_key`]: that key stops matching, and nothing is copied.
pub fn try_add_columns<E>(&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);
// 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);
f.attrs.extend(added.clone());
}
return Ok(());
}
self.before_copy();

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.

Low-severity, and the same order as before this PR (the old for row in &mut ds.features also fired the hook before its first check). Here before_copy() runs before the first step(), so a Cancel at row 0 frees older Undo steps (via before_rows_copy) even though the layer is left unchanged. The hook's doc says an edit that fails before writing keeps them. Taking the first step before the hook would keep Undo history on an immediate Cancel, e.g. by calling step() once ahead of the loop and the hook after it. Worth a look, not a blocker.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Left for the release quality pass.

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).
Expand Down Expand Up @@ -178,7 +221,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<Feature> {
self.before_copy();
Expand Down Expand Up @@ -316,6 +360,61 @@ mod tests {
assert_eq!(ds.features.row(2).map(|r| r.values().cloned().collect::<Vec<_>>()), 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 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();
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();
Expand Down
14 changes: 6 additions & 8 deletions crates/engine/src/cmd/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`]).

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.

Wording nit: "A table's runs ahead on a worker" is missing its noun. Suggested wording:

Suggested change
// A table's runs ahead on a worker, with progress and Cancel ([`table_ahead`]).
// A table's edit runs ahead on a worker, with progress and Cancel ([`table_ahead`]).

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Left for the release quality pass.

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)
}

Expand Down
2 changes: 1 addition & 1 deletion xtask/memory-limits.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion xtask/row-uses.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading