diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py
index bfbd782e85..7664ce5a5f 100644
--- a/apps/rustgis-python/python/rustgis/_embed.py
+++ b/apps/rustgis-python/python/rustgis/_embed.py
@@ -289,9 +289,14 @@ def _app_src(url: Optional[str], lang: Optional[str]) -> str:
Args:
url: The web app's address, or None for ``RUSTGIS_WEB_URL`` or the default.
lang: The interface language code, or None.
+
+ Raises:
+ ValueError: When the address is not an ``http://`` or ``https://`` URL with a host.
"""
base = url or os.environ.get("RUSTGIS_WEB_URL") or DEFAULT_URL
parts = urlsplit(base)
+ if parts.scheme.lower() not in ("http", "https") or not parts.netloc or not parts.hostname:
+ raise ValueError(f"web app url must be an http:// or https:// address with a host, got {base!r}")
kept = [q for q in parts.query.split("&") if q]
if lang:
# The app reads the first `lang`: an explicit one replaces any the address holds.
diff --git a/apps/rustgis-python/python/rustgis/_widget.js b/apps/rustgis-python/python/rustgis/_widget.js
index b41ccc713e..850e388306 100644
--- a/apps/rustgis-python/python/rustgis/_widget.js
+++ b/apps/rustgis-python/python/rustgis/_widget.js
@@ -5,9 +5,13 @@
function render({ model, el }) {
const src = model.get("_src");
- const origin = new URL(src, window.location.href).origin;
+ const parsed = new URL(src, window.location.href);
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
+ throw new Error(`Refusing non-HTTP(S) RustGIS app URL: ${parsed.protocol}`);
+ }
+ const origin = parsed.origin;
const iframe = document.createElement("iframe");
- iframe.src = src;
+ iframe.src = parsed.href;
iframe.style.width = "100%";
iframe.style.height = model.get("height") || "800px";
iframe.style.border = "0";
diff --git a/apps/rustgis-python/tests/test_embed.py b/apps/rustgis-python/tests/test_embed.py
new file mode 100644
index 0000000000..43a63b476f
--- /dev/null
+++ b/apps/rustgis-python/tests/test_embed.py
@@ -0,0 +1,61 @@
+"""URL construction and validation for the embedded web app widgets."""
+
+import shutil
+import subprocess
+
+import pytest
+
+from rustgis._embed import WIDGET_JS, _app_src
+
+
+@pytest.mark.parametrize(
+ "bad_url",
+ [
+ "javascript:alert(1)",
+ "JAVASCRIPT:alert(1)",
+ "data:text/html,
x
",
+ "file:///etc/passwd",
+ "https://",
+ "http://",
+ "https://:443",
+ "/relative/path",
+ "ftp://example.org/app",
+ ],
+)
+def test_app_src_rejects_non_http_or_hostless_urls(bad_url):
+ with pytest.raises(ValueError):
+ _app_src(bad_url, None)
+
+
+def test_widget_js_refuses_non_http_and_frames_https(tmp_path):
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node not installed")
+ mjs = tmp_path / "_widget.mjs"
+ mjs.write_text(WIDGET_JS.read_text(encoding="utf-8"), encoding="utf-8")
+ script = f"""
+import widget from {mjs.as_uri()!r};
+globalThis.window = {{ location: {{ href: "https://notebook.example/" }}, addEventListener() {{}}, removeEventListener() {{}} }};
+globalThis.document = {{ createElement() {{ return {{ style: {{}} }}; }} }};
+const model = (src) => ({{ get: (k) => (k === "_src" ? src : ""), on() {{}}, off() {{}} }});
+const el = {{ appended: 0, appendChild() {{ this.appended += 1; }} }};
+// The guard refuses a javascript: address with its own message, not some other failure.
+let message = null;
+try {{
+ widget.render({{ model: model("javascript:alert(1)"), el }});
+}} catch (e) {{
+ message = String(e && e.message);
+}}
+if (!message || !message.includes("Refusing non-HTTP(S) RustGIS app URL")) {{
+ console.error(`expected the scheme guard to refuse javascript:, got ${{message}}`);
+ process.exit(1);
+}}
+// The same harness frames an https: address.
+const cleanup = widget.render({{ model: model("https://web.rustgis.app/?embed"), el }});
+if (el.appended !== 1 || typeof cleanup !== "function") {{
+ console.error("expected an https: address to be framed");
+ process.exit(1);
+}}
+"""
+ proc = subprocess.run([node, "--input-type=module", "-e", script], capture_output=True, text=True)
+ assert proc.returncode == 0, proc.stderr
diff --git a/crates/analysis/src/kriging.rs b/crates/analysis/src/kriging.rs
index 9fa3276999..62a67e7b04 100644
--- a/crates/analysis/src/kriging.rs
+++ b/crates/analysis/src/kriging.rs
@@ -368,6 +368,7 @@ fn kriging_on(
let scratch = || (Vec::<(f64, f64, Coord)>::with_capacity(points.len()), KrigingBuffers::new(), crate::control::Pace::default());
let (mut pred_data, mut var_data) = (crate::rasterops::new_band(w, h, NODATA)?, crate::rasterops::new_band(w, h, NODATA)?);
let rows = pred_data.chunks_mut(w).zip(var_data.chunks_mut(w));
+ let (past_pred, past_var) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
crate::control::begin(h);
crate::parallel::for_each_row(rows, threads, scratch, |(near, buffers, pace), row, (pred, var): (&mut [f32], &mut [f32])| {
// East-west degrees shrink with latitude; a projected system's units don't.
@@ -387,19 +388,27 @@ fn kriging_on(
}));
if k < near.len() {
- near.select_nth_unstable_by(k - 1, |a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
+ near.select_nth_unstable_by(k - 1, |a, b| a.0.total_cmp(&b.0));
near.truncate(k);
}
let (val, var_est) = ordinary_kriging_point(c, near, params, kx, buffers);
- *pred = if val.is_finite() { val as f32 } else { NODATA };
- *var = if var_est.is_finite() { var_est as f32 } else { NODATA };
+ // Each band counted on its own, so its note says which output lost the values.
+ *pred = crate::rasterops::stored_counting(val, &past_pred);
+ *var = crate::rasterops::stored_counting(var_est, &past_var);
}
})?;
let gt = GeoTransform { origin_x: extent.min_x, origin_y: extent.max_y, pixel_width: cell, pixel_height: -cell };
- Raster::new(name, w as u32, h as u32, vec![pred_data, var_data], gt, crs, Some(NODATA as f64), ColorHint::Gray, "Float32")
- .map_err(|e| e.to_string())
+ let mut r = Raster::new(name, w as u32, h as u32, vec![pred_data, var_data], gt, crs, Some(NODATA as f64), ColorHint::Gray, "Float32")
+ .map_err(|e| e.to_string())?;
+ // Named as the tool names its two outputs: the prediction, and `{name}_variance`.
+ for (band, past) in [(name.to_string(), past_pred), (format!("{name}_variance"), past_var)] {
+ if let Some(note) = crate::rasterops::past_f32_note(past.into_inner()) {
+ r.lost.push(rustgis_data::loss::Note::loss(rustgis_data::loss::LossCode::DroppedValue, format!("{band}: {note}")));
+ }
+ }
+ Ok(r)
}
#[cfg(test)]
diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs
index f63ea3671d..da83928b7b 100644
--- a/crates/analysis/src/network.rs
+++ b/crates/analysis/src/network.rs
@@ -30,7 +30,7 @@ impl PartialOrd for State {
}
impl Ord for State {
fn cmp(&self, o: &Self) -> std::cmp::Ordering {
- o.0.partial_cmp(&self.0).unwrap_or(std::cmp::Ordering::Equal)
+ o.0.total_cmp(&self.0)
}
}
@@ -1061,7 +1061,7 @@ pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result
(d.is_finite() && d <= radius_m).then_some((*r, d))
})
.collect();
- out.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
+ out.sort_by(|a, b| a.1.total_cmp(&b.1));
WithinReport { rows: out, bounded, invalid_latitudes, missing_coordinates }
}
diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs
index aa97b0b4ab..18450d6ac7 100644
--- a/crates/analysis/src/rasterops.rs
+++ b/crates/analysis/src/rasterops.rs
@@ -433,20 +433,52 @@ pub fn hillshade_on(r: &Raster, b: usize, azimuth: f64, altitude: f64, zf: f64,
terrain_reported(r, b, zf, ground, None, TerrainFunction::Hillshade { azimuth, altitude }).map(|(pixels, _, _)| pixels)
}
+/// What a result says of its `n` cells whose value is finite but past the range of 32-bit floats,
+/// which are stored as no-data: none when there are none.
+pub fn past_f32_note(n: usize) -> Option {
+ match n {
+ 0 => None,
+ 1 => Some("1 cell past the range of 32-bit floats (±3.4 × 10^38) has no value".into()),
+ n => Some(format!("{n} cells past the range of 32-bit floats (±3.4 × 10^38) have no value")),
+ }
+}
+
+/// `v` as a cell: no-data when it is not finite, and when it is finite but past the range of
+/// 32-bit floats, which is counted in `past` for [`past_f32_note`].
+pub(crate) fn stored_counting(v: f64, past: &std::sync::atomic::AtomicUsize) -> f32 {
+ if !v.is_finite() {
+ return NODATA;
+ }
+ let out = v as f32;
+ if out.is_finite() {
+ out
+ } else {
+ past.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ NODATA
+ }
+}
+
/// A band arithmetic expression over `b1`, `b2`… (+ - * / and parentheses, numbers).
pub fn band_math(r: &Raster, expr: &str) -> Result, String> {
+ band_math_reported(r, expr).map(|(cells, _)| cells)
+}
+
+/// [`band_math`], with how many cells came out finite but past the range of 32-bit floats and
+/// were stored as no-data ([`past_f32_note`]).
+pub fn band_math_reported(r: &Raster, expr: &str) -> Result<(Vec, usize), String> {
band_math_on(None, r, expr)
}
-/// [`band_math`] on `threads` threads (none: as many as pay off): each cell on its own, so rows go
-/// on several threads (#1252), each with its own band values.
-fn band_math_on(threads: Option, r: &Raster, expr: &str) -> Result, String> {
+/// [`band_math_reported`] on `threads` threads (none: as many as pay off): each cell on its own,
+/// so rows go on several threads (#1252), each with its own band values.
+fn band_math_on(threads: Option, r: &Raster, expr: &str) -> Result<(Vec, usize), String> {
let e = Expr::parse(expr, r.band_count())?;
let (w, h) = (r.width as usize, r.height as usize);
let mut out = new_band(w, h, NODATA)?;
if w == 0 {
- return Ok(out);
+ return Ok((out, 0));
}
+ let past = std::sync::atomic::AtomicUsize::new(0);
// A cell reads every band and evaluates the expression: about a unit a band.
let work = w.saturating_mul(h).saturating_mul(r.band_count().max(1));
let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_rows(h, work, 0));
@@ -458,29 +490,26 @@ fn band_math_on(threads: Option, r: &Raster, expr: &str) -> Result,
pub empty: Vec<(f64, f64)>,
+ pub past_f32: usize,
}
/// Remaps value ranges `[lo, hi)` to new values; other values become no-data unless `keep`.
@@ -489,6 +518,7 @@ pub struct Remap {
pub fn remap(r: &Raster, b: usize, ranges: &[(f64, f64, f64)], keep: bool) -> Result {
let d = band(r, b)?;
let n = r.width as usize * r.height as usize;
+ let past = std::sync::atomic::AtomicUsize::new(0);
// A lookup in the ranges: about a unit a cell.
let cells = per_index(
n,
@@ -499,14 +529,14 @@ pub fn remap(r: &Raster, b: usize, ranges: &[(f64, f64, f64)], keep: bool) -> Re
let Some(v) = d.get(i).copied().filter(|v| r.is_valid(*v)) else { return NODATA };
let x = v as f64;
match ranges.iter().find(|(lo, hi, _)| x >= *lo && x < *hi) {
- Some((_, _, new)) => *new as f32,
+ Some((_, _, new)) => stored_counting(*new, &past),
None if keep => v,
None => NODATA,
}
},
)?;
let empty = ranges.iter().filter(|(lo, hi, _)| lo >= hi).map(|(lo, hi, _)| (*lo, *hi)).collect();
- Ok(Remap { cells, empty })
+ Ok(Remap { cells, empty, past_f32: past.into_inner() })
}
/// The one notice for remap ranges that match nothing, each with the raster it was given for,
@@ -854,6 +884,9 @@ fn viewshed_on(
radius_m: f64,
heights: Heights,
) -> Result {
+ if !height.is_finite() {
+ return Err("the observer height must be a finite number".into());
+ }
let (oc, or) = r.pixel_at(observer).ok_or("the observer is outside the raster")?;
let z0 = r.value(b, oc, or).ok_or("the observer stands on no-data")? as f64 + height;
// The radius and the Earth's curvature are metres: so are the cells, in a system in feet too.
@@ -1217,7 +1250,8 @@ fn idw_on(
let every = every_point.then(|| IdwColumns::new(points));
let mut data = new_band(w, h, NODATA)?;
crate::control::begin(h);
- let stored = |v: f64| if v.is_finite() { v as f32 } else { NODATA };
+ let past = std::sync::atomic::AtomicUsize::new(0);
+ let stored = |v: f64| stored_counting(v, &past);
crate::parallel::for_each_row(
data.chunks_mut(w),
threads,
@@ -1258,7 +1292,7 @@ fn idw_on(
near.extend(points.iter().map(|(p, v)| (d2(c, kx, p.x, p.y).sqrt(), *v)));
}
if k < near.len() {
- near.select_nth_unstable_by(k - 1, |a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
+ near.select_nth_unstable_by(k - 1, |a, b| a.0.total_cmp(&b.0));
near.truncate(k);
}
let v = if let Some(on) = near.iter().find(|(d, _)| *d < exact) {
@@ -1278,7 +1312,12 @@ fn idw_on(
},
)?;
let gt = GeoTransform { origin_x: extent.min_x, origin_y: extent.max_y, pixel_width: cell, pixel_height: -cell };
- Raster::new(name, w as u32, h as u32, vec![data], gt, crs, Some(NODATA as f64), ColorHint::Gray, "Float32").map_err(|e| e.to_string())
+ let mut r = Raster::new(name, w as u32, h as u32, vec![data], gt, crs, Some(NODATA as f64), ColorHint::Gray, "Float32")
+ .map_err(|e| e.to_string())?;
+ if let Some(note) = past_f32_note(past.into_inner()) {
+ r.lost.push(rustgis_data::loss::Note::loss(rustgis_data::loss::LossCode::DroppedValue, note));
+ }
+ Ok(r)
}
/// Unsupervised k-means classes (1..=k) of the pixels over the given bands.
@@ -1329,7 +1368,7 @@ fn kmeans_on(threads: Option, r: &Raster, bands: &[usize], k: usize, iter
cs.iter()
.enumerate()
.map(|(i, c)| (i, c.iter().zip(p).map(|(a, b)| (a - b).powi(2)).sum::()))
- .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
+ .min_by(|a, b| a.1.total_cmp(&b.1))
.map_or(0, |x| x.0)
};
let mut sums = vec![vec![0.0; data.len()]; centres.len()];
@@ -1362,7 +1401,9 @@ fn kmeans_on(threads: Option, r: &Raster, bands: &[usize], k: usize, iter
// Classes numbered by the first band's centre, low to high.
let mut order: Vec = (0..centres.len()).collect();
order.sort_by(|a, b| {
- centres.get(*a).and_then(|c| c.first()).partial_cmp(¢res.get(*b).and_then(|c| c.first())).unwrap_or(std::cmp::Ordering::Equal)
+ let fa = centres.get(*a).and_then(|c| c.first().copied()).unwrap_or(f64::NAN);
+ let fb = centres.get(*b).and_then(|c| c.first().copied()).unwrap_or(f64::NAN);
+ fa.total_cmp(&fb)
});
let rank: Vec = (0..centres.len()).map(|c| order.iter().position(|o| *o == c).unwrap_or(0)).collect();
let (w, h) = (r.width as usize, r.height as usize);
@@ -1415,7 +1456,7 @@ pub fn classify_min_distance(r: &Raster, bands: &[usize], means: &[(f32, Vec()))
- .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
+ .min_by(|a, b| a.1.total_cmp(&b.1))
.map_or(NODATA, |x| x.0)
},
)
@@ -2985,9 +3026,9 @@ mod tests {
.unwrap();
let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>();
for expr in ["(b1 - b2) / (b1 + b2)", "b3 * 2 + 1 / b1"] {
- let one = band_math_on(Some(1), &r, expr).unwrap();
+ let one = band_math_on(Some(1), &r, expr).unwrap().0;
for threads in [2, 7, 16] {
- assert_eq!(bits(&band_math_on(Some(threads), &r, expr).unwrap()), bits(&one), "{expr}, {threads} threads");
+ assert_eq!(bits(&band_math_on(Some(threads), &r, expr).unwrap().0), bits(&one), "{expr}, {threads} threads");
}
}
let f = |c: i64, row: i64| (c % 5 != 0).then(|| r.value(1, c, row).map(|v| f64::from(v) / ((c - row) as f64))).flatten();
@@ -4004,6 +4045,79 @@ mod tests {
}
}
+ #[test]
+ fn band_math_ignores_nodata_in_unreferenced_band() {
+ let gt = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 };
+ let b1 = vec![10.0, NODATA, 30.0, 40.0];
+ let b2 = vec![NODATA, 2.0, NODATA, 4.0];
+ let r = Raster::new("m", 2, 2, vec![b1, b2], gt, Crs::LonLat, Some(NODATA as f64), ColorHint::Gray, "Float32").unwrap();
+ let out = band_math(&r, "b1 * 2").unwrap();
+ assert_eq!(out, vec![20.0, NODATA, 60.0, 80.0]);
+ let both = band_math(&r, "b1 + b2").unwrap();
+ assert_eq!(both, vec![NODATA, NODATA, NODATA, 44.0]);
+ }
+
+ #[test]
+ fn raster_ops_turn_f64_to_f32_overflow_into_nodata() {
+ let gt = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 };
+ let r = Raster::new(
+ "big",
+ 2,
+ 1,
+ vec![vec![1e20f32, 2.0], vec![1e20f32, 3.0]],
+ gt,
+ Crs::LonLat,
+ Some(NODATA as f64),
+ ColorHint::Gray,
+ "Float32",
+ )
+ .unwrap();
+ // Each cell past the range is counted, and said; a clean result says nothing.
+ assert_eq!(band_math_reported(&r, "b1 * b2").unwrap(), (vec![NODATA, 6.0], 1));
+ assert_eq!(band_math_reported(&r, "b1 + b2").unwrap(), (vec![2e20, 5.0], 0));
+ assert_eq!(past_f32_note(1).as_deref(), Some("1 cell past the range of 32-bit floats (±3.4 × 10^38) has no value"));
+ assert_eq!(past_f32_note(0), None);
+
+ let remapped = remap(&r, 0, &[(0.0, 10.0, 1e40)], true).unwrap();
+ assert_eq!((remapped.cells[1], remapped.past_f32), (NODATA, 1));
+ assert_eq!(remap(&r, 0, &[(0.0, 10.0, 1e30)], true).unwrap().past_f32, 0);
+
+ let past =
+ |r: &Raster| r.lost.texts().filter(|t| t.contains("past the range of 32-bit floats")).map(String::from).collect::>();
+ let pts = vec![(Coord::new(0.0, 0.0), 1e40), (Coord::new(1.0, 1.0), 1e40)];
+ let ext = Extent::new(0.0, 0.0, 1.0, 1.0);
+ let idw_r = idw(&pts, &ext, 0.5, 2.0, 0, "idw", Crs::LonLat).unwrap();
+ assert!(idw_r.bands[0].data.iter().all(|&v| v == NODATA), "{:?}", idw_r.bands[0].data);
+ assert_eq!(past(&idw_r), vec!["4 cells past the range of 32-bit floats (±3.4 × 10^38) have no value".to_string()]);
+
+ let vp = crate::kriging::auto_variogram(&pts, &ext, crate::kriging::VariogramModel::Spherical);
+ let krig_r = crate::kriging::kriging(&pts, &ext, 0.5, &vp, 2, "krig", Crs::LonLat).unwrap();
+ assert!(krig_r.bands[0].data.iter().all(|&v| v == NODATA), "{:?}", krig_r.bands[0].data);
+ // Each note names the output that lost the values: here the prediction.
+ assert_eq!(past(&krig_r), vec!["krig: 4 cells past the range of 32-bit floats (±3.4 × 10^38) have no value".to_string()]);
+ // Values that fit but spread past it: the prediction keeps them, the variance can't.
+ let spread = vec![(Coord::new(0.0, 0.0), 0.0), (Coord::new(1.0, 1.0), 1e30)];
+ let vp = crate::kriging::auto_variogram(&spread, &ext, crate::kriging::VariogramModel::Spherical);
+ let spread_r = crate::kriging::kriging(&spread, &ext, 0.5, &vp, 2, "krig", Crs::LonLat).unwrap();
+ let notes = past(&spread_r);
+ assert!(!notes.is_empty() && notes.iter().all(|n| n.starts_with("krig_variance: ")), "{notes:?}");
+
+ let clean = vec![(Coord::new(0.0, 0.0), 1.0), (Coord::new(1.0, 1.0), 3.0)];
+ assert!(past(&idw(&clean, &ext, 0.5, 2.0, 0, "idw", Crs::LonLat).unwrap()).is_empty());
+ let vp = crate::kriging::auto_variogram(&clean, &ext, crate::kriging::VariogramModel::Spherical);
+ assert!(past(&crate::kriging::kriging(&clean, &ext, 0.5, &vp, 2, "krig", Crs::LonLat).unwrap()).is_empty());
+ }
+
+ #[test]
+ fn viewshed_rejects_non_finite_observer_height() {
+ let gt = GeoTransform { origin_x: 0.0, origin_y: 0.003, pixel_width: 0.001, pixel_height: -0.001 };
+ let r = Raster::new("dem", 3, 3, vec![vec![100.0; 9]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap();
+ let obs = Coord::new(0.0015, 0.0015);
+ for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
+ assert!(viewshed(&r, 0, obs, bad, 1_000.0, Heights::Nearest).is_err(), "height={bad}");
+ }
+ }
+
#[test]
fn profile_guards_nan_and_interpolates_across_antimeridian() {
// Global 1-degree LonLat raster: elevation 100 near +/-180 deg, 0 elsewhere.
diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs
index 501ea9a95b..f187aaa6b2 100644
--- a/crates/analysis/src/tools.rs
+++ b/crates/analysis/src/tools.rs
@@ -5422,12 +5422,21 @@ fn idw_interpolation(inp: &dyn Inputs, p: &Json) -> Result {
let bytes = rustgis_data::raster::geotiff::write(&r, 0).map_err(|e| e.to_string())?;
let msg = format!("IDW Interpolation: {} × {} cells from {} points", r.width, r.height, pts.len());
Ok(ToolResult {
- losses: left_out.losses("IDW Interpolation", picked.len(), field, "a coordinate is not a finite number"),
+ losses: left_out
+ .losses("IDW Interpolation", picked.len(), field, "a coordinate is not a finite number")
+ .into_iter()
+ .chain(raster_losses(&r))
+ .collect(),
output: Output::Layers(vec![OutputLayer::Raster { file_name: format!("{name}.tif"), name, bytes }]),
messages: std::iter::once(msg).chain(beyond_note).chain(crs_note).collect(),
})
}
+/// The losses an interpolated raster's notes give, such as cells past the range of 32-bit floats.
+fn raster_losses(r: &rustgis_data::raster::Raster) -> Vec {
+ r.lost.iter().filter_map(|n| n.loss.map(|code| rustgis_data::loss::LossMessage { code, text: n.text.clone() })).collect()
+}
+
/// The automatic IDW cell size: 300 cells across the extent, coarsened until every cell weighing
/// every one of `n` points stays within the interpolation's work limit.
fn idw_auto_cell(extent: &Extent, n: usize) -> f64 {
@@ -5572,12 +5581,11 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result, b: &geo::Rect) -> bool {
pub fn overlaps(ds: &Dataset, rows: &[usize]) -> Checked {
let mut p = polygons(ds, rows);
// Sweep from west to east: only polygons whose boxes overlap in x are compared.
- p.sort_by(|a, b| a.2.min().x.partial_cmp(&b.2.min().x).unwrap_or(std::cmp::Ordering::Equal));
+ p.sort_by(|a, b| a.2.min().x.total_cmp(&b.2.min().x));
let mut out = Vec::new();
let mut work = 0usize;
crate::control::begin(p.len());
diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs
index adedacaff6..5357f80e7b 100644
--- a/crates/assistant/src/agent.rs
+++ b/crates/assistant/src/agent.rs
@@ -1119,6 +1119,9 @@ impl Agent {
// Its steps count against this message's budget; its "always" approvals stay.
self.steps = self.steps.saturating_add(child.steps);
for key in &child.always {
+ if self.always.contains(key) {
+ continue;
+ }
if self.always.len() >= 64 {
self.always.remove(0);
}
@@ -1194,6 +1197,7 @@ impl Agent {
if allow
&& always
&& let Some(remembered) = self.pending_policy.as_ref().and_then(Pending::remember)
+ && !self.always.contains(&remembered)
{
if self.always.len() >= 64 {
self.always.remove(0);
@@ -1475,3 +1479,89 @@ impl Drop for Agent {
self.live.0.store(false, Ordering::SeqCst);
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::provider::Config;
+ use rustgis_engine::{Project, Session};
+ use serde_json::json;
+
+ fn test_cfg() -> Config {
+ let mut c = Config::from_env("openai");
+ c.key = "k".into();
+ c
+ }
+
+ #[test]
+ fn repeated_subagent_delegation_does_not_duplicate_or_evict_always_approvals() {
+ let mut s = Session::new(Project::default());
+ let mut a = Agent::new(test_cfg(), &s);
+
+ let reply = |body: serde_json::Value| Ok(HttpResponse { status: 200, body: body.to_string().into_bytes(), headers: vec![] });
+ let call_msg = |id: &str, name: &str, args: serde_json::Value| {
+ reply(json!({
+ "choices": [{
+ "message": {
+ "role": "assistant",
+ "content": null,
+ "tool_calls": [{
+ "id": id,
+ "type": "function",
+ "function": { "name": name, "arguments": args.to_string() }
+ }]
+ }
+ }]
+ }))
+ };
+ let say_msg = |text: &str| reply(json!({ "choices": [{ "message": { "role": "assistant", "content": text } }] }));
+
+ // Approve one action with always=true, then delegate to a subagent three times.
+ assert!(matches!(a.ask("add data", &s), Step::Send(_)));
+ let add = call_msg("e0", "run_command", json!({"command": "layer.addData", "params": {"path": "nonexistent-always.geojson"}}));
+ assert_eq!(a.receive(a.generation(), add, &mut s), Step::Confirm);
+ let asked = a.asking().unwrap_or_else(|| panic!("no approval waiting"));
+ assert!(matches!(a.decide(&asked, true, true, &mut s), Some(Step::Send(_))));
+ assert_eq!(a.always.len(), 1);
+
+ for i in 0..3 {
+ let del = call_msg(&format!("d{i}"), "delegate", json!({"task": "check map"}));
+ assert!(matches!(a.receive(a.generation(), del, &mut s), Step::Send(_)));
+ assert!(matches!(a.receive(a.generation(), say_msg("done"), &mut s), Step::Send(_)));
+ assert_eq!(a.always.len(), 1, "delegation {i} duplicated always approvals");
+ }
+ assert_eq!(a.receive(a.generation(), say_msg("all done"), &mut s), Step::Done);
+
+ // Filling all 64 slots and merging a child with an already-remembered key must not evict slot 0.
+ let mut parent = Agent::new(test_cfg(), &s);
+ for i in 0..64 {
+ assert!(matches!(parent.ask("run", &s), Step::Send(_)));
+ let c = call_msg(
+ &format!("k{i}"),
+ "run_command",
+ json!({"command": "layer.addData", "params": {"path": format!("nonexistent-{i}.geojson")}}),
+ );
+ assert_eq!(parent.receive(parent.generation(), c, &mut s), Step::Confirm);
+ let asked = parent.asking().unwrap_or_else(|| panic!("no approval waiting"));
+ assert!(matches!(parent.decide(&asked, true, true, &mut s), Some(Step::Send(_))));
+ assert_eq!(parent.receive(parent.generation(), say_msg("ok"), &mut s), Step::Done);
+ }
+ assert_eq!(parent.always.len(), 64);
+ assert!(matches!(parent.ask("delegate", &s), Step::Send(_)));
+ let del = call_msg("d-full", "delegate", json!({"task": "noop"}));
+ assert!(matches!(parent.receive(parent.generation(), del, &mut s), Step::Send(_)));
+ // Simulate a child that carries only the newest remembered key (already in parent.always).
+ if let Some(child) = parent.child.as_mut() {
+ child.always.drain(..63);
+ }
+ assert!(matches!(parent.receive(parent.generation(), say_msg("done"), &mut s), Step::Send(_)));
+ assert_eq!(parent.always.len(), 64);
+ // Re-running the oldest approved call must still be covered without prompting again.
+ let repeat_first =
+ call_msg("k0-again", "run_command", json!({"command": "layer.addData", "params": {"path": "nonexistent-0.geojson"}}));
+ assert!(
+ matches!(parent.receive(parent.generation(), repeat_first, &mut s), Step::Send(_)),
+ "duplicate key from child evicted oldest approval"
+ );
+ }
+}
diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs
index 0ac677118d..6a022dce0e 100644
--- a/crates/data/src/ogc.rs
+++ b/crates/data/src/ogc.rs
@@ -4088,7 +4088,7 @@ enum Phase {
order: WfsOrder,
},
/// An OGC API or WFS page, retaining the largest reported legacy total across the chain.
- Linked { total: Option },
+ Linked { total: Option, pages: usize, empty_streak: usize },
/// An ArcGIS page, `size` long from an offset, in `order`. `start` is the first such page's
/// first feature (a server that ignores the offset sends it again), once it is read; until
/// then `first` keeps the first page as it came, to fall back on (none: the address asked
@@ -4142,6 +4142,11 @@ fn split_page(bytes: &[u8]) -> Result