diff --git a/crates/analysis/src/attribute_join.rs b/crates/analysis/src/attribute_join.rs index dc914abca1..42562d9b0e 100644 --- a/crates/analysis/src/attribute_join.rs +++ b/crates/analysis/src/attribute_join.rs @@ -204,12 +204,49 @@ fn written(v: &Value) -> String { JoinKey::from_value(v).map(|k| k.display()).unwrap_or_default() } +/// Validates windowed flags and key-field compatibility and returns the progress work units +/// (`source_len` + optional `NumberAsText` scan + `target_len`) that [`join_field`] will advance. +pub(crate) fn join_field_work( + target: &Dataset, + target_len: usize, + source: &Dataset, + source_len: usize, + target_field: &str, + join_field: &str, +) -> Result { + if target.windowed { + return Err("the target layer is streamed; load all features first".into()); + } + if source.windowed { + return Err("the source layer is streamed; load all features first".into()); + } + let target_key_idx = crate::tools::find_field_case_insensitive(target, target_field)?; + let source_key_idx = crate::tools::find_field_case_insensitive(source, join_field)?; + let target_key_field = target.fields.get(target_key_idx).ok_or_else(|| "target key field missing".to_string())?; + let source_key_field = source.fields.get(source_key_idx).ok_or_else(|| "source key field missing".to_string())?; + let comparison = key_comparison(target_key_field, source_key_field)?; + let extra_scan = if comparison == KeyComparison::NumberAsText { source_len } else { 0 }; + Ok(source_len.saturating_add(extra_scan).saturating_add(target_len)) +} + /// Executes a non-spatial attribute join from `source` onto `target`. /// /// Preserves target order, IDs, geometry, existing attributes, and the record count of the /// provided target dataset (when invoked through the tool, row selections are applied beforehand). /// Appends selected attributes from `source` based on matching key values. pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_>) -> Result<(Dataset, JoinFieldReport), String> { + join_field_with_progress(target, source, opts, false) +} + +/// Executes [`join_field`], optionally continuing an active `control::begin` step started by the +/// caller (used by `joinField` when partial selections copy rows beforehand so progress climbs +/// monotonically across subsetting and joining). +pub(crate) fn join_field_with_progress( + target: &Dataset, + source: &Dataset, + opts: &JoinFieldOptions<'_>, + progress_started: bool, +) -> Result<(Dataset, JoinFieldReport), String> { if target.windowed { return Err("the target layer is streamed; load all features first".into()); } @@ -278,33 +315,40 @@ pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_ } // 5. Index source records: Map JoinKey -> source feature index + let extra_scan = if comparison == KeyComparison::NumberAsText { source.features.len() } else { 0 }; + if !progress_started { + crate::control::begin(source.features.len().saturating_add(extra_scan).saturating_add(target.features.len())); + } + crate::control::check()?; let mut source_index: HashMap = HashMap::with_capacity(source.features.len()); let mut duplicate_count = 0usize; for (s_idx, s_feat) in source.features.iter().enumerate() { + crate::control::check()?; let val = s_feat.attrs.get(source_key_idx).unwrap_or(&Value::Null); - let Some(key) = JoinKey::from_value_compared(val, comparison) else { - // Null or non-finite keys in source cannot match - continue; - }; - - match source_index.entry(key) { - std::collections::hash_map::Entry::Occupied(mut occ) => { - duplicate_count += 1; - match opts.duplicate_strategy { - DuplicateStrategy::Error => { - return Err(format!("duplicate key {} found in source table under Error duplicate strategy", occ.key().display())); - } - DuplicateStrategy::First => {} - DuplicateStrategy::Last => { - occ.insert(s_idx); + if let Some(key) = JoinKey::from_value_compared(val, comparison) { + match source_index.entry(key) { + std::collections::hash_map::Entry::Occupied(mut occ) => { + duplicate_count += 1; + match opts.duplicate_strategy { + DuplicateStrategy::Error => { + return Err(format!( + "duplicate key {} found in source table under Error duplicate strategy", + occ.key().display() + )); + } + DuplicateStrategy::First => {} + DuplicateStrategy::Last => { + occ.insert(s_idx); + } } } - } - std::collections::hash_map::Entry::Vacant(vac) => { - vac.insert(s_idx); + std::collections::hash_map::Entry::Vacant(vac) => { + vac.insert(s_idx); + } } } + crate::control::advance(1); } // Source text keys with leading zeros, by their digits without them: a target number that @@ -312,11 +356,13 @@ pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_ let mut zero_padded_sources: HashMap = HashMap::new(); if comparison == KeyComparison::NumberAsText { for (s_idx, s_feat) in source.features.iter().enumerate() { + crate::control::check()?; if let Some(Value::Text(text)) = s_feat.attrs.get(source_key_idx) && let Some(digits) = without_leading_zeros(text) { zero_padded_sources.entry(digits.to_string()).or_insert(s_idx); } + crate::control::advance(1); } } let source_key_value = |s_idx: usize| source.features.get(s_idx).and_then(|f| f.attrs.get(source_key_idx)).unwrap_or(&Value::Null); @@ -329,6 +375,7 @@ pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_ let mut out_features = Vec::with_capacity(target_len); for t_feat in &target.features { + crate::control::check()?; if t_feat.attrs.len() > target.fields.len() { return Err(format!( "target feature {} has {} attributes, exceeding schema field count {}", @@ -376,6 +423,7 @@ pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_ } out_features.push(rustgis_data::Feature { id: t_feat.id, geometry: t_feat.geometry.clone(), attrs: new_attrs }); + crate::control::advance(1); } out.features = out_features.into(); @@ -1311,4 +1359,79 @@ mod tests { assert_eq!(out_col.fields[2].alias, None); assert_eq!(out_col.fields[2].display(), "cost_2"); } + + #[test] + fn test_join_field_checks_cancel_and_reports_progress() { + use crate::control::Control; + + // Case 1: Exact comparison (Integer vs Integer), 5 source rows (one Null key) + 5 target rows => total 10. + let target = make_table("target", vec![("id", FieldType::Integer)], (1..=5).map(|i| vec![Value::Int(i)]).collect()); + let source = make_table( + "source", + vec![("id", FieldType::Integer), ("tag", FieldType::Text)], + vec![ + vec![Value::Int(1), Value::Text("a".into())], + vec![Value::Int(2), Value::Text("b".into())], + vec![Value::Null, Value::Text("null".into())], + vec![Value::Int(4), Value::Text("d".into())], + vec![Value::Int(5), Value::Text("e".into())], + ], + ); + let opts = JoinFieldOptions { + target_field: "id", + join_field: "id", + fields_to_transfer: None, + prefix: "", + duplicate_strategy: DuplicateStrategy::First, + output_name: "joined".into(), + }; + + let counting = Control::cancelled_at_look(u64::MAX); + let (out, rep) = crate::run_under("Join Field", &counting, || join_field(&target, &source, &opts)).unwrap(); + assert_eq!(rep.matched_records, 4); + assert_eq!(out.features.len(), 5); + assert_eq!(counting.progress(), Some((10, 10))); + assert_eq!(counting.looked(), 11); + + let cancel_source = Control::cancelled_at_look(3); + let err = crate::run_under("Join Field", &cancel_source, || join_field(&target, &source, &opts)).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_source.looked(), 3); + assert_eq!(cancel_source.progress(), Some((1, 10))); + + let cancel_target = Control::cancelled_at_look(8); + let err = crate::run_under("Join Field", &cancel_target, || join_field(&target, &source, &opts)).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_target.looked(), 8); + assert_eq!(cancel_target.progress(), Some((6, 10))); + + // Case 2: NumberAsText comparison (Text target vs Integer source), 4 rows each => total 12. + let target_text = + make_table("target", vec![("GEOID", FieldType::Text)], (1..=4).map(|i| vec![Value::Text(i.to_string())]).collect()); + let source_int = make_table( + "source", + vec![("GEOID", FieldType::Integer), ("tag", FieldType::Text)], + (1..=4).map(|i| vec![Value::Int(i), Value::Text(format!("v{i}"))]).collect(), + ); + let opts_num = JoinFieldOptions { + target_field: "GEOID", + join_field: "GEOID", + fields_to_transfer: None, + prefix: "", + duplicate_strategy: DuplicateStrategy::First, + output_name: "joined_num".into(), + }; + + let counting_num = Control::cancelled_at_look(u64::MAX); + let (_, rep_num) = crate::run_under("Join Field", &counting_num, || join_field(&target_text, &source_int, &opts_num)).unwrap(); + assert_eq!(rep_num.matched_records, 4); + assert_eq!(counting_num.progress(), Some((12, 12))); + assert_eq!(counting_num.looked(), 13); + + let cancel_scan = Control::cancelled_at_look(7); + let err = crate::run_under("Join Field", &cancel_scan, || join_field(&target_text, &source_int, &opts_num)).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_scan.looked(), 7); + assert_eq!(cancel_scan.progress(), Some((5, 12))); + } } diff --git a/crates/analysis/src/merge.rs b/crates/analysis/src/merge.rs index 14a04095b1..3932e493f0 100644 --- a/crates/analysis/src/merge.rs +++ b/crates/analysis/src/merge.rs @@ -49,6 +49,8 @@ pub(crate) fn run(inputs: &dyn Inputs, params: &Json) -> Result Result Result Result } }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::control::Control; + use rustgis_data::FieldType; + use std::collections::HashMap; + + #[derive(Default)] + struct MergeInputs { + data: HashMap, + selected: HashMap>, + } + + impl Inputs for MergeInputs { + fn dataset(&self, layer: &str) -> Option<&Dataset> { + self.data.get(layer) + } + + fn selection(&self, layer: &str) -> &[usize] { + self.selected.get(layer).map(Vec::as_slice).unwrap_or(&[]) + } + } + + fn point_layer(name: &str, count: usize) -> Dataset { + let mut ds = Dataset::new(name, GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + for i in 0..count { + ds.push_next(Some(Geometry::Point(Coord::new(i as f64, 0.0))), vec![Value::Int(i as i64)]); + } + ds + } + + #[test] + fn merge_checks_cancel_and_reports_progress() { + let mut inputs = MergeInputs { + data: HashMap::from([("A".to_string(), point_layer("A", 3)), ("B".to_string(), point_layer("B", 4))]), + ..Default::default() + }; + let params = serde_json::json!({"inputs": ["A", "B"], "attributes": true}); + + let counting = Control::cancelled_at_look(u64::MAX); + let res = crate::run_with("merge", &inputs, ¶ms, &counting).unwrap(); + let Output::Layer(out) = res.output else { panic!("expected layer") }; + assert_eq!(out.features.len(), 7); + assert_eq!(counting.progress(), Some((7, 7))); + assert_eq!(counting.looked(), 8); + + let cancel_pre_reserve = Control::cancelled_at_look(1); + let err = crate::run_with("merge", &inputs, ¶ms, &cancel_pre_reserve).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_pre_reserve.looked(), 1); + assert_eq!(cancel_pre_reserve.progress(), Some((0, 7))); + + let cancel_mid = Control::cancelled_at_look(5); + let err = crate::run_with("merge", &inputs, ¶ms, &cancel_mid).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_mid.looked(), 5); + assert_eq!(cancel_mid.progress(), Some((3, 7))); + + // Stale selection indices in A must not inflate progress past valid count n = 1 + 4 = 5. + inputs.selected.insert("A".to_string(), vec![0, usize::MAX]); + let counting_sel = Control::cancelled_at_look(u64::MAX); + let res_sel = crate::run_with("merge", &inputs, ¶ms, &counting_sel).unwrap(); + let Output::Layer(out_sel) = res_sel.output else { panic!("expected layer") }; + assert_eq!(out_sel.features.len(), 5); + assert_eq!(counting_sel.progress(), Some((5, 5))); + } +} diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 185dc12d63..77d910b2f5 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -8710,22 +8710,39 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result< Ok(ToolResult { losses, output: Output::Layer(out), messages }) } -/// Returns a borrowed dataset when rows match the full dataset in identity order, or a new dataset containing -/// only the selected rows, in table order, with schema, CRS, and windowed flag preserved. -fn subset<'a>(ds: &'a Dataset, selected_rows: &[usize]) -> Cow<'a, Dataset> { - // Selections keep the order they were picked in: sort and dedupe so the table's order wins. +/// Sorts, deduplicates, and bounds-filters `selected_rows` against `ds` so table order wins. +fn normalize_selected_rows(ds: &Dataset, selected_rows: &[usize]) -> Vec { let mut rows: Vec = selected_rows.iter().copied().filter(|&r| r < ds.features.len()).collect(); rows.sort_unstable(); rows.dedup(); + rows +} + +/// Returns a borrowed dataset when `rows` (sorted, deduplicated, and in bounds) covers the full +/// dataset, or a new dataset containing only those selected rows with schema, CRS, and windowed +/// flag preserved. +/// +/// Advances progress within the caller's active `control::begin` step and returns `Err` when the +/// run is cancelled before allocating or between cloned rows. +fn subset<'a>(ds: &'a Dataset, rows: &[usize]) -> Result, String> { if rows.len() == ds.features.len() { - Cow::Borrowed(ds) + Ok(Cow::Borrowed(ds)) } else { let mut sub = Dataset::new(ds.name.clone(), ds.geometry_type, ds.fields.clone()); sub.crs = ds.crs; sub.crs_incomplete = ds.crs_incomplete; sub.windowed = ds.windowed; - sub.features = rows.iter().filter_map(|&r| ds.features.get(r).cloned()).collect::>().into(); - Cow::Owned(sub) + crate::control::check()?; + let mut features = Vec::with_capacity(rows.len()); + for &r in rows { + crate::control::check()?; + if let Some(f) = ds.features.get(r) { + features.push(f.clone()); + } + crate::control::advance(1); + } + sub.features = features.into(); + Ok(Cow::Owned(sub)) } } @@ -8840,9 +8857,6 @@ fn join_field_tool(inp: &dyn Inputs, p: &Json) -> Result { } } - let target_ref = subset(target, &target_rows); - let source_ref = subset(source, &source_rows); - let target_field = s(p, "targetField"); if target_field.is_empty() { return Err("target key field is required".into()); @@ -8898,7 +8912,18 @@ fn join_field_tool(inp: &dyn Inputs, p: &Json) -> Result { output_name, }; - let (out, report) = crate::attribute_join::join_field(&target_ref, &source_ref, &opts)?; + let target_norm = normalize_selected_rows(target, &target_rows); + let source_norm = normalize_selected_rows(source, &source_rows); + let join_work = + crate::attribute_join::join_field_work(target, target_norm.len(), source, source_norm.len(), opts.target_field, opts.join_field)?; + let target_copy = if target_norm.len() == target.features.len() { 0 } else { target_norm.len() }; + let source_copy = if source_norm.len() == source.features.len() { 0 } else { source_norm.len() }; + crate::control::begin(target_copy.saturating_add(source_copy).saturating_add(join_work)); + + let target_ref = subset(target, &target_norm)?; + let source_ref = subset(source, &source_norm)?; + + let (out, report) = crate::attribute_join::join_field_with_progress(&target_ref, &source_ref, &opts, true)?; messages.push(report.message(&target.name)); messages.extend(report.leading_zero_notice()); @@ -17954,4 +17979,76 @@ mod tests { assert!(res18.is_err()); assert_eq!(res18.unwrap_err(), "Transfer Fields must be a string or JSON array"); } + + #[test] + fn join_field_partial_selection_subset_checks_cancel_and_reports_progress() { + use crate::control::Control; + + struct SelectedInputs { + datasets: HashMap, + selections: HashMap>, + } + impl Inputs for SelectedInputs { + fn dataset(&self, layer: &str) -> Option<&Dataset> { + self.datasets.get(layer) + } + fn table(&self, _id: u32) -> Option<&Dataset> { + None + } + fn selection(&self, layer: &str) -> &[usize] { + self.selections.get(layer).map(|v| v.as_slice()).unwrap_or(&[]) + } + } + + let mut target = Dataset::new("target", GeometryType::None, vec![Field::new("id", FieldType::Integer)]); + for i in 0..4 { + target.push(None, vec![Value::Int(i)]); + } + let mut source = + Dataset::new("source", GeometryType::None, vec![Field::new("id", FieldType::Integer), Field::new("tag", FieldType::Integer)]); + for i in 0..4 { + source.push(None, vec![Value::Int(i), Value::Int(i * 10)]); + } + let inp = SelectedInputs { + datasets: HashMap::from([("target".to_string(), target), ("source".to_string(), source)]), + selections: HashMap::from([("target".to_string(), vec![0, 1, 2]), ("source".to_string(), vec![0, 1])]), + }; + let params = serde_json::json!({ + "target": "target", + "targetField": "id", + "joinTable": "source", + "joinField": "id" + }); + + // Shared progress total across target subset (3), source subset (2), source index (2), and target join (3) = 10. + let counting = Control::cancelled_at_look(u64::MAX); + let res = crate::run_with("joinField", &inp, ¶ms, &counting).unwrap(); + let Output::Table(out) = res.output else { panic!("expected Output::Table") }; + assert_eq!(out.features.len(), 3); + assert_eq!(out.features[0].attrs[1], Value::Int(0)); + assert_eq!(out.features[1].attrs[1], Value::Int(10)); + assert_eq!(out.features[2].attrs[1], Value::Null); + assert_eq!(counting.progress(), Some((10, 10))); + + // Cancel mid-target subset (look 1 before alloc, look 2 row 0 -> advance 1, look 3 row 1). + let cancel_target = Control::cancelled_at_look(3); + let err = crate::run_with("joinField", &inp, ¶ms, &cancel_target).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_target.looked(), 3); + assert_eq!(cancel_target.progress(), Some((1, 10))); + + // Cancel mid-source subset (4 looks in target subset -> 3 done; look 5 before alloc, look 6 row 0 -> 4 done, look 7 row 1). + let cancel_source = Control::cancelled_at_look(7); + let err = crate::run_with("joinField", &inp, ¶ms, &cancel_source).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_source.looked(), 7); + assert_eq!(cancel_source.progress(), Some((4, 10))); + + // Cancel mid-join (7 subset looks -> 5 done; look 8 pre-index, look 9 source row 0 -> 6 done, look 10 source row 1). + let cancel_join = Control::cancelled_at_look(10); + let err = crate::run_with("joinField", &inp, ¶ms, &cancel_join).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_join.looked(), 10); + assert_eq!(cancel_join.progress(), Some((6, 10))); + } } diff --git a/crates/analysis/src/tools/geometry.rs b/crates/analysis/src/tools/geometry.rs index fc16c06274..9aa69c5111 100644 --- a/crates/analysis/src/tools/geometry.rs +++ b/crates/analysis/src/tools/geometry.rs @@ -20,58 +20,93 @@ pub(super) fn convert(inp: &dyn Inputs, p: &Json, mode: Conversion) -> Result { - let mut parts = Vec::new(); - if polys.is_empty() { - skipped += 1; + let row_ids = rows(inp, p, "input", ds); + crate::control::begin(row_ids.len()); + crate::control::check()?; + let mut pace = crate::control::Pace::default(); + for row in row_ids { + crate::control::check()?; + convert_row(ds, row, mode, tool, &mut out, &mut skipped, &mut pace)?; + crate::control::advance(1); + } + finish(out, skipped, tool) +} + +const RING_COPY_CHUNK: usize = 65_536; + +/// Copies `ring` (closing it if needed) in [`RING_COPY_CHUNK`]-vertex slices so a single huge ring +/// still checks Cancel via `pace` mid-copy. +fn copy_ring_paced(ring: &[Coord], pace: &mut crate::control::Pace) -> Result, String> { + let closed = ring.first() == ring.last(); + let mut line = Vec::with_capacity(ring.len() + usize::from(!closed)); + for chunk in ring.chunks(RING_COPY_CHUNK) { + if pace.stop(chunk.len()) { + return Err(crate::control::Cancelled.into()); + } + line.extend_from_slice(chunk); + } + if !closed && let Some(first) = line.first().copied() { + line.push(first); + } + Ok(line) +} + +fn convert_row( + ds: &Dataset, + row: usize, + mode: Conversion, + tool: &str, + out: &mut Dataset, + skipped: &mut usize, + pace: &mut crate::control::Pace, +) -> Result<(), String> { + let Some(f) = ds.features.get(row) else { return Ok(()) }; + require_schema(f, ds.fields.len())?; + let Some(g) = &f.geometry else { + *skipped += 1; + return Ok(()); + }; + require_finite(g)?; + match (mode, g) { + (Conversion::PolygonToLine, Geometry::Polygon(polys)) => { + let mut parts = Vec::new(); + if polys.is_empty() { + *skipped += 1; + } + for rings in polys { + if rings.is_empty() { + *skipped += 1; } - for rings in polys { - if rings.is_empty() { - skipped += 1; + for ring in rings { + if pace.stop(crate::control::PACE_WORK / 1024) { + return Err(crate::control::Cancelled.into()); } - for ring in rings { - if ring.len() < 2 { - skipped += 1; - continue; - } - let mut line = ring.clone(); - if let Some(first) = line.first().copied() - && line.last() != Some(&first) - { - line.push(first); - } - parts.push(line); + if ring.len() < 2 { + *skipped += 1; + continue; } - } - if !parts.is_empty() { - out.push_next(Some(Geometry::Line(parts)), f.attrs.clone()); + parts.push(copy_ring_paced(ring, pace)?); } } - (Conversion::PolygonToLine, _) => { - return Err(format!("{tool}: feature {} has an incompatible geometry", f.id)); + if !parts.is_empty() { + out.push_next(Some(Geometry::Line(parts)), f.attrs.clone()); } - _ => { - let e = g.extent(); - if e.is_empty() || e.width() == 0.0 || e.height() == 0.0 { - skipped += 1; - continue; - } - let a = Coord::new(e.min_x, e.min_y); - let ring = vec![a, Coord::new(e.max_x, e.min_y), Coord::new(e.max_x, e.max_y), Coord::new(e.min_x, e.max_y), a]; - out.push_next(Some(Geometry::Polygon(vec![vec![ring]])), f.attrs.clone()); + } + (Conversion::PolygonToLine, _) => { + return Err(format!("{tool}: feature {} has an incompatible geometry", f.id)); + } + _ => { + let e = g.extent(); + if e.is_empty() || e.width() == 0.0 || e.height() == 0.0 { + *skipped += 1; + return Ok(()); } + let a = Coord::new(e.min_x, e.min_y); + let ring = vec![a, Coord::new(e.max_x, e.min_y), Coord::new(e.max_x, e.max_y), Coord::new(e.min_x, e.max_y), a]; + out.push_next(Some(Geometry::Polygon(vec![vec![ring]])), f.attrs.clone()); } } - finish(out, skipped, tool) + Ok(()) } /// A generated dataset retains schema and loss provenance, without a reloadable source/window. @@ -95,7 +130,9 @@ fn size_segments<'a>( estimate: bool, ) -> Result<(usize, Option, usize), String> { let (mut count, mut bytes, mut skipped) = (0usize, 0u64, 0usize); + let mut pace = crate::control::Pace::default(); for f in features { + crate::control::check()?; require_schema(f, width)?; let Some(g) = &f.geometry else { skipped += 1; @@ -109,6 +146,9 @@ fn size_segments<'a>( let per_segment = if estimate { point_bytes(f.attrs.get(..width).unwrap_or(&f.attrs), width).saturating_add(SEGMENT_EXTRA_BYTES) } else { 0 }; for part in parts { + if pace.stop(crate::control::PACE_WORK / 1024) { + return Err(crate::control::Cancelled.into()); + } if part.len() < 2 { skipped += 1; } @@ -170,15 +210,25 @@ pub(super) fn split(inp: &dyn Inputs, p: &Json) -> Result { check_segment_room(n, need, web_has_room)?; } let no_memory = |e: TryReserveError| format!("Split Line At Vertices: not enough memory for {n} segments: {e}"); + crate::control::begin(n); + crate::control::check()?; let mut segments = Vec::new(); segments.try_reserve_exact(n).map_err(no_memory)?; + let mut pace = crate::control::Pace::default(); for f in features() { + crate::control::check()?; let Some(Geometry::Line(parts)) = &f.geometry else { continue }; for pair in parts.iter().flat_map(|part| part.windows(2)) { + if pace.stop(crate::control::PACE_WORK / 1024) { + return Err(crate::control::Cancelled.into()); + } let id = u64::try_from(segments.len()).ok().and_then(|n| n.checked_add(1)).ok_or("Split Line At Vertices: too many segments")?; match segment_feature(id, pair, &f.attrs, ds.fields.len()) { - Ok(feature) => segments.push(feature), + Ok(feature) => { + segments.push(feature); + crate::control::advance(1); + } Err(e) => { drop(segments); return Err(no_memory(e)); @@ -232,34 +282,14 @@ pub(super) fn unsplit(inp: &dyn Inputs, p: &Json) -> Result let mut edges = Vec::new(); let mut nodes: HashMap<_, Vec<(usize, bool)>> = HashMap::new(); let mut skipped = 0; - for row in rows(inp, p, "input", ds) { - let Some(f) = ds.features.get(row) else { continue }; - require_schema(f, ds.fields.len())?; - let Some(g) = &f.geometry else { - skipped += 1; - continue; - }; - require_finite(g)?; - let Geometry::Line(parts) = g else { - return Err(format!("Unsplit Line: feature {} is not a line", f.id)); - }; - if parts.is_empty() { - skipped += 1; - } - for part in parts { - let (Some(first), Some(last)) = (part.first(), part.last()) else { - skipped += 1; - continue; - }; - if part.len() < 2 { - skipped += 1; - continue; - } - let id = edges.len(); - nodes.entry(endpoint(first)).or_default().push((id, false)); - nodes.entry(endpoint(last)).or_default().push((id, true)); - edges.push((part, &f.attrs)); - } + let row_ids = rows(inp, p, "input", ds); + crate::control::begin(row_ids.len()); + crate::control::check()?; + let mut pace = crate::control::Pace::default(); + for row in row_ids { + crate::control::check()?; + unsplit_collect_row(ds, row, &mut edges, &mut nodes, &mut skipped, &mut pace)?; + crate::control::advance(1); } // An endpoint is traversable only when both incident edges have the same attributes. let joins = |c: &Coord| -> Option<&Vec<(usize, bool)>> { @@ -269,8 +299,12 @@ pub(super) fn unsplit(inp: &dyn Inputs, p: &Json) -> Result (0..ds.fields.len()).all(|i| a.get(i).unwrap_or(&Value::Null) == b.get(i).unwrap_or(&Value::Null)).then_some(incident) }; let mut used = vec![false; edges.len()]; + crate::control::begin(edges.len()); for cycles in [false, true] { for (seed, (part, attrs)) in edges.iter().enumerate() { + if pace.stop(crate::control::PACE_WORK / 1024) { + return Err(crate::control::Cancelled.into()); + } if used.get(seed).copied().unwrap_or(true) { continue; } @@ -291,6 +325,7 @@ pub(super) fn unsplit(inp: &dyn Inputs, p: &Json) -> Result if *seen { break; } + crate::control::check()?; *seen = true; let skip = usize::from(!line.is_empty()); if reverse { @@ -298,6 +333,7 @@ pub(super) fn unsplit(inp: &dyn Inputs, p: &Json) -> Result } else { line.extend(part.iter().skip(skip).copied()); } + crate::control::advance(1); let next = line.last().and_then(joins).and_then(|incident| incident.iter().find(|(other, _)| *other != id)); let Some(&(other, at_end)) = next else { break }; id = other; @@ -311,6 +347,47 @@ pub(super) fn unsplit(inp: &dyn Inputs, p: &Json) -> Result finish(out, skipped, "Unsplit Line") } +fn unsplit_collect_row<'a>( + ds: &'a Dataset, + row: usize, + edges: &mut Vec<(&'a Vec, &'a Vec)>, + nodes: &mut HashMap<(u64, u64), Vec<(usize, bool)>>, + skipped: &mut usize, + pace: &mut crate::control::Pace, +) -> Result<(), String> { + let Some(f) = ds.features.get(row) else { return Ok(()) }; + require_schema(f, ds.fields.len())?; + let Some(g) = &f.geometry else { + *skipped += 1; + return Ok(()); + }; + require_finite(g)?; + let Geometry::Line(parts) = g else { + return Err(format!("Unsplit Line: feature {} is not a line", f.id)); + }; + if parts.is_empty() { + *skipped += 1; + } + for part in parts { + if pace.stop(crate::control::PACE_WORK / 1024) { + return Err(crate::control::Cancelled.into()); + } + let (Some(first), Some(last)) = (part.first(), part.last()) else { + *skipped += 1; + continue; + }; + if part.len() < 2 { + *skipped += 1; + continue; + } + let id = edges.len(); + nodes.entry(endpoint(first)).or_default().push((id, false)); + nodes.entry(endpoint(last)).or_default().push((id, true)); + edges.push((part, &f.attrs)); + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -343,4 +420,205 @@ mod tests { assert!(check_segment_room(n, need, |_| false).unwrap_err().contains("3 segments")); assert_eq!(size_segments(&features, 1, false).unwrap(), (3, None, 0)); } + + struct One(Dataset); + + impl Inputs for One { + fn dataset(&self, name: &str) -> Option<&Dataset> { + (name == "input").then_some(&self.0) + } + fn selection(&self, _: &str) -> &[usize] { + &[] + } + } + + fn poly_square(x: f64) -> Geometry { + let ring = vec![Coord::new(x, 0.0), Coord::new(x + 1.0, 0.0), Coord::new(x + 1.0, 1.0), Coord::new(x, 0.0)]; + Geometry::Polygon(vec![vec![ring]]) + } + + #[test] + fn convert_checks_cancel_and_reports_progress() { + use crate::control::Control; + + let mut ds = Dataset::new("input", GeometryType::Polygon, vec![Field::new("id", FieldType::Integer)]); + for i in 0..4 { + ds.push_next(Some(poly_square(i as f64 * 2.0)), vec![Value::Int(i)]); + } + ds.push_next(None, vec![Value::Int(4)]); + let inp = One(ds); + let params = serde_json::json!({"input": "input"}); + + for tool in ["polygonToLine", "featureEnvelopeToPolygon"] { + let counting = Control::cancelled_at_look(u64::MAX); + crate::run_with(tool, &inp, ¶ms, &counting).unwrap(); + assert_eq!(counting.progress(), Some((5, 5)), "{tool}"); + assert_eq!(counting.looked(), 6, "{tool}"); + + let cancelled = Control::cancelled_at_look(4); + let err = crate::run_with(tool, &inp, ¶ms, &cancelled).unwrap_err(); + assert!(err.contains("cancelled"), "{tool}: {err}"); + assert_eq!(cancelled.looked(), 4, "{tool}"); + assert_eq!(cancelled.progress(), Some((2, 5)), "{tool}"); + } + + // Single multipolygon with 1,500 rings cancels inside the ring loop via Pace. + let ring = vec![Coord::new(0.0, 0.0), Coord::new(1.0, 0.0), Coord::new(1.0, 1.0), Coord::new(0.0, 0.0)]; + let mut rings = Vec::with_capacity(1500); + for _ in 0..1500 { + rings.push(ring.clone()); + } + let mut poly_ds = Dataset::new("input", GeometryType::Polygon, vec![]); + poly_ds.push_next(Some(Geometry::Polygon(vec![rings])), vec![]); + let poly_inp = One(poly_ds); + + let counting_rings = Control::cancelled_at_look(u64::MAX); + crate::run_with("polygonToLine", &poly_inp, ¶ms, &counting_rings).unwrap(); + assert_eq!(counting_rings.looked(), 3); + + let cancel_ring = Control::cancelled_at_look(3); + let err = crate::run_with("polygonToLine", &poly_inp, ¶ms, &cancel_ring).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_ring.looked(), 3); + + // 800 rings of 1,200 vertices: per-ring and per-chunk units together cross PACE_WORK, so Cancel is looked at inside the ring loop. + let make_heavy_rings = |verts: usize| { + let mut ring = Vec::with_capacity(verts); + for i in 0..verts { + ring.push(Coord::new(i as f64, 0.0)); + } + let rings = vec![ring; 800]; + let mut d = Dataset::new("input", GeometryType::Polygon, vec![]); + d.push_next(Some(Geometry::Polygon(vec![rings])), vec![]); + One(d) + }; + let counting_small = Control::cancelled_at_look(u64::MAX); + crate::run_with("polygonToLine", &make_heavy_rings(4), ¶ms, &counting_small).unwrap(); + assert_eq!(counting_small.looked(), 2); + + let cancel_verts = Control::cancelled_at_look(3); + let err = crate::run_with("polygonToLine", &make_heavy_rings(1_200), ¶ms, &cancel_verts).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_verts.looked(), 3); + } + + #[test] + fn copy_ring_paced_cancels_mid_ring_across_chunks() { + use crate::control::{Control, PACE_WORK, Pace}; + + let verts = RING_COPY_CHUNK + 4_464; + let big_ring: Vec = (0..verts).map(|i| Coord::new(i as f64, 0.0)).collect(); + + // Prime Pace so chunk 1 (RING_COPY_CHUNK) stays below PACE_WORK and chunk 2 crosses it mid-ring. + let cancel_mid = Control::cancelled_at_look(1); + let err = crate::run_under("copy_ring_paced", &cancel_mid, || { + let mut pace = Pace::default(); + assert!(!pace.stop(PACE_WORK - verts)); + copy_ring_paced(&big_ring, &mut pace) + }) + .unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_mid.looked(), 1); + + let counting = Control::cancelled_at_look(u64::MAX); + let copied = crate::run_under("copy_ring_paced", &counting, || { + let mut pace = Pace::default(); + assert!(!pace.stop(PACE_WORK - verts)); + copy_ring_paced(&big_ring, &mut pace) + }) + .unwrap(); + assert_eq!(counting.looked(), 1); + assert_eq!(copied.len(), verts + 1); + assert_eq!(copied.first(), copied.last()); + } + + #[test] + fn split_checks_cancel_and_reports_progress() { + use crate::control::Control; + + // 4 polyline features, 3 vertices each (2 segments each => n = 8). + let mut ds = Dataset::new("input", GeometryType::Polyline, vec![Field::new("id", FieldType::Integer)]); + for i in 0..4 { + let x = i as f64 * 10.0; + ds.push_next( + Some(Geometry::Line(vec![vec![Coord::new(x, 0.0), Coord::new(x + 1.0, 0.0), Coord::new(x + 2.0, 0.0)]])), + vec![Value::Int(i)], + ); + } + let inp = One(ds); + let params = serde_json::json!({"input": "input"}); + + let counting = Control::cancelled_at_look(u64::MAX); + crate::run_with("splitLineAtVertices", &inp, ¶ms, &counting).unwrap(); + assert_eq!(counting.progress(), Some((8, 8))); + assert_eq!(counting.looked(), 9); + + let cancel_sizing = Control::cancelled_at_look(2); + let err = crate::run_with("splitLineAtVertices", &inp, ¶ms, &cancel_sizing).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_sizing.looked(), 2); + assert_eq!(cancel_sizing.progress(), None); + + let cancel_reserve = Control::cancelled_at_look(5); + let err = crate::run_with("splitLineAtVertices", &inp, ¶ms, &cancel_reserve).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_reserve.looked(), 5); + assert_eq!(cancel_reserve.progress(), Some((0, 8))); + + let cancel_emit = Control::cancelled_at_look(7); + let err = crate::run_with("splitLineAtVertices", &inp, ¶ms, &cancel_emit).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_emit.looked(), 7); + assert_eq!(cancel_emit.progress(), Some((2, 8))); + + // Single long line with 2,500 vertices (2,499 segments) cancels mid-line via Pace. + let mut long_ds = Dataset::new("input", GeometryType::Polyline, vec![]); + let coords: Vec = (0..2500).map(|i| Coord::new(i as f64, 0.0)).collect(); + long_ds.push_next(Some(Geometry::Line(vec![coords])), vec![]); + let long_inp = One(long_ds); + + let counting_long = Control::cancelled_at_look(u64::MAX); + crate::run_with("splitLineAtVertices", &long_inp, ¶ms, &counting_long).unwrap(); + assert_eq!(counting_long.progress(), Some((2499, 2499))); + assert_eq!(counting_long.looked(), 5); + + let cancel_long = Control::cancelled_at_look(4); + let err = crate::run_with("splitLineAtVertices", &long_inp, ¶ms, &cancel_long).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_long.looked(), 4); + assert_eq!(cancel_long.progress(), Some((1023, 2499))); + } + + #[test] + fn unsplit_checks_cancel_and_reports_progress() { + use crate::control::Control; + + // 4 connected 2-vertex line features forming a 4-edge chain with identical attribute. + let mut ds = Dataset::new("input", GeometryType::Polyline, vec![Field::new("road", FieldType::Text)]); + for i in 0..4 { + let x = i as f64; + ds.push_next(Some(Geometry::Line(vec![vec![Coord::new(x, 0.0), Coord::new(x + 1.0, 0.0)]])), vec![Value::Text("main".into())]); + } + let inp = One(ds); + let params = serde_json::json!({"input": "input"}); + + let counting = Control::cancelled_at_look(u64::MAX); + let res = crate::run_with("unsplitLine", &inp, ¶ms, &counting).unwrap(); + let Output::Layer(out) = res.output else { panic!("expected layer") }; + assert_eq!(out.features.len(), 1); + assert_eq!(counting.progress(), Some((4, 4))); + assert_eq!(counting.looked(), 9); + + let cancel_input = Control::cancelled_at_look(3); + let err = crate::run_with("unsplitLine", &inp, ¶ms, &cancel_input).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_input.looked(), 3); + assert_eq!(cancel_input.progress(), Some((1, 4))); + + let cancel_chain = Control::cancelled_at_look(7); + let err = crate::run_with("unsplitLine", &inp, ¶ms, &cancel_chain).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_chain.looked(), 7); + assert_eq!(cancel_chain.progress(), Some((1, 4))); + } } diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 57c460e779..15d6113a25 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -366,6 +366,12 @@ pub(super) fn long_commands(boundaries: bool) { ("a5Grid", json!({"system": "Hexagon", "resolution": 3, "area": "Input Layer", "input": "Countries"})), ("a5Aggregate", json!({"system": "H3", "input": "Cities", "resolution": 3})), ("a5Grid", json!({"system": "H3", "resolution": 3, "area": "Input Layer", "input": "Countries"})), + ("joinField", json!({"target": "Cities", "joinTable": "ranks", "targetField": "name", "joinField": "name"})), + ("merge", json!({"inputs": ["Countries", "Squares"], "attributes": true})), + ("polygonToLine", json!({"input": "Countries"})), + ("featureEnvelopeToPolygon", json!({"input": "Countries"})), + ("splitLineAtVertices", json!({"input": "Rivers"})), + ("unsplitLine", json!({"input": "Rivers"})), ]; for (tool, params) in &tools { exercise(&s, tool, params, Kind::Tool, &dir.0, boundaries);