diff --git a/crates/analysis/src/attribute_join.rs b/crates/analysis/src/attribute_join.rs index 42562d9b0e..b677453000 100644 --- a/crates/analysis/src/attribute_join.rs +++ b/crates/analysis/src/attribute_join.rs @@ -204,29 +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()); +/// Validated key-field indices and comparison mode shared between progress sizing and execution +/// so both always agree on the work units [`join_field`] advances. +#[derive(Clone, Copy)] +pub(crate) struct ResolvedKeys { + target_key_idx: usize, + source_key_idx: usize, + comparison: KeyComparison, +} + +impl ResolvedKeys { + /// Validates `windowed` flags, resolves key field indices case-insensitively, and checks key + /// type compatibility once for both progress sizing and join execution. + pub(crate) fn resolve(target: &Dataset, source: &Dataset, 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)?; + Ok(Self { target_key_idx, source_key_idx, comparison }) } - if source.windowed { - return Err("the source layer is streamed; load all features first".into()); + + /// Progress work units (`source_len` + optional `NumberAsText` scan + `target_len`) that + /// [`join_field_prepared`] advances for datasets of these row counts. + pub(crate) fn work(self, target_len: usize, source_len: usize) -> usize { + let extra_scan = if self.comparison == KeyComparison::NumberAsText { source_len } else { 0 }; + source_len.saturating_add(extra_scan).saturating_add(target_len) } - 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)) +} + +/// Whether [`join_field_prepared`] starts its own `control::begin` step or advances within an +/// active caller step (used by `joinField` to share one monotonic bar across subsetting and join). +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum JoinProgress { + /// Start a new `control::begin` step with the join's own work total. + Start, + /// Continue the caller's active `control::begin` step without resetting it. + Continue, } /// Executes a non-spatial attribute join from `source` onto `target`. @@ -235,36 +255,22 @@ pub(crate) fn join_field_work( /// 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) + let keys = ResolvedKeys::resolve(target, source, opts.target_field, opts.join_field)?; + join_field_prepared(target, source, opts, keys, JoinProgress::Start) } -/// 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( +/// Executes [`join_field`] using pre-validated [`ResolvedKeys`] and explicit [`JoinProgress`] +/// ownership. +pub(crate) fn join_field_prepared( target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_>, - progress_started: bool, + keys: ResolvedKeys, + progress: JoinProgress, ) -> Result<(Dataset, JoinFieldReport), String> { - 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()); - } - - // 1. Resolve key field indices - let target_key_idx = crate::tools::find_field_case_insensitive(target, opts.target_field)?; - let source_key_idx = crate::tools::find_field_case_insensitive(source, opts.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())?; - - // 2. Validate key type compatibility - let comparison = key_comparison(target_key_field, source_key_field)?; + let ResolvedKeys { target_key_idx, source_key_idx, comparison } = keys; - // 3. Resolve which source fields to transfer + // 1. Resolve which source fields to transfer let transfer_indices: Vec = match opts.fields_to_transfer { Some(explicit) => { let mut indices = Vec::with_capacity(explicit.len()); @@ -286,7 +292,7 @@ pub(crate) fn join_field_with_progress( } }; - // 4. Build output schema with deterministic collision handling + // 2. Build output schema with deterministic collision handling let mut out = Dataset::new(opts.output_name.clone(), target.geometry_type, target.fields.clone()); out.crs = target.crs; out.crs_incomplete = target.crs_incomplete; @@ -314,10 +320,9 @@ pub(crate) fn join_field_with_progress( out.fields.push(Field { name: unique_name, ty: src_field.ty, alias }); } - // 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())); + // 3. Index source records: Map JoinKey -> source feature index + if progress == JoinProgress::Start { + crate::control::begin(keys.work(target.features.len(), source.features.len())); } crate::control::check()?; let mut source_index: HashMap = HashMap::with_capacity(source.features.len()); diff --git a/crates/analysis/src/control.rs b/crates/analysis/src/control.rs index 1744b54136..6abb97af8a 100644 --- a/crates/analysis/src/control.rs +++ b/crates/analysis/src/control.rs @@ -248,6 +248,9 @@ pub(crate) fn uncapped() -> bool { /// inside an item of a loop ([`Pace`]): a few milliseconds. pub(crate) const PACE_WORK: usize = 1 << 22; +/// Coordinates processed per [`Pace`] slice when scanning or copying a single large geometry. +pub(crate) const COORD_PACE_CHUNK: usize = 65_536; + /// Looks at the cancel flag about every [`PACE_WORK`] units of work, within an item that may /// take long on its own (a row of a wide grid without a work cap), so Cancel stops the run soon. #[derive(Default)] diff --git a/crates/analysis/src/merge.rs b/crates/analysis/src/merge.rs index 3932e493f0..ec05c642ee 100644 --- a/crates/analysis/src/merge.rs +++ b/crates/analysis/src/merge.rs @@ -19,10 +19,14 @@ pub(crate) fn run(inputs: &dyn Inputs, params: &Json) -> Result = Vec::new(); let mut mappings = Vec::new(); + let mut pace = crate::control::Pace::default(); for ds in &layers { let mut mapping = Vec::new(); if attributes { for field in &ds.fields { + if pace.stop(original_fields.len().max(1)) { + return Err(crate::control::Cancelled.into()); + } let index = original_fields .iter() .enumerate() @@ -70,7 +74,11 @@ pub(crate) fn run(inputs: &dyn Inputs, params: &Json) -> Result geometry, + Err(CloneGeometryError::Cancelled) => return Err(crate::control::Cancelled.into()), + Err(CloneGeometryError::Reserve(e)) => return Err(no_memory(e)), + }; out.push_next(geometry, attrs); crate::control::advance(1); } @@ -82,7 +90,64 @@ pub(crate) fn run(inputs: &dyn Inputs, params: &Json) -> Result for CloneGeometryError { + fn from(e: TryReserveError) -> Self { + Self::Reserve(e) + } +} + +/// Fallible, cancel-aware geometry copy: reserves exact capacities and checks `pace` between +/// parts and every [`crate::control::COORD_PACE_CHUNK`] coordinates so a single huge feature still +/// observes Cancel. +fn clone_geometry_paced(g: &Geometry, pace: &mut crate::control::Pace) -> Result { + fn coords(source: &[Coord], pace: &mut crate::control::Pace) -> Result, CloneGeometryError> { + let mut out = Vec::new(); + out.try_reserve_exact(source.len())?; + for chunk in source.chunks(crate::control::COORD_PACE_CHUNK) { + if pace.stop(chunk.len()) { + return Err(CloneGeometryError::Cancelled); + } + out.extend_from_slice(chunk); + } + Ok(out) + } + fn parts(source: &[Vec], pace: &mut crate::control::Pace) -> Result>, CloneGeometryError> { + let mut out = Vec::new(); + out.try_reserve_exact(source.len())?; + for part in source { + if pace.stop(crate::control::PACE_WORK / 1024) { + return Err(CloneGeometryError::Cancelled); + } + out.push(coords(part, pace)?); + } + Ok(out) + } + Ok(match g { + Geometry::Point(c) => Geometry::Point(*c), + Geometry::MultiPoint(points) => Geometry::MultiPoint(coords(points, pace)?), + Geometry::Line(lines) => Geometry::Line(parts(lines, pace)?), + Geometry::Polygon(polygons) => { + let mut out = Vec::new(); + out.try_reserve_exact(polygons.len())?; + for polygon in polygons { + if polygon.is_empty() && pace.stop(crate::control::PACE_WORK / 1024) { + return Err(CloneGeometryError::Cancelled); + } + out.push(parts(polygon, pace)?); + } + Geometry::Polygon(out) + } + }) +} + +/// Fallible geometry copies, so a large merge or geometry check can return an allocation error. +/// Unchecked within one feature; callers check Cancel between features or use +/// [`clone_geometry_paced`] when copying huge geometries directly. pub(crate) fn clone_geometry(g: &Geometry) -> Result { fn coords(source: &[Coord]) -> Result, TryReserveError> { let mut out = Vec::new(); @@ -179,4 +244,68 @@ mod tests { assert_eq!(out_sel.features.len(), 5); assert_eq!(counting_sel.progress(), Some((5, 5))); } + + #[test] + fn clone_geometry_paced_cancels_mid_large_polygon_and_many_rings() { + use crate::control::{PACE_WORK, Pace}; + + let verts = crate::control::COORD_PACE_CHUNK + 2_048; + let big_ring: Vec = (0..verts).map(|i| Coord::new(i as f64, 0.0)).collect(); + let big_poly = Geometry::Polygon(vec![vec![big_ring]]); + + let map_clone_err = |e: CloneGeometryError| -> String { + match e { + CloneGeometryError::Cancelled => crate::control::Cancelled.into(), + CloneGeometryError::Reserve(err) => err.to_string(), + } + }; + + // Prime Pace so chunk 1 stays below PACE_WORK and chunk 2 cancels mid-ring. + let cancel_chunk = Control::cancelled_at_look(1); + let err = crate::run_under("clone_geometry_paced", &cancel_chunk, || { + let mut pace = Pace::default(); + assert!(!pace.stop(PACE_WORK - (PACE_WORK / 1024) - verts)); + clone_geometry_paced(&big_poly, &mut pace).map_err(map_clone_err) + }) + .unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_chunk.looked(), 1); + + let counting_chunk = Control::cancelled_at_look(u64::MAX); + let cloned = crate::run_under("clone_geometry_paced", &counting_chunk, || { + let mut pace = Pace::default(); + assert!(!pace.stop(PACE_WORK - (PACE_WORK / 1024) - verts)); + clone_geometry_paced(&big_poly, &mut pace).map_err(map_clone_err) + }) + .unwrap(); + assert_eq!(counting_chunk.looked(), 1); + assert_eq!(cloned, big_poly); + + // Single multipolygon feature with 1,500 rings cancels mid-feature during merge::run. + 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 poly_ds = Dataset::new("P", GeometryType::Polygon, vec![]); + poly_ds.push_next(Some(Geometry::Polygon(vec![vec![ring; 1500]])), vec![]); + let inputs = MergeInputs { data: HashMap::from([("P".to_string(), poly_ds)]), ..Default::default() }; + let params = serde_json::json!({"inputs": ["P"], "attributes": false}); + + let counting_rings = Control::cancelled_at_look(u64::MAX); + crate::run_with("merge", &inputs, ¶ms, &counting_rings).unwrap(); + assert_eq!(counting_rings.looked(), 3); + + let cancel_rings = Control::cancelled_at_look(3); + let err = crate::run_with("merge", &inputs, ¶ms, &cancel_rings).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_rings.looked(), 3); + + // Many distinct fields cancel during schema field-mapping preparation before feature work. + let fields: Vec = (0..3_000).map(|i| Field::new(format!("f{i}"), FieldType::Integer)).collect(); + let wide_ds = Dataset::new("W", GeometryType::Point, fields); + let wide_inputs = MergeInputs { data: HashMap::from([("W".to_string(), wide_ds)]), ..Default::default() }; + let wide_params = serde_json::json!({"inputs": ["W"], "attributes": true}); + let cancel_schema = Control::cancelled_at_look(1); + let err = crate::run_with("merge", &wide_inputs, &wide_params, &cancel_schema).unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_schema.looked(), 1); + assert_eq!(cancel_schema.progress(), None); + } } diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 0d8fd7b8e7..97f20a8753 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -8774,39 +8774,80 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result< Ok(ToolResult { losses, output: Output::Layer(out), messages }) } -/// 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 +/// Normalized row selection for `joinField`: either the full dataset (no index buffer or sort) +/// or a sorted, deduplicated list of in-bounds row indices. +enum SelectedSubset { + All(usize), + Rows(Vec), +} + +impl SelectedSubset { + /// Builds a normalized selection for `ds`. Skips allocating and sorting when `sel` is empty + /// (full table). For a non-empty selection, fallibly reserves the in-bounds index buffer, then + /// sorts and deduplicates it in one pass (an uninterruptible `usize` sort, fast even on + /// millions of indices) so table order wins. + fn from_selection(ds: &Dataset, sel: &[usize]) -> Result { + if sel.is_empty() { + return Ok(Self::All(ds.features.len())); + } + let in_bounds = sel.iter().filter(|&&r| r < ds.features.len()).count(); + let mut rows = Vec::new(); + rows.try_reserve_exact(in_bounds) + .map_err(|e| format!("Join Field: not enough memory for {in_bounds} selected row indices: {e}"))?; + rows.extend(sel.iter().copied().filter(|&r| r < ds.features.len())); + rows.sort_unstable(); + rows.dedup(); + if rows.len() == ds.features.len() { Ok(Self::All(ds.features.len())) } else { Ok(Self::Rows(rows)) } + } + + fn len(&self) -> usize { + match self { + Self::All(n) => *n, + Self::Rows(rows) => rows.len(), + } + } + + fn is_empty(&self) -> bool { + self.len() == 0 + } + + fn copy_work(&self) -> usize { + match self { + Self::All(_) => 0, + Self::Rows(rows) => rows.len(), + } + } } -/// 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. +/// Returns a borrowed dataset when `selection` covers the full dataset, or a new dataset +/// containing only the 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() { - 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; - crate::control::check()?; - let mut features = Vec::with_capacity(rows.len()); - for &r in rows { +/// Consumes `selection` so its index buffer is released before joining, advances progress within +/// the caller's active `control::begin` step, reserves fallibly, and returns `Err` when the run is +/// cancelled before allocating or between cloned rows. +fn subset<'a>(ds: &'a Dataset, selection: SelectedSubset) -> Result, String> { + match selection { + SelectedSubset::All(_) => Ok(Cow::Borrowed(ds)), + SelectedSubset::Rows(rows) => { + 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; crate::control::check()?; - if let Some(f) = ds.features.get(r) { - features.push(f.clone()); + let mut features = Vec::new(); + features + .try_reserve_exact(rows.len()) + .map_err(|e| format!("Join Field: not enough memory for {} selected rows: {e}", rows.len()))?; + for r in rows { + crate::control::check()?; + if let Some(row) = ds.features.row(r) { + features.push(row.to_feature()); + } + crate::control::advance(1); } - crate::control::advance(1); + sub.features = features.into(); + Ok(Cow::Owned(sub)) } - sub.features = features.into(); - Ok(Cow::Owned(sub)) } } @@ -8884,18 +8925,18 @@ fn join_field_tool(inp: &dyn Inputs, p: &Json) -> Result { let mut messages = Vec::new(); let target_sel = inp.selection(s(p, "target")); - let target_rows = rows(inp, p, "target", target); + let target_subset = SelectedSubset::from_selection(target, target_sel)?; if !target_sel.is_empty() { - if target_rows.is_empty() { + if target_subset.is_empty() { messages.push(format!( "Warning: the selection on target '{}' contains only stale indices (0/{} features selected); output is empty", target.name, target.features.len() )); - } else if target_rows.len() < target.features.len() { + } else if target_subset.len() < target.features.len() { messages.push(format!( "Processing {} selected feature(s) from target '{}' (out of {})", - target_rows.len(), + target_subset.len(), target.name, target.features.len() )); @@ -8903,18 +8944,18 @@ fn join_field_tool(inp: &dyn Inputs, p: &Json) -> Result { } let source_sel = inp.selection(s(p, "joinTable")); - let source_rows = rows(inp, p, "joinTable", source); + let source_subset = SelectedSubset::from_selection(source, source_sel)?; if !source_sel.is_empty() { - if source_rows.is_empty() { + if source_subset.is_empty() { messages.push(format!( "Warning: the selection on source '{}' contains only stale indices (0/{} records selected); no attributes will match", source.name, source.features.len() )); - } else if source_rows.len() < source.features.len() { + } else if source_subset.len() < source.features.len() { messages.push(format!( "Joining against {} selected record(s) from source '{}' (out of {})", - source_rows.len(), + source_subset.len(), source.name, source.features.len() )); @@ -8976,18 +9017,15 @@ fn join_field_tool(inp: &dyn Inputs, p: &Json) -> Result { output_name, }; - 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 keys = crate::attribute_join::ResolvedKeys::resolve(target, source, opts.target_field, opts.join_field)?; + let join_work = keys.work(target_subset.len(), source_subset.len()); + crate::control::begin(target_subset.copy_work().saturating_add(source_subset.copy_work()).saturating_add(join_work)); - let target_ref = subset(target, &target_norm)?; - let source_ref = subset(source, &source_norm)?; + let target_ref = subset(target, target_subset)?; + let source_ref = subset(source, source_subset)?; - let (out, report) = crate::attribute_join::join_field_with_progress(&target_ref, &source_ref, &opts, true)?; + let (out, report) = + crate::attribute_join::join_field_prepared(&target_ref, &source_ref, &opts, keys, crate::attribute_join::JoinProgress::Continue)?; messages.push(report.message(&target.name)); messages.extend(report.leading_zero_notice()); @@ -18155,5 +18193,25 @@ mod tests { assert!(err.contains("cancelled"), "{err}"); assert_eq!(cancel_join.looked(), 10); assert_eq!(cancel_join.progress(), Some((6, 10))); + + // Duplicate selection indices deduplicate before reporting counts and copy work. + let inp_dup = SelectedInputs { + datasets: inp.datasets.clone(), + selections: HashMap::from([("target".to_string(), vec![2, 0, 2, 1]), ("source".to_string(), vec![1, 1, 0])]), + }; + let counting_dup = Control::cancelled_at_look(u64::MAX); + let res_dup = crate::run_with("joinField", &inp_dup, ¶ms, &counting_dup).unwrap(); + assert!(res_dup.messages.iter().any(|m| m.contains("Processing 3 selected feature(s) from target 'target' (out of 4)"))); + assert!(res_dup.messages.iter().any(|m| m.contains("Joining against 2 selected record(s) from source 'source' (out of 4)"))); + assert_eq!(counting_dup.progress(), Some((10, 10))); + + // Unselected join skips subsetting work completely: progress counts only source (4) + target (4) = 8. + let inp_all = SelectedInputs { datasets: inp.datasets, selections: HashMap::new() }; + let counting_all = Control::cancelled_at_look(u64::MAX); + let res_all = crate::run_with("joinField", &inp_all, ¶ms, &counting_all).unwrap(); + let Output::Table(out_all) = res_all.output else { panic!("expected Output::Table") }; + assert_eq!(out_all.features.len(), 4); + assert_eq!(counting_all.progress(), Some((8, 8))); + assert_eq!(counting_all.looked(), 9); } } diff --git a/crates/analysis/src/tools/geometry.rs b/crates/analysis/src/tools/geometry.rs index 9aa69c5111..90ff001d32 100644 --- a/crates/analysis/src/tools/geometry.rs +++ b/crates/analysis/src/tools/geometry.rs @@ -32,14 +32,18 @@ pub(super) fn convert(inp: &dyn Inputs, p: &Json, mode: Conversion) -> Result Result, String> { +const PART_PACE_WORK: usize = crate::control::PACE_WORK / 65_536; + +/// Copies `ring` (closing it if needed) in [`COORD_PACE_CHUNK`]-vertex slices with fallible +/// reservation so a single huge ring checks Cancel via `pace` mid-copy. +fn copy_ring_paced(ring: &[Coord], tool: &str, 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) { + let needed = ring.len().checked_add(usize::from(!closed)).ok_or_else(|| format!("{tool}: ring has too many vertices"))?; + let mut line = Vec::new(); + line.try_reserve_exact(needed).map_err(|e| format!("{tool}: not enough memory for {needed} vertices: {e}"))?; + for chunk in ring.chunks(COORD_PACE_CHUNK) { if pace.stop(chunk.len()) { return Err(crate::control::Cancelled.into()); } @@ -66,9 +70,9 @@ fn convert_row( *skipped += 1; return Ok(()); }; - require_finite(g)?; match (mode, g) { (Conversion::PolygonToLine, Geometry::Polygon(polys)) => { + require_finite_paced(g, pace)?; let mut parts = Vec::new(); if polys.is_empty() { *skipped += 1; @@ -85,7 +89,7 @@ fn convert_row( *skipped += 1; continue; } - parts.push(copy_ring_paced(ring, pace)?); + parts.push(copy_ring_paced(ring, tool, pace)?); } } if !parts.is_empty() { @@ -93,10 +97,11 @@ fn convert_row( } } (Conversion::PolygonToLine, _) => { + require_finite_paced(g, pace)?; return Err(format!("{tool}: feature {} has an incompatible geometry", f.id)); } _ => { - let e = g.extent(); + let e = finite_extent_paced(g, pace)?; if e.is_empty() || e.width() == 0.0 || e.height() == 0.0 { *skipped += 1; return Ok(()); @@ -138,7 +143,7 @@ fn size_segments<'a>( skipped += 1; continue; }; - require_finite(g)?; + require_finite_paced(g, &mut pace)?; let Geometry::Line(parts) = g else { return Err(format!("Split Line At Vertices: feature {} is not a line", f.id)) }; if parts.is_empty() { skipped += 1; @@ -249,11 +254,65 @@ fn require_schema(f: &Feature, width: usize) -> Result<(), String> { Ok(()) } -/// Rejects invalid coordinates before extent calculation or endpoint hashing can hide them. -fn require_finite(g: &Geometry) -> Result<(), String> { - let mut finite = true; - g.for_each_coord(|c| finite &= c.is_finite()); - if finite { Ok(()) } else { Err("Geometry conversion requires finite coordinates".into()) } +/// Walks `g` in [`COORD_PACE_CHUNK`]-coordinate slices, rejecting non-finite coordinates while +/// checking Cancel via `pace` and forwarding each finite coordinate to `visit`. +fn visit_finite_coords_paced(g: &Geometry, pace: &mut crate::control::Pace, mut visit: impl FnMut(Coord)) -> Result<(), String> { + fn visit_slice(coords: &[Coord], pace: &mut crate::control::Pace, visit: &mut impl FnMut(Coord)) -> Result<(), String> { + if pace.stop(PART_PACE_WORK) { + return Err(crate::control::Cancelled.into()); + } + for chunk in coords.chunks(COORD_PACE_CHUNK) { + if pace.stop(chunk.len()) { + return Err(crate::control::Cancelled.into()); + } + for &c in chunk { + if !c.is_finite() { + return Err("Geometry conversion requires finite coordinates".into()); + } + visit(c); + } + } + Ok(()) + } + match g { + Geometry::Point(c) => { + if !c.is_finite() { + return Err("Geometry conversion requires finite coordinates".into()); + } + visit(*c); + } + Geometry::MultiPoint(pts) => visit_slice(pts, pace, &mut visit)?, + Geometry::Line(parts) => { + for part in parts { + visit_slice(part, pace, &mut visit)?; + } + } + Geometry::Polygon(polys) => { + for rings in polys { + if rings.is_empty() && pace.stop(PART_PACE_WORK) { + return Err(crate::control::Cancelled.into()); + } + for ring in rings { + visit_slice(ring, pace, &mut visit)?; + } + } + } + } + Ok(()) +} + +/// Walks `g` in [`COORD_PACE_CHUNK`]-coordinate slices, rejecting non-finite coordinates and +/// computing its bounding [`Extent`] while checking Cancel via `pace`. +fn finite_extent_paced(g: &Geometry, pace: &mut crate::control::Pace) -> Result { + let mut extent = Extent::EMPTY; + visit_finite_coords_paced(g, pace, |c| extent.expand(c))?; + Ok(extent) +} + +/// Rejects invalid coordinates before extent calculation or endpoint hashing can hide them, +/// checking Cancel via `pace` inside large geometries without computing an unused extent. +fn require_finite_paced(g: &Geometry, pace: &mut crate::control::Pace) -> Result<(), String> { + visit_finite_coords_paced(g, pace, |_| {}) } /// Returns counted loss notices, refusing a result in which every usable geometry was lost. @@ -271,6 +330,64 @@ fn endpoint(c: &Coord) -> (u64, u64) { (bits(c.x), bits(c.y)) } +/// Pre-counts valid line parts (`len >= 2`) across `row_ids` so [`unsplit`] reports one monotonic +/// progress total (`rows + edges`) across both edge collection and chain walking. +fn count_unsplit_edges(ds: &Dataset, row_ids: &[usize], pace: &mut crate::control::Pace) -> Result { + let mut edges = 0usize; + for &row in row_ids { + if pace.stop(PART_PACE_WORK) { + return Err(crate::control::Cancelled.into()); + } + let Some(f) = ds.features.row(row) else { continue }; + let Some(Geometry::Line(parts)) = f.geometry() else { continue }; + for part in parts { + if pace.stop(PART_PACE_WORK) { + return Err(crate::control::Cancelled.into()); + } + if part.len() >= 2 { + edges = edges.saturating_add(1); + } + } + } + Ok(edges) +} + +/// Appends `part` (forward or reversed, optionally skipping the shared junction vertex) in +/// [`COORD_PACE_CHUNK`]-vertex slices with fallible reservation so a single huge edge checks +/// Cancel via `pace` mid-copy. +fn extend_part_paced( + line: &mut Vec, + part: &[Coord], + reverse: bool, + skip_first: bool, + pace: &mut crate::control::Pace, +) -> Result<(), String> { + let slice = if !skip_first { + part + } else if reverse { + part.get(..part.len().saturating_sub(1)).unwrap_or(&[]) + } else { + part.get(1..).unwrap_or(&[]) + }; + line.try_reserve(slice.len()).map_err(|e| format!("Unsplit Line: not enough memory for vertices: {e}"))?; + if reverse { + for chunk in slice.rchunks(COORD_PACE_CHUNK) { + if pace.stop(chunk.len()) { + return Err(crate::control::Cancelled.into()); + } + line.extend(chunk.iter().rev().copied()); + } + } else { + for chunk in slice.chunks(COORD_PACE_CHUNK) { + if pace.stop(chunk.len()) { + return Err(crate::control::Cancelled.into()); + } + line.extend_from_slice(chunk); + } + } + Ok(()) +} + /// Joins endpoint-connected parts only through degree-two nodes with identical attributes. /// Crossings without endpoint vertices are untouched. Two passes start open chains before cycles. pub(super) fn unsplit(inp: &dyn Inputs, p: &Json) -> Result { @@ -283,9 +400,10 @@ pub(super) fn unsplit(inp: &dyn Inputs, p: &Json) -> Result let mut nodes: HashMap<_, Vec<(usize, bool)>> = HashMap::new(); let mut skipped = 0; let row_ids = rows(inp, p, "input", ds); - crate::control::begin(row_ids.len()); - crate::control::check()?; let mut pace = crate::control::Pace::default(); + let edge_count = count_unsplit_edges(ds, &row_ids, &mut pace)?; + crate::control::begin(row_ids.len().saturating_add(edge_count)); + crate::control::check()?; for row in row_ids { crate::control::check()?; unsplit_collect_row(ds, row, &mut edges, &mut nodes, &mut skipped, &mut pace)?; @@ -299,7 +417,6 @@ 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) { @@ -327,12 +444,8 @@ pub(super) fn unsplit(inp: &dyn Inputs, p: &Json) -> Result } crate::control::check()?; *seen = true; - let skip = usize::from(!line.is_empty()); - if reverse { - line.extend(part.iter().rev().skip(skip).copied()); - } else { - line.extend(part.iter().skip(skip).copied()); - } + let skip_first = !line.is_empty(); + extend_part_paced(&mut line, part, reverse, skip_first, &mut pace)?; 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 }; @@ -361,7 +474,7 @@ fn unsplit_collect_row<'a>( *skipped += 1; return Ok(()); }; - require_finite(g)?; + require_finite_paced(g, pace)?; let Geometry::Line(parts) = g else { return Err(format!("Unsplit Line: feature {} is not a line", f.id)); }; @@ -506,15 +619,15 @@ mod tests { fn copy_ring_paced_cancels_mid_ring_across_chunks() { use crate::control::{Control, PACE_WORK, Pace}; - let verts = RING_COPY_CHUNK + 4_464; + let verts = COORD_PACE_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. + // Prime Pace so chunk 1 (COORD_PACE_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) + copy_ring_paced(&big_ring, "Polygon To Line", &mut pace) }) .unwrap_err(); assert!(err.contains("cancelled"), "{err}"); @@ -524,7 +637,7 @@ mod tests { 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) + copy_ring_paced(&big_ring, "Polygon To Line", &mut pace) }) .unwrap(); assert_eq!(counting.looked(), 1); @@ -532,6 +645,83 @@ mod tests { assert_eq!(copied.first(), copied.last()); } + #[test] + fn finite_extent_paced_cancels_mid_ring_and_rejects_non_finite() { + use crate::control::{Control, PACE_WORK, Pace}; + + let verts = COORD_PACE_CHUNK + 1_024; + let big_ring: Vec = (0..verts).map(|i| Coord::new(i as f64, -(i as f64))).collect(); + let geom = Geometry::Polygon(vec![vec![big_ring]]); + + // Prime Pace so chunk 1 stays below PACE_WORK and chunk 2 triggers Cancel mid-scan. + let cancel_mid = Control::cancelled_at_look(1); + let err = crate::run_under("finite_extent_paced", &cancel_mid, || { + let mut pace = Pace::default(); + assert!(!pace.stop(PACE_WORK - PART_PACE_WORK - verts)); + finite_extent_paced(&geom, &mut pace) + }) + .unwrap_err(); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(cancel_mid.looked(), 1); + + let counting = Control::cancelled_at_look(u64::MAX); + let ext = crate::run_under("finite_extent_paced", &counting, || { + let mut pace = Pace::default(); + assert!(!pace.stop(PACE_WORK - PART_PACE_WORK - verts)); + finite_extent_paced(&geom, &mut pace) + }) + .unwrap(); + assert_eq!(counting.looked(), 1); + assert_eq!(ext, geom.extent()); + + let bad = Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(f64::NAN, 1.0)]]); + let mut pace = Pace::default(); + assert!(finite_extent_paced(&bad, &mut pace).unwrap_err().contains("finite")); + } + + #[test] + fn extend_part_paced_cancels_mid_part_forward_and_reversed() { + use crate::control::{Control, PACE_WORK, Pace}; + + let verts = COORD_PACE_CHUNK + 2_048; + let part: Vec = (0..verts).map(|i| Coord::new(i as f64, 0.0)).collect(); + + for reverse in [false, true] { + let cancel_mid = Control::cancelled_at_look(1); + let err = crate::run_under("extend_part_paced", &cancel_mid, || { + let mut pace = Pace::default(); + let copied = verts - 1; + assert!(!pace.stop(PACE_WORK - copied)); + let mut line = vec![Coord::new(-1.0, 0.0)]; + extend_part_paced(&mut line, &part, reverse, true, &mut pace) + }) + .unwrap_err(); + assert!(err.contains("cancelled"), "reverse={reverse}: {err}"); + assert_eq!(cancel_mid.looked(), 1); + + let counting = Control::cancelled_at_look(u64::MAX); + let out = crate::run_under("extend_part_paced", &counting, || { + let mut pace = Pace::default(); + let copied = verts - 1; + assert!(!pace.stop(PACE_WORK - copied)); + let mut line = vec![Coord::new(-1.0, 0.0)]; + extend_part_paced(&mut line, &part, reverse, true, &mut pace)?; + Ok::<_, String>(line) + }) + .unwrap(); + assert_eq!(counting.looked(), 1); + assert_eq!(out.len(), verts); + assert_eq!(out[0], Coord::new(-1.0, 0.0)); + if reverse { + assert_eq!(out[1], Coord::new((verts - 2) as f64, 0.0)); + assert_eq!(out[verts - 1], Coord::new(0.0, 0.0)); + } else { + assert_eq!(out[1], Coord::new(1.0, 0.0)); + assert_eq!(out[verts - 1], Coord::new((verts - 1) as f64, 0.0)); + } + } + } + #[test] fn split_checks_cancel_and_reports_progress() { use crate::control::Control; @@ -602,23 +792,24 @@ mod tests { let inp = One(ds); let params = serde_json::json!({"input": "input"}); + // Shared monotonic progress across 4 input rows + 4 collected edges = 8. 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.progress(), Some((8, 8))); 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))); + assert_eq!(cancel_input.progress(), Some((1, 8))); 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))); + assert_eq!(cancel_chain.progress(), Some((5, 8))); } } diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 67af684444..5eff209857 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 = 767 +count = 766