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
103 changes: 54 additions & 49 deletions crates/analysis/src/attribute_join.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize, String> {
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<Self, 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());
}
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`.
Expand All @@ -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<usize> = match opts.fields_to_transfer {
Some(explicit) => {
let mut indices = Vec::with_capacity(explicit.len());
Expand All @@ -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;
Expand Down Expand Up @@ -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<JoinKey, usize> = HashMap::with_capacity(source.features.len());
Expand Down
3 changes: 3 additions & 0 deletions crates/analysis/src/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
133 changes: 131 additions & 2 deletions crates/analysis/src/merge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,14 @@ pub(crate) fn run(inputs: &dyn Inputs, params: &Json) -> Result<ToolResult, Stri
out.crs_incomplete = layers.iter().any(|ds| ds.crs_incomplete);
let mut original_fields: Vec<Field> = 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()
Expand Down Expand Up @@ -70,7 +74,11 @@ pub(crate) fn run(inputs: &dyn Inputs, params: &Json) -> Result<ToolResult, Stri
*value = crate::tools::try_clone_value(ds.value(row, source)).map_err(no_memory)?;
}
}
let geometry = feature.geometry.as_ref().map(clone_geometry).transpose().map_err(no_memory)?;
let geometry = match feature.geometry.as_ref().map(|g| clone_geometry_paced(g, &mut pace)).transpose() {
Ok(geometry) => 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);
}
Expand All @@ -82,7 +90,64 @@ pub(crate) fn run(inputs: &dyn Inputs, params: &Json) -> Result<ToolResult, Stri
})
}

/// Fallible geometry copies, so a large merge can return an allocation error.
enum CloneGeometryError {
Cancelled,
Reserve(TryReserveError),
}

impl From<TryReserveError> 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<Geometry, CloneGeometryError> {
fn coords(source: &[Coord], pace: &mut crate::control::Pace) -> Result<Vec<Coord>, 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<Coord>], pace: &mut crate::control::Pace) -> Result<Vec<Vec<Coord>>, 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<Geometry, TryReserveError> {
fn coords(source: &[Coord]) -> Result<Vec<Coord>, TryReserveError> {
let mut out = Vec::new();
Expand Down Expand Up @@ -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<Coord> = (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, &params, &counting_rings).unwrap();
assert_eq!(counting_rings.looked(), 3);

let cancel_rings = Control::cancelled_at_look(3);
let err = crate::run_with("merge", &inputs, &params, &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<Field> = (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);
}
}
Loading
Loading