From 78ee26ab0ae723aaf18f13a30918f49689a6bf84 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:12:09 -0500 Subject: [PATCH 1/8] Fix core data, geometry, analysis, tile, assistant, and Python embed bugs Harden nine core correctness and crash paths across data readers, geodesic projection, raster and topology analysis, byte-range fetching, subagent approval merging, and Python widget URL handling, each with regression tests: - GRIB2 complex packing: compute group totals in O(1) when width_bits and length_bits are both zero, check cancellation periodically in the group validation loop, and guard width > 0 before testing missing-value sentinel bits so constant-zero groups with zero ref_bits stay valid. - SQLite reader: track accumulated local cell bytes per b-tree page (0x0d, 0x0a, 0x02, 0x05) against usable page size and reject overlapping/aliased cell pointers before large allocations. - OGC linked paging: cap total linked pages (10,000) and consecutive empty pages with next links (10) so endless empty chains stop cleanly with a notice. - Azimuthal equidistant projection: reject non-finite coordinates in Aeqd::new, Aeqd::forward, Aeqd::inverse, and Aeqd::inverse_heading with NaN instead of clamping infinity to a pole. - Floating-point sorting: replace partial_cmp().unwrap_or(Equal) with total_cmp in analysis and render sorts, selects, and Ord impls so NaN values cannot panic driftsort. - Raster operations and kriging: preserve valid pixels in band_math when only unreferenced bands hold NoData, convert f64-to-f32 overflows to NODATA instead of infinity, and reject non-finite observer height in viewshed. - Tile range reads: use saturating arithmetic for inclusive byte-range spans so #rustgis-range=0-18446744073709551615 cannot overflow u64. - Assistant subagent delegation: deduplicate remembered approvals when merging child.always back into the parent so repeated delegations do not duplicate or evict existing approvals. - Python embedded widgets: validate http/https URLs with a host in _app_src (inserting query params before #fragment) and enforce http:/https: protocol checks in _widget.js. --- apps/rustgis-python/python/rustgis/_embed.py | 13 +- apps/rustgis-python/python/rustgis/_widget.js | 8 +- apps/rustgis-python/tests/test_embed.py | 60 +++++++ crates/analysis/src/density.rs | 2 +- crates/analysis/src/kriging.rs | 7 +- crates/analysis/src/network.rs | 6 +- crates/analysis/src/rasterops.rs | 96 ++++++++--- crates/analysis/src/topology.rs | 24 ++- crates/assistant/src/agent.rs | 88 ++++++++++ crates/data/src/ogc.rs | 61 ++++++- crates/data/src/raster/grib.rs | 7 + crates/data/src/raster/grib/complex.rs | 38 ++++- crates/data/src/raster/grib_tests.rs | 45 +++++ crates/data/src/sqlite.rs | 154 ++++++++++++++++-- crates/engine/src/policy/scope.rs | 2 +- crates/geom/src/lib.rs | 33 +++- crates/render/src/effects.rs | 6 +- crates/tiles/src/cache.rs | 28 +++- 18 files changed, 611 insertions(+), 67 deletions(-) create mode 100644 apps/rustgis-python/tests/test_embed.py diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index 7dfc49e095..8fd9cfa76e 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -16,7 +16,7 @@ import pathlib import threading from typing import Any, Dict, Iterable, List, Optional, Tuple, Union -from urllib.parse import quote +from urllib.parse import quote, urlsplit, urlunsplit from . import PathLike, RustGISError, Session, _Api, _warn_losses @@ -289,10 +289,17 @@ 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 - query = "embed" + (f"&lang={quote(lang)}" if lang else "") - return base + ("&" if "?" in base else "?") + query + parts = urlsplit(base) + if parts.scheme.lower() not in ("http", "https") or not parts.netloc: + raise ValueError(f"web app url must be an http:// or https:// address with a host, got {base!r}") + extra = "embed" + (f"&lang={quote(lang)}" if lang else "") + query = f"{parts.query}&{extra}" if parts.query else extra + return urlunsplit((parts.scheme, parts.netloc, parts.path, query, parts.fragment)) def _data_args(path: PathLike) -> Tuple[str, Dict[str, Any]]: 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..a5d9343aa4 --- /dev/null +++ b/apps/rustgis-python/tests/test_embed.py @@ -0,0 +1,60 @@ +"""URL construction and validation for the embedded web app widgets.""" + +import pathlib +import subprocess +import shutil + +import pytest + +from rustgis._embed import DEFAULT_URL, WIDGET_JS, _app_src + + +def test_app_src_preserves_query_and_fragment(monkeypatch): + monkeypatch.delenv("RUSTGIS_WEB_URL", raising=False) + assert _app_src(None, None) == f"{DEFAULT_URL}?embed" + assert _app_src("http://127.0.0.1:8772/", "de") == "http://127.0.0.1:8772/?embed&lang=de" + assert _app_src("https://web.rustgis.app/?foo=1", "fr") == "https://web.rustgis.app/?foo=1&embed&lang=fr" + assert _app_src("https://web.rustgis.app/#map", None) == "https://web.rustgis.app/?embed#map" + assert _app_src("https://web.rustgis.app/?foo=1#map", "de") == "https://web.rustgis.app/?foo=1&embed&lang=de#map" + + +@pytest.mark.parametrize( + "bad_url", + [ + "javascript:alert(1)", + "JAVASCRIPT:alert(1)", + "data:text/html,

x

", + "file:///etc/passwd", + "https://", + "http://", + "/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_rejects_non_http_protocol(): + node = shutil.which("node") + if node is None: + pytest.skip("node not installed") + script = f""" +import widget from {WIDGET_JS.as_uri()!r}; +globalThis.window = {{ location: {{ href: "https://notebook.example/" }}, addEventListener() {{}}, removeEventListener() {{}} }}; +globalThis.document = {{ createElement() {{ return {{ style: {{}} }}; }} }}; +const badModel = {{ get: (k) => (k === "_src" ? "javascript:alert(1)" : ""), on() {{}}, off() {{}} }}; +let threw = false; +try {{ + widget.render({{ model: badModel, el: {{ appendChild() {{}} }} }}); +}} catch (e) {{ + threw = true; +}} +if (!threw) {{ + console.error("expected _widget.js to reject javascript: URL"); + 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/density.rs b/crates/analysis/src/density.rs index 32bc049017..3a2627081f 100644 --- a/crates/analysis/src/density.rs +++ b/crates/analysis/src/density.rs @@ -100,7 +100,7 @@ pub fn silverman_bandwidth(points: &[(Coord, f64)], extent: &Extent) -> f64 { (((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2)).sqrt(), weight) }) .collect(); - dists.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); + dists.sort_by(|a, b| a.0.total_cmp(&b.0)); let half_w = sum_w * 0.5; let mut cum_w = 0.0; diff --git a/crates/analysis/src/kriging.rs b/crates/analysis/src/kriging.rs index 9fa3276999..93b7b83e07 100644 --- a/crates/analysis/src/kriging.rs +++ b/crates/analysis/src/kriging.rs @@ -387,13 +387,14 @@ 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 }; + let (p, v) = (val as f32, var_est as f32); + *pred = if p.is_finite() { p } else { NODATA }; + *var = if v.is_finite() { v } else { NODATA }; } })?; diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 907f4b7150..ca8d955229 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) } } @@ -969,7 +969,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 1fab346287..07956d733c 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -99,7 +99,7 @@ fn per_cell_on(threads: Option, r: &Raster, cost: usize, f: impl Fn(i64, || (), |_, row, line: &mut [f32]| { for (col, slot) in line.iter_mut().enumerate() { - *slot = f(col as i64, row as i64).filter(|v| v.is_finite()).map(|v| v as f32).unwrap_or(NODATA); + *slot = f(col as i64, row as i64).map(|v| v as f32).filter(|v| v.is_finite()).unwrap_or(NODATA); } }, )?; @@ -151,7 +151,7 @@ fn terrain_on(threads: Option, r: &Raster, data: &[f32], zf: f64, f: impl if w < 3 || h < 3 || data.len() != len { return per_cell(r, 1, scalar); } - let value = |v: Option| v.filter(|v| v.is_finite()).map(|v| v as f32).unwrap_or(NODATA); + let value = |v: Option| v.map(|v| v as f32).filter(|v| v.is_finite()).unwrap_or(NODATA); let mut out = new_band(w, h, NODATA)?; // A cell's gradient and its function cost about one unit of the threshold's (some 30 ns). let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_rows(h, len, 0)); @@ -266,19 +266,14 @@ fn band_math_on(threads: Option, r: &Raster, expr: &str) -> Result 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)) => { + let out = *new as f32; + if out.is_finite() { out } else { NODATA } + } None if keep => v, None => NODATA, } @@ -405,7 +403,8 @@ pub fn weighted_overlay(criteria: &[(Vec, f64)]) -> Result, String } s += v as f64 * w.max(0.0) / total; } - s as f32 + let out = s as f32; + if out.is_finite() { out } else { NODATA } }, ) } @@ -658,6 +657,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; let (cx, cy) = r.cell_size_m(); @@ -858,7 +860,7 @@ fn idw_on( near.extend(points.iter().map(|(p, v)| (d2(p).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) { @@ -873,7 +875,8 @@ fn idw_on( }); num / den }; - *o = if v.is_finite() { v as f32 } else { NODATA }; + let out = v as f32; + *o = if out.is_finite() { out } else { NODATA }; } }, )?; @@ -918,7 +921,7 @@ fn kmeans_on(threads: Option, r: &Raster, bands: &[usize], k: usize, iter sorted.sort_by(|a, b| { let (va, vb) = (pixel(*a).and_then(|p| p.first().copied()).unwrap_or(0.0), pixel(*b).and_then(|p| p.first().copied()).unwrap_or(0.0)); - va.partial_cmp(&vb).unwrap_or(std::cmp::Ordering::Equal) + va.total_cmp(&vb) }); let mut centres: Vec> = (0..k).filter_map(|i| sorted.get((i * 2 + 1) * sorted.len() / (2 * k)).and_then(|j| pixel(*j))).collect(); @@ -926,7 +929,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) }; for _ in 0..iterations.clamp(1, 50) { @@ -951,7 +954,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); @@ -1004,7 +1009,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) }, ) @@ -3255,4 +3260,57 @@ mod tests { assert_eq!(got, Some((vec![1.0], inside)), "{x0} {x1} {y0} {y1}"); } } + + #[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(); + let prod = band_math(&r, "b1 * b2").unwrap(); + assert_eq!(prod, vec![NODATA, 6.0]); + + let remapped = remap(&r, 0, &[(0.0, 10.0, 1e40)], true).unwrap(); + assert_eq!(remapped.cells[1], NODATA); + + 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); + + 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); + } + + #[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}"); + } + } } diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 873e45b5c8..293eb47c59 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -143,7 +143,7 @@ fn rects_touch(a: &geo::Rect, 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()); @@ -222,7 +222,7 @@ fn self_crossing(path: &[Coord], closed: bool) -> Result, Coord> { let mut order: Vec = (0..n).collect(); order.sort_by(|a, b| { let (sa, sb) = (segs.get(*a).map_or(0.0, minx), segs.get(*b).map_or(0.0, minx)); - sa.partial_cmp(&sb).unwrap_or(std::cmp::Ordering::Equal) + sa.total_cmp(&sb) }); let mut work = 0usize; for (k, &i) in order.iter().enumerate() { @@ -1683,4 +1683,24 @@ mod tests { // and west of everything: reported. assert_eq!(reported, [1, 2, 3, 4, 5, 6]); } + + #[test] + fn self_intersections_with_nan_vertices_never_panics() { + // Interleave finite and NaN pairs so the sweep sort sees both NaN and finite segment + // min-x keys across enough elements to exercise driftsort's ordering check. + let mut path = Vec::new(); + for i in 0..40 { + if i % 3 == 0 { + path.push(Coord::new(f64::NAN, f64::NAN)); + path.push(Coord::new(f64::NAN, f64::NAN)); + } else { + let x = ((i * 17) % 31) as f64 * 0.01; + path.push(Coord::new(x, i as f64 * 0.01)); + } + } + let mut ds = Dataset::new("nan_line", GeometryType::Polyline, vec![]); + ds.push(Some(Geometry::Line(vec![path])), vec![]); + let checked = self_intersections(&ds, &[0]); + assert!(checked.complete); + } } diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index 1811368753..72458ce21c 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -1039,6 +1039,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); } @@ -1108,6 +1111,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); @@ -1374,3 +1378,87 @@ 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); + assert!(matches!(a.decide(true, true, &mut s), 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); + assert!(matches!(parent.decide(true, true, &mut s), 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 724e595ddf..934d7c62ba 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -3823,7 +3823,7 @@ enum Phase { duplicates: usize, }, /// 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 @@ -3860,6 +3860,11 @@ fn split_page(bytes: &[u8]) -> Result, max: usize, paging: Option = None; let following = match &mut self.phase { Phase::WfsOffsets { matched, offset, size, ids, unidentified, overlap, duplicates } => { let returned = more.len(); @@ -4323,9 +4336,25 @@ impl Pages { } exceeded(&page).then(|| arcgis_page_url(&self.url, read + more.len(), *size, order.as_deref())) } - Phase::Linked { total } => { + Phase::Linked { total, pages, empty_streak } => { *total = (*total).max(page.get("totalFeatures").and_then(serde_json::Value::as_u64)); - next_page(&self.next, &page) + *pages += 1; + if more.is_empty() { + *empty_streak += 1; + } else { + *empty_streak = 0; + } + let next = next_page(&self.next, &page); + if next.is_some() { + if *empty_streak >= MAX_EMPTY_LINKED_PAGES { + linked_stop = Some(format!( + "the server sent {MAX_EMPTY_LINKED_PAGES} empty pages in a row while still giving a next link; the rest aren't read" + )); + } else if *pages >= MAX_LINKED_PAGES { + linked_stop = Some(format!("the server's next links ran past {MAX_LINKED_PAGES} pages; the rest aren't read")); + } + } + next } _ => next_page(&self.next, &page), }; @@ -4338,6 +4367,9 @@ impl Pages { if self.features.len() > self.max { return self.finish_at_max(); } + if let Some(why) = linked_stop { + return self.stop(why); + } match following { Some(n) => { self.from = std::mem::replace(&mut self.next, n); @@ -4350,7 +4382,7 @@ impl Pages { self.phase = Phase::WfsHits; self.advance() } - None if let Phase::Linked { total } = self.phase + None if let Phase::Linked { total, .. } = self.phase && is_legacy_wfs_query(&self.url) => { let read = self.features.len(); @@ -9324,4 +9356,23 @@ mod tests { assert_eq!(s.listed, Some(MAX_LISTED_LAYERS)); assert!(!s.notes.iter().any(|n| n.contains(PAST_READ_LIMIT)), "{:?}", s.notes); } + + #[test] + fn linked_pages_stop_on_endless_empty_next_chain() { + let url = "https://api.example.org/collections/a/items?page=0"; + let empty = |next: usize| { + format!( + r#"{{"type":"FeatureCollection","features":[],"links":[{{"rel":"next","type":"application/geo+json","href":"items?page={next}"}}]}}"# + ) + .into_bytes() + }; + let mut calls = 0usize; + let (_joined, note) = join_pages(url, empty(1), 100, |_u| { + calls += 1; + assert!(calls <= 100, "linked paging did not stop on endless empty next links"); + Ok(empty(calls + 1)) + }); + assert!(calls <= 10, "expected cutoff after consecutive empty pages, got {calls} fetches"); + assert!(note.is_some_and(|n| n.contains("empty pages")), "missing empty-page stop notice"); + } } diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index b49d5cf68f..1fa8ceb54c 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -198,6 +198,7 @@ fn read_limited(mut source: R, name: &str, sidecar_nodata: Optio fields.push(f); } } + Err(Skip::Cancelled) => return Err(DataError::Cancelled), Err(Skip::TooLarge) => skipped.over_limit += 1, Err(Skip::OtherGrid) => skipped.other_grid += 1, Err(Skip::Other(why)) => skipped.add(why), @@ -466,6 +467,7 @@ fn count_fields(source: &mut R, start: u64, len: u64, grib2: boo /// packing, a grid), or damage; each reason is said once with a count. #[derive(Clone)] enum Skip { + Cancelled, TooLarge, /// On another grid than the first field kept: told before it is decoded, so it takes none of /// the room a later field on that grid may need. @@ -1255,7 +1257,12 @@ fn grib2(b: &[u8], room: usize, mut first: Option, uncounted: Uncounted) - first.get_or_insert(grid); Ok(Field { name: format!("{reference}:discipline={discipline}:{product}"), grid, values, rounded, past }) })(); + let cancelled = matches!(field, Err(Skip::Cancelled)); out.push(field); + if cancelled { + broken = true; + break; + } } _ => {} } diff --git a/crates/data/src/raster/grib/complex.rs b/crates/data/src/raster/grib/complex.rs index 318e8a0cb7..1330538782 100644 --- a/crates/data/src/raster/grib/complex.rs +++ b/crates/data/src/raster/grib/complex.rs @@ -110,13 +110,31 @@ impl Complex { too_large: false, }; let (mut held, mut need) = (0u64, at); - for g in 0..self.groups { - let (width, length) = values.size(g); - if width > u64::from(MAX_BITS) { - return Err(Skip::Other(format!("values of {width} bits"))); + if self.width_bits == 0 && self.length_bits == 0 { + if self.groups > 0 { + let width = u64::from(self.width_ref); + if width > u64::from(MAX_BITS) { + return Err(Skip::Other(format!("values of {width} bits"))); + } + let before = (self.groups - 1) as u64; + let len_ref = u64::from(self.length_ref); + let last_len = u64::from(self.last_length); + held = before.saturating_mul(len_ref).saturating_add(last_len); + need = + at.saturating_add(before.saturating_mul(width.saturating_mul(len_ref))).saturating_add(width.saturating_mul(last_len)); + } + } else { + for g in 0..self.groups { + if g & 0xfff == 0 && crate::progress::check().is_err() { + return Err(Skip::Cancelled); + } + let (width, length) = values.size(g); + if width > u64::from(MAX_BITS) { + return Err(Skip::Other(format!("values of {width} bits"))); + } + held = held.saturating_add(length); + need = need.saturating_add(width.saturating_mul(length)); } - held = held.saturating_add(length); - need = need.saturating_add(width.saturating_mul(length)); } if held != count as u64 { return Err(Skip::Damaged("a field whose groups don't hold its values".to_string())); @@ -198,9 +216,11 @@ impl Values<'_> { // reference of a group of no bits. if p.missing > 0 { let (v, width) = if self.width == 0 { (self.reference, p.ref_bits) } else { (packed, self.width) }; - let ones = (1u64 << width) - 1; - if v == ones || (p.missing == 2 && v + 1 == ones) { - return None; + if width > 0 { + let ones = (1u64 << width) - 1; + if v == ones || (p.missing == 2 && v + 1 == ones) { + return None; + } } } // At most 33 bits, so the sums below are far from `i64`'s range. diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index 1e030aa615..091e8ef313 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -1543,3 +1543,48 @@ fn hostile_complex_packing_never_panics() { } } } + +#[test] +fn complex_packing_constant_zero_group_with_zero_ref_bits_is_not_missing() { + for missing in [1, 2] { + let mut c = Cx::new(&[(0, 0, &[0, 0, 0])]); + c.ref_bits = 0; + c.missing = missing; + assert_eq!(there(&c.values()), [Some(0.0), Some(0.0), Some(0.0)], "missing={missing}"); + } +} + +#[test] +fn complex_packing_zero_width_and_length_bits_and_cancellation() { + // Zero width_bits and zero length_bits: O(1) validation for uniform group widths/lengths. + let c = Cx::new(&[(0, 0, &[0, 0]), (0, 0, &[0, 0]), (0, 0, &[0])]); + let (mut s5, _) = c.sections(); + s5[19] = 0; // ref_bits = 0 + s5[35] = 0; // width_ref = 0 + s5[36] = 0; // width_bits = 0 + s5[37..41].copy_from_slice(&u(2, 4)); // length_ref = 2 + s5[42..46].copy_from_slice(&u(1, 4)); // last_length = 1 + s5[46] = 0; // length_bits = 0 + let s7 = [0, 0, 0, 5, 7]; + let r = read_bytes(&c.message_of(&s5, &s7), "t").unwrap(); + assert_eq!(r.bands[0].data, vec![0.0; 5]); + + // width_ref past MAX_BITS is still rejected on the O(1) path. + let mut bad_width = s5.clone(); + bad_width[35] = 33; + refused(&c.message_of(&bad_width, &s7), "values of 33 bits"); + + // Cancellation stops the group-validation loop when width_bits or length_bits is non-zero. + struct AlwaysCancelled; + impl crate::progress::Probe for AlwaysCancelled { + fn cancelled(&self) -> bool { + true + } + fn begin(&self, _: u64) {} + fn advance(&self, _: u64) {} + } + let msg = Cx::new(&[(7, 3, &[5]), (300, 0, &[0; 5]), (2, 9, &[0, 511, 100])]).message(); + let _guard = crate::progress::install(Some(std::sync::Arc::new(AlwaysCancelled))); + let decoded = grib2(&msg, usize::MAX, None, Uncounted::default()); + assert!(decoded.first().is_some_and(std::result::Result::is_err), "expected cancellation error"); +} diff --git a/crates/data/src/sqlite.rs b/crates/data/src/sqlite.rs index 7fd2368f4e..89381413df 100644 --- a/crates/data/src/sqlite.rs +++ b/crates/data/src/sqlite.rs @@ -112,20 +112,38 @@ impl> Db { match kind { // An interior table page: child pointers, then the right-most child. 0x05 => { + let mut used = hdr.saturating_add(12).saturating_add(2usize.saturating_mul(cells)); + if used > self.usable { + return Err(bad("overlapping cells")); + } let mut children = Vec::with_capacity(cells + 1); for i in 0..cells { let at = be16(page, hdr + 12 + 2 * i).ok_or_else(|| bad("cell pointer"))?; - children.push(be32(page, at).ok_or_else(|| bad("interior cell"))?); + let child = be32(page, at).ok_or_else(|| bad("interior cell"))?; + let (_, a) = varint(page, at + 4).ok_or_else(|| bad("interior cell"))?; + used = used.saturating_add(a - at); + if used > self.usable { + return Err(bad("overlapping cells")); + } + children.push(child); } children.push(be32(page, hdr + 8).ok_or_else(|| bad("page header"))?); stack.extend(children.into_iter().rev()); } // A leaf table page: (payload size, rowid, payload) cells. 0x0d => { + let mut used = hdr.saturating_add(8).saturating_add(2usize.saturating_mul(cells)); + if used > self.usable { + return Err(bad("overlapping cells")); + } for i in 0..cells { let at = be16(page, hdr + 8 + 2 * i).ok_or_else(|| bad("cell pointer"))?; let (size, a) = varint(page, at).ok_or_else(|| bad("leaf cell"))?; let (rowid, a) = varint(page, a).ok_or_else(|| bad("leaf cell"))?; + used = used.saturating_add(self.cell_local_span(a - at, size, self.usable - 35)?); + if used > self.usable { + return Err(bad("overlapping cells")); + } let payload = self.payload_seen(page, a, size, &mut seen)?; if f(rowid as i64, record(&payload)?).is_break() { return Ok(()); @@ -171,11 +189,20 @@ impl> Db { // An interior index page: (left child, payload size, payload) cells, then the // right-most child. Each cell's entry comes after its left child's. 0x02 => { + let mut used = hdr.saturating_add(12).saturating_add(2usize.saturating_mul(cells)); + if used > self.usable { + return Err(bad("overlapping cells")); + } let mut steps = Vec::with_capacity(2 * cells + 1); for i in 0..cells { let at = be16(page, hdr + 12 + 2 * i).ok_or_else(|| bad("cell pointer"))?; - steps.push(Step::Page(be32(page, at).ok_or_else(|| bad("interior cell"))?)); + let child = be32(page, at).ok_or_else(|| bad("interior cell"))?; let (size, a) = varint(page, at + 4).ok_or_else(|| bad("interior cell"))?; + used = used.saturating_add(self.cell_local_span(a - at, size, max_local)?); + if used > self.usable { + return Err(bad("overlapping cells")); + } + steps.push(Step::Page(child)); steps.push(Step::Entry(self.payload_with(page, a, size, max_local, Some(&mut seen))?)); } steps.push(Step::Page(be32(page, hdr + 8).ok_or_else(|| bad("page header"))?)); @@ -183,9 +210,17 @@ impl> Db { } // A leaf index page: (payload size, payload) cells. 0x0a => { + let mut used = hdr.saturating_add(8).saturating_add(2usize.saturating_mul(cells)); + if used > self.usable { + return Err(bad("overlapping cells")); + } for i in 0..cells { let at = be16(page, hdr + 8 + 2 * i).ok_or_else(|| bad("cell pointer"))?; let (size, a) = varint(page, at).ok_or_else(|| bad("leaf cell"))?; + used = used.saturating_add(self.cell_local_span(a - at, size, max_local)?); + if used > self.usable { + return Err(bad("overlapping cells")); + } let payload = self.payload_with(page, a, size, max_local, Some(&mut seen))?; if f(record(&payload)?).is_break() { return Ok(()); @@ -214,9 +249,19 @@ impl> Db { let cells = be16(page, hdr + 3).ok_or_else(|| bad("page header"))?; match page.get(hdr) { Some(0x05) => { + let mut used = hdr.saturating_add(12).saturating_add(2usize.saturating_mul(cells)); + if used > self.usable { + return Err(bad("overlapping cells")); + } for i in 0..cells { let at = be16(page, hdr + 12 + 2 * i).ok_or_else(|| bad("cell pointer"))?; - stack.push(be32(page, at).ok_or_else(|| bad("interior cell"))?); + let child = be32(page, at).ok_or_else(|| bad("interior cell"))?; + let (_, a) = varint(page, at + 4).ok_or_else(|| bad("interior cell"))?; + used = used.saturating_add(a - at); + if used > self.usable { + return Err(bad("overlapping cells")); + } + stack.push(child); } stack.push(be32(page, hdr + 8).ok_or_else(|| bad("page header"))?); } @@ -227,6 +272,31 @@ impl> Db { Ok(n_rows) } + /// How many bytes of a `size`-byte payload sit on the b-tree page itself (SQLite's rule). + fn local_len(&self, size: usize, max_local: usize) -> usize { + if size <= max_local { + size + } else { + let u = self.usable; + let min_local = (u - 12) * 32 / 255 - 23; + let k = min_local + (size - min_local) % (u - 4); + if k <= max_local { k } else { min_local } + } + } + + /// The bytes a cell occupies on its b-tree page: header, local payload and optional 4-byte + /// overflow pointer. + fn cell_local_span(&self, header_len: usize, size: u64, max_local: usize) -> Result { + let total = self.bytes.as_ref().len() as u64; + if size > total { + return Err(bad("a payload larger than the file")); + } + let size = size as usize; + let local = self.local_len(size, max_local); + let overflow = if local < size { 4 } else { 0 }; + header_len.checked_add(local).and_then(|n| n.checked_add(overflow)).ok_or_else(|| bad("overlapping cells")) + } + /// A cell's payload of `size` bytes starting at `at` on `page`, following its overflow pages. /// [`Db::payload`] during a scan: each overflow page may be read only once. fn payload_seen(&self, page: &[u8], at: usize, size: u64, seen: &mut [bool]) -> Result, String> { @@ -241,13 +311,7 @@ impl> Db { let size = size as usize; let u = self.usable; // How much of the payload is on the page itself (the SQLite file format's rule). - let local = if size <= max_local { - size - } else { - let min_local = (u - 12) * 32 / 255 - 23; - let k = min_local + (size - min_local) % (u - 4); - if k <= max_local { k } else { min_local } - }; + let local = self.local_len(size, max_local); // Grown as pages are read: a forged size can't make a large allocation up front. let mut out = Vec::with_capacity(size.min(local + 4096)); out.extend_from_slice(page.get(at..at + local).ok_or_else(|| bad("a cell past its page"))?); @@ -690,6 +754,76 @@ mod tests { assert_eq!(db.page(2).unwrap_err(), bad("page offset")); } + #[test] + fn overlapping_cell_pointers_are_rejected() { + let make_db = |page2: [u8; 512]| { + let mut bytes = vec![0u8; 512 * 3]; + bytes[..16].copy_from_slice(b"SQLite format 3\0"); + bytes[16..18].copy_from_slice(&512u16.to_be_bytes()); + bytes[56..60].copy_from_slice(&1u32.to_be_bytes()); + bytes[512..1024].copy_from_slice(&page2); + // Page 3: empty leaf page so valid child pointers would resolve if not rejected. + bytes[1024] = 0x0d; + Db::open(bytes).unwrap() + }; + + // 0x0d leaf table page: 60 pointers all aliasing one 20-byte cell at offset 450. + let mut leaf_table = [0u8; 512]; + leaf_table[0] = 0x0d; + leaf_table[3..5].copy_from_slice(&60u16.to_be_bytes()); + for i in 0..60usize { + leaf_table[8 + 2 * i..10 + 2 * i].copy_from_slice(&450u16.to_be_bytes()); + } + // Cell at 450: payload size = 20, rowid = 1, 20-byte record (header 2, type 0 = NULL, 18 pad). + leaf_table[450] = 20; + leaf_table[451] = 1; + leaf_table[452] = 2; + leaf_table[453] = 0; + let db = make_db(leaf_table); + assert_eq!(db.scan(2, |_, _| ControlFlow::Continue(())).unwrap_err(), bad("overlapping cells")); + + // 0x0a leaf index page: 60 pointers all aliasing one 20-byte cell at offset 450. + let mut leaf_index = [0u8; 512]; + leaf_index[0] = 0x0a; + leaf_index[3..5].copy_from_slice(&60u16.to_be_bytes()); + for i in 0..60usize { + leaf_index[8 + 2 * i..10 + 2 * i].copy_from_slice(&450u16.to_be_bytes()); + } + leaf_index[450] = 20; + leaf_index[451] = 2; + leaf_index[452] = 0; + let db = make_db(leaf_index); + assert_eq!(db.scan_index(2, |_| ControlFlow::Continue(())).unwrap_err(), bad("overlapping cells")); + + // 0x02 interior index page: 60 pointers all aliasing one cell at offset 450. + let mut interior_index = [0u8; 512]; + interior_index[0] = 0x02; + interior_index[3..5].copy_from_slice(&60u16.to_be_bytes()); + interior_index[8..12].copy_from_slice(&3u32.to_be_bytes()); + for i in 0..60usize { + interior_index[12 + 2 * i..14 + 2 * i].copy_from_slice(&450u16.to_be_bytes()); + } + interior_index[450..454].copy_from_slice(&3u32.to_be_bytes()); + interior_index[454] = 20; + interior_index[455] = 2; + interior_index[456] = 0; + let db = make_db(interior_index); + assert_eq!(db.scan_index(2, |_| ControlFlow::Continue(())).unwrap_err(), bad("overlapping cells")); + + // 0x05 interior table page: 90 pointers all aliasing one 5-byte cell at offset 480. + let mut interior_table = [0u8; 512]; + interior_table[0] = 0x05; + interior_table[3..5].copy_from_slice(&90u16.to_be_bytes()); + interior_table[8..12].copy_from_slice(&3u32.to_be_bytes()); + for i in 0..90usize { + interior_table[12 + 2 * i..14 + 2 * i].copy_from_slice(&480u16.to_be_bytes()); + } + interior_table[480..484].copy_from_slice(&3u32.to_be_bytes()); + interior_table[484] = 1; + let db = make_db(interior_table); + assert_eq!(db.scan(2, |_, _| ControlFlow::Continue(())).unwrap_err(), bad("overlapping cells")); + } + #[test] fn create_table_columns() { let (cols, pk) = parse_create_table( diff --git a/crates/engine/src/policy/scope.rs b/crates/engine/src/policy/scope.rs index 697f0a3608..4b751ad588 100644 --- a/crates/engine/src/policy/scope.rs +++ b/crates/engine/src/policy/scope.rs @@ -162,7 +162,7 @@ pub struct Permit { pub(super) plan: Arc, pub(super) request: String, } -#[derive(Clone)] +#[derive(Clone, PartialEq)] pub struct Remembered { pub(super) plan: Arc, } diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 5c8eb7fcfc..60e0b3ed76 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -843,11 +843,18 @@ pub struct Aeqd { impl Aeqd { pub fn new(centre: Coord) -> Self { + if !centre.is_finite() { + return Aeqd { lon0: f64::NAN, lat0: f64::NAN }; + } Aeqd { lon0: centre.x, lat0: centre.y.clamp(-90.0, 90.0) } } - /// Lon/lat (degrees) → metres from the centre. + /// Lon/lat (degrees) → metres from the centre. Non-finite coordinates give no place (both + /// coordinates NaN). pub fn forward(&self, c: Coord) -> Coord { + if !(self.lon0.is_finite() && self.lat0.is_finite() && c.is_finite()) { + return Coord::new(f64::NAN, f64::NAN); + } let (s12, azi1, _, _): (f64, f64, f64, f64) = WGS84.inverse(self.lat0, self.lon0, c.y.clamp(-90.0, 90.0), c.x); let (sa, ca) = azi1.to_radians().sin_cos(); Coord::new(s12 * sa, s12 * ca) @@ -857,7 +864,7 @@ impl Aeqd { /// not folded into −180..180, so a shape across the antimeridian stays in one piece. Metres /// that aren't finite give no place (both coordinates NaN). pub fn inverse(&self, p: Coord) -> Coord { - if !(p.x.is_finite() && p.y.is_finite()) { + if !(self.lon0.is_finite() && self.lat0.is_finite() && p.is_finite()) { return Coord::new(f64::NAN, f64::NAN); } // At a pole the azimuth is taken from the meridian `lon0`, as `forward` gives it. @@ -869,7 +876,7 @@ impl Aeqd { /// center arrives there with: a direction carried along it turns as much as that differs from /// the azimuth it left with, `p.x.atan2(p.y)`. pub fn inverse_heading(&self, p: Coord) -> (Coord, f64) { - if !(p.x.is_finite() && p.y.is_finite()) { + if !(self.lon0.is_finite() && self.lat0.is_finite() && p.is_finite()) { return (Coord::new(f64::NAN, f64::NAN), f64::NAN); } let (lat, lon, azi2): (f64, f64, f64) = WGS84.direct(self.lat0, self.lon0, p.x.atan2(p.y).to_degrees(), p.x.hypot(p.y)); @@ -1644,6 +1651,26 @@ mod tests { } } + #[test] + fn aeqd_rejects_non_finite_coordinates() { + let proj = Aeqd::new(Coord::new(10.0, 45.0)); + for bad in [ + Coord::new(10.0, f64::INFINITY), + Coord::new(10.0, f64::NEG_INFINITY), + Coord::new(f64::INFINITY, 45.0), + Coord::new(f64::NEG_INFINITY, 45.0), + Coord::new(10.0, f64::NAN), + ] { + let m = proj.forward(bad); + assert!(m.x.is_nan() && m.y.is_nan(), "forward({bad:?}) = {m:?}"); + let bad_centre = Aeqd::new(bad); + let fwd = bad_centre.forward(Coord::new(10.0, 45.0)); + assert!(fwd.x.is_nan() && fwd.y.is_nan(), "Aeqd::new({bad:?}).forward = {fwd:?}"); + let inv = bad_centre.inverse(Coord::new(1_000.0, 1_000.0)); + assert!(inv.x.is_nan() && inv.y.is_nan(), "Aeqd::new({bad:?}).inverse = {inv:?}"); + } + } + #[test] fn geodesic_destination_and_interpolation() { // Destinations on WGS 84 from GeographicLib (pyproj.Geod(ellps="WGS84").fwd): 10 km from diff --git a/crates/render/src/effects.rs b/crates/render/src/effects.rs index 109c2ca80d..cfc75f1625 100644 --- a/crates/render/src/effects.rs +++ b/crates/render/src/effects.rs @@ -154,7 +154,7 @@ fn shapes( } // Painted by where they stand on the ground: a part raised over a building behind it may be // painted under it; the GPU's depth buffer has no such limit. - shapes.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); + shapes.sort_by(|a, b| a.0.total_cmp(&b.0)); shapes } @@ -467,7 +467,7 @@ pub fn tilted_walls( walls.push(TiltedWall { depth: mid.1, quad: [fa, fb, tb, ta], top, foot }); } } - walls.sort_by(|a, b| a.depth.partial_cmp(&b.depth).unwrap_or(std::cmp::Ordering::Equal)); + walls.sort_by(|a, b| a.depth.total_cmp(&b.depth)); walls } @@ -582,7 +582,7 @@ pub(crate) fn extrude_tilted( shapes.push((cam.ground_px(centroid).1, rings, holes, base, up, t * t * (3.0 - 2.0 * t), row)); } // Far (up the screen) first. - shapes.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); + shapes.sort_by(|a, b| a.0.total_cmp(&b.0)); let at = |u: f64, v: f64, up: f64| cam.project_raised(u, v, up, w, h).map(|(x, y)| (x as f32 * ppp, y as f32 * ppp)); let path = |pts: &[(f32, f32)]| { let mut pb = PathBuilder::new(); diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index 0eab06da51..1960e94d2e 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -3648,7 +3648,7 @@ mod native { if let Some(local) = url.strip_prefix(LOCAL) { let (path, range) = super::split_range(local); let (a, b) = range.ok_or("a local read without a range")?; - return crate::pmtiles::read_file(path, a, b - a + 1) + return crate::pmtiles::read_file(path, a, b.saturating_sub(a).saturating_add(1)) .map(|bytes| Fetched { bytes, origin: Origin::named(url) }) .map_err(Failure::from); } @@ -3856,10 +3856,11 @@ mod native { return Err(format!("larger than {max} bytes").into()); } if let Some((a, b)) = range.filter(|_| whole) { - if buf.len() as u64 > b - a + 1 { + let span = b.saturating_sub(a).saturating_add(1); + if buf.len() as u64 > span { return Err(rustgis_data::diagnostics::message_with_address(url, super::NO_RANGES).into()); } - buf.truncate(usize::try_from(b - a + 1).unwrap_or(usize::MAX)); + buf.truncate(usize::try_from(span).unwrap_or(usize::MAX)); } Ok(Fetched { bytes: buf, origin }) })(); @@ -8033,4 +8034,25 @@ Connection: close assert_eq!(ceiling_for(&tile), crate::address::Reach::Public); assert!(matches!(get_tile(&tile, Want::Image), State::Failed(_))); } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn full_u64_range_does_not_overflow() { + let _turn = turn(); + // HTTP 200 whole-file answer to `#rustgis-range=0-18446744073709551615`. + let base = serve(vec!["HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: close\r\n\r\nhello".into()]); + let (tx, rx) = std::sync::mpsc::channel(); + native::fetch(format!("{base}/file.bin#rustgis-range=0-18446744073709551615"), Box::new(move |r| tx.send(r).unwrap()), &[]); + let bytes = rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap().unwrap(); + assert_eq!(bytes, b"hello"); + + // Local file read with `#rustgis-range=0-18446744073709551615`. + let path = std::env::temp_dir().join(format!("rustgis-range-max-{}.bin", std::process::id())); + std::fs::write(&path, b"world").unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + native::fetch_local(format!("{}#rustgis-range=0-18446744073709551615", path.display()), Box::new(move |r| tx.send(r).unwrap())); + let bytes = rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap().unwrap(); + let _ = std::fs::remove_file(&path); + assert_eq!(bytes, b"world"); + } } From 5ee0d2f9390b9a6ec4f551e9957f4e52f0d72a22 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:27:52 -0500 Subject: [PATCH 2/8] Address PR review comments on embed URL checks, GRIB test, and OGC empty cutoff - Require a non-empty hostname in `_app_src` so port-only URLs like `https://:443` are rejected while valid `host:port` URLs pass. - Clean up `test_embed.py` (drop unused `pathlib` import) and copy `_widget.js` to a temporary `.mjs` file for ESM import in Node. - Append a second valid field in the GRIB2 cancellation test and assert `Err(Skip::Cancelled)` with immediate stop before the second field. - Raise `MAX_EMPTY_LINKED_PAGES` in `crates/data/src/ogc.rs` from 10 to 50 so filtered servers can return more empty pages before stopping. --- apps/rustgis-python/python/rustgis/_embed.py | 2 +- apps/rustgis-python/tests/test_embed.py | 11 +++++++---- crates/data/src/ogc.rs | 6 +++--- crates/data/src/raster/grib_tests.rs | 10 ++++++++-- 4 files changed, 19 insertions(+), 10 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index 8fd9cfa76e..5b21494818 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -295,7 +295,7 @@ def _app_src(url: Optional[str], lang: Optional[str]) -> str: """ 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: + 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}") extra = "embed" + (f"&lang={quote(lang)}" if lang else "") query = f"{parts.query}&{extra}" if parts.query else extra diff --git a/apps/rustgis-python/tests/test_embed.py b/apps/rustgis-python/tests/test_embed.py index a5d9343aa4..90df97f562 100644 --- a/apps/rustgis-python/tests/test_embed.py +++ b/apps/rustgis-python/tests/test_embed.py @@ -1,8 +1,7 @@ """URL construction and validation for the embedded web app widgets.""" -import pathlib -import subprocess import shutil +import subprocess import pytest @@ -13,6 +12,7 @@ def test_app_src_preserves_query_and_fragment(monkeypatch): monkeypatch.delenv("RUSTGIS_WEB_URL", raising=False) assert _app_src(None, None) == f"{DEFAULT_URL}?embed" assert _app_src("http://127.0.0.1:8772/", "de") == "http://127.0.0.1:8772/?embed&lang=de" + assert _app_src("https://example.com:8443/app", None) == "https://example.com:8443/app?embed" assert _app_src("https://web.rustgis.app/?foo=1", "fr") == "https://web.rustgis.app/?foo=1&embed&lang=fr" assert _app_src("https://web.rustgis.app/#map", None) == "https://web.rustgis.app/?embed#map" assert _app_src("https://web.rustgis.app/?foo=1#map", "de") == "https://web.rustgis.app/?foo=1&embed&lang=de#map" @@ -27,6 +27,7 @@ def test_app_src_preserves_query_and_fragment(monkeypatch): "file:///etc/passwd", "https://", "http://", + "https://:443", "/relative/path", "ftp://example.org/app", ], @@ -36,12 +37,14 @@ def test_app_src_rejects_non_http_or_hostless_urls(bad_url): _app_src(bad_url, None) -def test_widget_js_rejects_non_http_protocol(): +def test_widget_js_rejects_non_http_protocol(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 {WIDGET_JS.as_uri()!r}; +import widget from {mjs.as_uri()!r}; globalThis.window = {{ location: {{ href: "https://notebook.example/" }}, addEventListener() {{}}, removeEventListener() {{}} }}; globalThis.document = {{ createElement() {{ return {{ style: {{}} }}; }} }}; const badModel = {{ get: (k) => (k === "_src" ? "javascript:alert(1)" : ""), on() {{}}, off() {{}} }}; diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 934d7c62ba..ced23d8d16 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -3863,7 +3863,7 @@ fn split_page(bytes: &[u8]) -> Result Date: Sat, 28 Nov 2026 20:26:00 -0500 Subject: [PATCH 3/8] fix(analysis): say cells past the range of 32-bit floats Band math, remap, IDW and Kriging now count the cells whose finite value is past f32's range and say how many, through the raster function notices, the STAC index notices and the tool's losses. Percent slope keeps main's infinite cells (the block-at-a-time path counts them), and the weighted overlay, a convex combination of f32 values, keeps main's plain cast. The merge also keeps main's lang handling in _app_src next to the scheme check, drops the duplicate query and fragment test that test_widget.py already has, and gives Skip::Cancelled a reason in the row reader. --- apps/rustgis-python/tests/test_embed.py | 12 +-- crates/analysis/src/kriging.rs | 14 ++-- crates/analysis/src/rasterops.rs | 98 +++++++++++++++++++------ crates/analysis/src/tools.rs | 9 ++- crates/data/src/raster/grib/rows.rs | 1 + crates/engine/src/cmd/stac_bands.rs | 5 +- crates/engine/src/cmd/workflows.rs | 29 +++++++- 7 files changed, 121 insertions(+), 47 deletions(-) diff --git a/apps/rustgis-python/tests/test_embed.py b/apps/rustgis-python/tests/test_embed.py index 90df97f562..c3a5c711f4 100644 --- a/apps/rustgis-python/tests/test_embed.py +++ b/apps/rustgis-python/tests/test_embed.py @@ -5,17 +5,7 @@ import pytest -from rustgis._embed import DEFAULT_URL, WIDGET_JS, _app_src - - -def test_app_src_preserves_query_and_fragment(monkeypatch): - monkeypatch.delenv("RUSTGIS_WEB_URL", raising=False) - assert _app_src(None, None) == f"{DEFAULT_URL}?embed" - assert _app_src("http://127.0.0.1:8772/", "de") == "http://127.0.0.1:8772/?embed&lang=de" - assert _app_src("https://example.com:8443/app", None) == "https://example.com:8443/app?embed" - assert _app_src("https://web.rustgis.app/?foo=1", "fr") == "https://web.rustgis.app/?foo=1&embed&lang=fr" - assert _app_src("https://web.rustgis.app/#map", None) == "https://web.rustgis.app/?embed#map" - assert _app_src("https://web.rustgis.app/?foo=1#map", "de") == "https://web.rustgis.app/?foo=1&embed&lang=de#map" +from rustgis._embed import WIDGET_JS, _app_src @pytest.mark.parametrize( diff --git a/crates/analysis/src/kriging.rs b/crates/analysis/src/kriging.rs index 93b7b83e07..0e3a76ad7e 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 = 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. @@ -392,15 +393,18 @@ fn kriging_on( } let (val, var_est) = ordinary_kriging_point(c, near, params, kx, buffers); - let (p, v) = (val as f32, var_est as f32); - *pred = if p.is_finite() { p } else { NODATA }; - *var = if v.is_finite() { v } else { NODATA }; + *pred = crate::rasterops::stored_counting(val, &past); + *var = crate::rasterops::stored_counting(var_est, &past); } })?; 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())?; + 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, note)); + } + Ok(r) } #[cfg(test)] diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 41d738d30b..c6679c9e7e 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -151,7 +151,7 @@ fn per_cell_on(threads: Option, r: &Raster, cost: usize, f: impl Fn(i64, || (), |_, row, line: &mut [f32]| { for (col, slot) in line.iter_mut().enumerate() { - *slot = f(col as i64, row as i64).map(|v| v as f32).filter(|v| v.is_finite()).unwrap_or(NODATA); + *slot = f(col as i64, row as i64).filter(|v| v.is_finite()).map(|v| v as f32).unwrap_or(NODATA); } }, )?; @@ -263,7 +263,7 @@ fn terrain_counted_on( if w < 3 || h < 3 || data.len() != len { return per_cell(r, 1, scalar).map(|pixels| (pixels, counts.finish())); } - let value = |v: Option| v.map(|v| v as f32).filter(|v| v.is_finite()).unwrap_or(NODATA); + let value = |v: Option| v.filter(|v| v.is_finite()).map(|v| v as f32).unwrap_or(NODATA); let mut out = new_band(w, h, NODATA)?; // A cell's gradient and its function cost about one unit of the threshold's (some 30 ns). let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_rows(h, len, 0)); @@ -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)); @@ -464,18 +496,20 @@ 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`. @@ -484,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, @@ -494,17 +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)) => { - let out = *new as f32; - if out.is_finite() { out } else { NODATA } - } + 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, @@ -595,8 +627,7 @@ pub fn weighted_overlay(criteria: &[(Vec, f64)]) -> Result, String } s += v as f64 * w.max(0.0) / total; } - let out = s as f32; - if out.is_finite() { out } else { NODATA } + s as f32 }, ) } @@ -1214,7 +1245,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| Some(v as f32).filter(|v| v.is_finite()).unwrap_or(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, @@ -1275,7 +1307,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. @@ -2984,9 +3021,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(); @@ -4030,20 +4067,33 @@ mod tests { "Float32", ) .unwrap(); - let prod = band_math(&r, "b1 * b2").unwrap(); - assert_eq!(prod, vec![NODATA, 6.0]); + // 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], NODATA); + 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); + assert_eq!(past(&krig_r).len(), 1, "{:?}", krig_r.lost); + + 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] diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 2d6879a08a..488667048c 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5233,12 +5233,17 @@ 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: Vec::new(), + losses: raster_losses(&r), 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 { @@ -5356,7 +5361,7 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result String { match s { Skip::Other(w) | Skip::Damaged(w) => format!("{w} can't be read row by row"), Skip::TooLarge | Skip::OtherGrid => "this record can't be read row by row".to_string(), + Skip::Cancelled => "a cancelled read".to_string(), } } diff --git a/crates/engine/src/cmd/stac_bands.rs b/crates/engine/src/cmd/stac_bands.rs index 97bce98d47..4cfc958915 100644 --- a/crates/engine/src/cmd/stac_bands.rs +++ b/crates/engine/src/cmd/stac_bands.rs @@ -209,8 +209,9 @@ mod desktop { let id = ix.id; Ok(Box::new(move || { rustgis_data::progress::check().map_err(|e| e.to_string())?; - let (stacked, notes) = read_and_stack(&name, &wanted, &picked, &hrefs, bbox, cell)?; - let band = rustgis_analysis::rasterops::band_math(&stacked, &expr)?; + let (stacked, mut notes) = read_and_stack(&name, &wanted, &picked, &hrefs, bbox, cell)?; + let (band, past) = rustgis_analysis::rasterops::band_math_reported(&stacked, &expr)?; + notes.extend(rustgis_analysis::rasterops::past_f32_note(past).map(|note| Note::loss(LossCode::DroppedValue, note))); // An index with no value anywhere (every cell 0 / 0, say) is no result: an error, not an empty layer. if !rustgis_analysis::rasterops::has_values(&band, stacked.width as usize)? { return Err(format!( diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 95a62b5a95..6d09545f7b 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -476,6 +476,8 @@ struct Remaps { terrain: Vec<(String, rasterops::TerrainEdges)>, empty: Vec<(String, f64, f64)>, emptied: Option, + /// Each raster whose cells came out past the range of 32-bit floats, with how many. + past_f32: Vec<(String, usize)>, } impl Remaps { @@ -484,6 +486,7 @@ impl Remaps { fn then(self) -> Then { let mut notes: Vec = rasterops::empty_ranges_note(&self.empty).into_iter().collect(); notes.extend(self.emptied.map(|name| format!("{name}: the remap left no cells with values"))); + notes.extend(self.past_f32.into_iter().filter_map(|(name, n)| rasterops::past_f32_note(n).map(|note| format!("{name}: {note}")))); for (stage, (name, edges)) in self.terrain.into_iter().enumerate() { if edges.clamped > 0 || edges.filled > 0 { let limit = if edges.at_most { "at most " } else { "" }; @@ -1657,9 +1660,16 @@ fn apply_function( match function { "ndvi" => { let (nir, red) = (p.get("nir").and_then(Value::as_u64).unwrap_or(4), p.get("red").and_then(Value::as_u64).unwrap_or(3)); - rasterops::band_math(r, &format!("(b{nir} - b{red}) / (b{nir} + b{red})")) + let (cells, past) = rasterops::band_math_reported(r, &format!("(b{nir} - b{red}) / (b{nir} + b{red})"))?; + remaps.past_f32.push((r.name.clone(), past)); + Ok(cells) + } + "bandMath" => { + let (cells, past) = + rasterops::band_math_reported(r, ps(p, "expression").ok_or("expression is required (b1, b2… with + - * /)")?)?; + remaps.past_f32.push((r.name.clone(), past)); + Ok(cells) } - "bandMath" => rasterops::band_math(r, ps(p, "expression").ok_or("expression is required (b1, b2… with + - * /)")?), "remap" | "threshold" => { let ranges: Vec<(f64, f64, f64)> = if ps(p, "function") == Some("threshold") { let v = f(p, "value").ok_or("value is required")?; @@ -1681,6 +1691,7 @@ fn apply_function( }; let remap = rasterops::remap(r, band, &ranges, b(p, "keep").unwrap_or(false))?; remaps.empty.extend(remap.empty.into_iter().map(|(lo, hi)| (r.name.clone(), lo, hi))); + remaps.past_f32.push((r.name.clone(), remap.past_f32)); if !rasterops::has_values(&remap.cells, r.width as usize)? { remaps.emptied.get_or_insert_with(|| r.name.clone()); } @@ -1843,6 +1854,8 @@ struct BlockRemaps { empty: Option>, /// Whether every block so far was left with no value, and the raster it was said of. emptied: Option>, + /// Cells past the range of 32-bit floats, by step, added up over the blocks. + past_f32: Vec<(String, usize)>, } #[cfg(not(target_arch = "wasm32"))] @@ -1858,6 +1871,13 @@ impl BlockRemaps { self.terrain.push((name, edges)); } } + for (i, (name, n)) in r.past_f32.into_iter().enumerate() { + if let Some((_, total)) = self.past_f32.get_mut(i) { + *total = total.saturating_add(n); + } else { + self.past_f32.push((name, n)); + } + } self.empty = Some(match self.empty.take() { None => r.empty, Some(mut e) => { @@ -1876,7 +1896,7 @@ impl BlockRemaps { /// What every block's remaps met together. fn met(self) -> Remaps { - Remaps { terrain: self.terrain, empty: self.empty.unwrap_or_default(), emptied: self.emptied.flatten() } + Remaps { terrain: self.terrain, empty: self.empty.unwrap_or_default(), emptied: self.emptied.flatten(), past_f32: self.past_f32 } } } @@ -2017,17 +2037,20 @@ fn suitability_work(s: &Session, p: &Value) -> Result { let first = first.read()?; let mut scored = Vec::new(); let mut empty = Vec::new(); + let mut past_f32 = Vec::new(); for (r, band, ranges, weight) in &criteria { let r = r.read()?; let on_grid = rasterops::resample_to(&r, *band, &first)?; let remap = rasterops::remap(&rasterops::derive(&first, &r.name, vec![on_grid])?, 0, ranges, false)?; empty.extend(remap.empty.into_iter().map(|(lo, hi)| (r.name.clone(), lo, hi))); + past_f32.extend(rasterops::past_f32_note(remap.past_f32).map(|note| format!("{}: {note}", r.name))); scored.push((remap.cells, *weight)); } let out = rasterops::weighted_overlay(&scored)?; // A cell is scored only where every criterion scores it. let none = !rasterops::has_values(&out, first.width as usize)?; let mut notes: Vec = rasterops::empty_ranges_note(&empty).into_iter().collect(); + notes.extend(past_f32); if none { notes.push(format!("{name}: no cell is scored by every criterion, so the result has no cells with values")); } From 97bddd02cd4500ef17c745783626ec9d4972a448 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 21:00:31 -0500 Subject: [PATCH 4/8] fix(data, engine): check each SQLite cell's place; say a spectral index's cells past f32 The b-tree reader now checks every cell of a page before reading any: each lies between the pointer array and the end of the usable page, and no two overlap, so two pointers to one small cell are refused even when the total fits. raster.index counts the cells past the range of 32-bit floats, added up over the blocks when it works a block at a time, and says them. --- crates/data/src/sqlite.rs | 146 ++++++++++++++++++----------- crates/engine/src/cmd/imagery.rs | 19 +++- crates/engine/src/cmd/workflows.rs | 2 +- 3 files changed, 108 insertions(+), 59 deletions(-) diff --git a/crates/data/src/sqlite.rs b/crates/data/src/sqlite.rs index 92dce52cc2..9f33ee2df1 100644 --- a/crates/data/src/sqlite.rs +++ b/crates/data/src/sqlite.rs @@ -126,38 +126,24 @@ impl> Db { match kind { // An interior table page: child pointers, then the right-most child. 0x05 => { - let mut used = hdr.saturating_add(12).saturating_add(2usize.saturating_mul(cells)); - if used > self.usable { - return Err(bad("overlapping cells")); - } + let offsets = self.cell_offsets(page, hdr + 12, cells, interior_table_span)?; let mut children = Vec::with_capacity(cells + 1); - for i in 0..cells { - let at = be16(page, hdr + 12 + 2 * i).ok_or_else(|| bad("cell pointer"))?; - let child = be32(page, at).ok_or_else(|| bad("interior cell"))?; - let (_, a) = varint(page, at + 4).ok_or_else(|| bad("interior cell"))?; - used = used.saturating_add(a - at); - if used > self.usable { - return Err(bad("overlapping cells")); - } - children.push(child); + for at in offsets { + children.push(be32(page, at).ok_or_else(|| bad("interior cell"))?); } children.push(be32(page, hdr + 8).ok_or_else(|| bad("page header"))?); stack.extend(children.into_iter().rev()); } // A leaf table page: (payload size, rowid, payload) cells. 0x0d => { - let mut used = hdr.saturating_add(8).saturating_add(2usize.saturating_mul(cells)); - if used > self.usable { - return Err(bad("overlapping cells")); - } - for i in 0..cells { - let at = be16(page, hdr + 8 + 2 * i).ok_or_else(|| bad("cell pointer"))?; + let offsets = self.cell_offsets(page, hdr + 8, cells, |page, at| { + let (size, a) = varint(page, at).ok_or_else(|| bad("leaf cell"))?; + let (_, a) = varint(page, a).ok_or_else(|| bad("leaf cell"))?; + self.cell_local_span(a - at, size, self.usable - 35) + })?; + for at in offsets { let (size, a) = varint(page, at).ok_or_else(|| bad("leaf cell"))?; let (rowid, a) = varint(page, a).ok_or_else(|| bad("leaf cell"))?; - used = used.saturating_add(self.cell_local_span(a - at, size, self.usable - 35)?); - if used > self.usable { - return Err(bad("overlapping cells")); - } let payload = self.payload_seen(page, a, size, &mut seen)?; if f(rowid as i64, record(&payload)?).is_break() { return Ok(()); @@ -203,19 +189,15 @@ impl> Db { // An interior index page: (left child, payload size, payload) cells, then the // right-most child. Each cell's entry comes after its left child's. 0x02 => { - let mut used = hdr.saturating_add(12).saturating_add(2usize.saturating_mul(cells)); - if used > self.usable { - return Err(bad("overlapping cells")); - } + let offsets = self.cell_offsets(page, hdr + 12, cells, |page, at| { + be32(page, at).ok_or_else(|| bad("interior cell"))?; + let (size, a) = varint(page, at + 4).ok_or_else(|| bad("interior cell"))?; + self.cell_local_span(a - at, size, max_local) + })?; let mut steps = Vec::with_capacity(2 * cells + 1); - for i in 0..cells { - let at = be16(page, hdr + 12 + 2 * i).ok_or_else(|| bad("cell pointer"))?; + for at in offsets { let child = be32(page, at).ok_or_else(|| bad("interior cell"))?; let (size, a) = varint(page, at + 4).ok_or_else(|| bad("interior cell"))?; - used = used.saturating_add(self.cell_local_span(a - at, size, max_local)?); - if used > self.usable { - return Err(bad("overlapping cells")); - } steps.push(Step::Page(child)); steps.push(Step::Entry(self.payload_with(page, a, size, max_local, Some(&mut seen))?)); } @@ -224,17 +206,12 @@ impl> Db { } // A leaf index page: (payload size, payload) cells. 0x0a => { - let mut used = hdr.saturating_add(8).saturating_add(2usize.saturating_mul(cells)); - if used > self.usable { - return Err(bad("overlapping cells")); - } - for i in 0..cells { - let at = be16(page, hdr + 8 + 2 * i).ok_or_else(|| bad("cell pointer"))?; + let offsets = self.cell_offsets(page, hdr + 8, cells, |page, at| { + let (size, a) = varint(page, at).ok_or_else(|| bad("leaf cell"))?; + self.cell_local_span(a - at, size, max_local) + })?; + for at in offsets { let (size, a) = varint(page, at).ok_or_else(|| bad("leaf cell"))?; - used = used.saturating_add(self.cell_local_span(a - at, size, max_local)?); - if used > self.usable { - return Err(bad("overlapping cells")); - } let payload = self.payload_with(page, a, size, max_local, Some(&mut seen))?; if f(record(&payload)?).is_break() { return Ok(()); @@ -263,19 +240,8 @@ impl> Db { let cells = be16(page, hdr + 3).ok_or_else(|| bad("page header"))?; match page.get(hdr) { Some(0x05) => { - let mut used = hdr.saturating_add(12).saturating_add(2usize.saturating_mul(cells)); - if used > self.usable { - return Err(bad("overlapping cells")); - } - for i in 0..cells { - let at = be16(page, hdr + 12 + 2 * i).ok_or_else(|| bad("cell pointer"))?; - let child = be32(page, at).ok_or_else(|| bad("interior cell"))?; - let (_, a) = varint(page, at + 4).ok_or_else(|| bad("interior cell"))?; - used = used.saturating_add(a - at); - if used > self.usable { - return Err(bad("overlapping cells")); - } - stack.push(child); + for at in self.cell_offsets(page, hdr + 12, cells, interior_table_span)? { + stack.push(be32(page, at).ok_or_else(|| bad("interior cell"))?); } stack.push(be32(page, hdr + 8).ok_or_else(|| bad("page header"))?); } @@ -286,6 +252,39 @@ impl> Db { Ok(n_rows) } + /// The offsets of a b-tree page's `cells`, whose 2-byte pointers start at `ptrs`, in pointer + /// order. Each cell, `span(page, at)` bytes long, must lie between the end of the pointer array + /// and the end of the usable page, and no two may overlap: an aliased cell would otherwise be + /// read, or its child followed, more than once. Checked for the whole page before any cell is + /// read. + fn cell_offsets( + &self, + page: &[u8], + ptrs: usize, + cells: usize, + span: impl Fn(&[u8], usize) -> Result, + ) -> Result, String> { + let floor = ptrs.saturating_add(2usize.saturating_mul(cells)); + if floor > self.usable { + return Err(bad("overlapping cells")); + } + let mut spans = Vec::with_capacity(cells); + for i in 0..cells { + let at = be16(page, ptrs + 2 * i).ok_or_else(|| bad("cell pointer"))?; + let end = at.saturating_add(span(page, at)?); + if at < floor || end > self.usable { + return Err(bad("a cell outside its page's cell area")); + } + spans.push((at, end)); + } + let mut sorted = spans.clone(); + sorted.sort_unstable(); + if sorted.windows(2).any(|w| matches!(w, [a, b] if a.1 > b.0)) { + return Err(bad("overlapping cells")); + } + Ok(spans.into_iter().map(|(at, _)| at).collect()) + } + /// How many bytes of a `size`-byte payload sit on the b-tree page itself (SQLite's rule). fn local_len(&self, size: usize, max_local: usize) -> usize { if size <= max_local { @@ -423,6 +422,13 @@ impl> Db { } } +/// The bytes an interior table cell takes: its 4-byte left child and its rowid varint. +fn interior_table_span(page: &[u8], at: usize) -> Result { + be32(page, at).ok_or_else(|| bad("interior cell"))?; + let (_, a) = varint(page, at + 4).ok_or_else(|| bad("interior cell"))?; + Ok(a - at) +} + fn be16(b: &[u8], at: usize) -> Option { let s = b.get(at..at.checked_add(2)?)?; Some(usize::from(u16::from_be_bytes([*s.first()?, *s.get(1)?]))) @@ -845,6 +851,34 @@ mod tests { interior_table[484] = 1; let db = make_db(interior_table); assert_eq!(db.scan(2, |_, _| ControlFlow::Continue(())).unwrap_err(), bad("overlapping cells")); + + // Two pointers to one small cell: the total fits on the page, but the row would be read twice. + let leaf = |pointers: &[u16], cells: &[(usize, [u8; 4])]| { + let mut page = [0u8; 512]; + page[0] = 0x0d; + page[3..5].copy_from_slice(&(pointers.len() as u16).to_be_bytes()); + for (i, p) in pointers.iter().enumerate() { + page[8 + 2 * i..10 + 2 * i].copy_from_slice(&p.to_be_bytes()); + } + for (at, cell) in cells { + page[*at..*at + 4].copy_from_slice(cell); + } + make_db(page) + }; + let rows = |db: &Db>| { + let mut n = 0; + db.scan(2, |_, _| { + n += 1; + ControlFlow::Continue(()) + }) + .map(|()| n) + }; + assert_eq!(rows(&leaf(&[450, 450], &[(450, [2, 1, 2, 0])])), Err(bad("overlapping cells"))); + // A cell inside the pointer array, and one past the usable page. + assert_eq!(rows(&leaf(&[450, 10], &[(450, [2, 1, 2, 0])])), Err(bad("a cell outside its page's cell area"))); + assert_eq!(rows(&leaf(&[508], &[(508, [5, 1, 2, 0])])), Err(bad("a cell outside its page's cell area"))); + // Distinct cells side by side are read, each once. + assert_eq!(rows(&leaf(&[450, 454], &[(450, [2, 1, 2, 0]), (454, [2, 2, 2, 0])])), Ok(2)); } #[test] diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 31127f4f70..157b8fc8aa 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1668,11 +1668,26 @@ pub(crate) fn index_work(s: &Session, p: &Value) -> Result = rasterops::past_f32_note(past.get()).map(|n| format!("{out}: {n}")).into_iter().collect(); + Ok(super::workflows::also(made, super::workflows::notices(notes))) + })); } Ok(Box::new(move || { let r = r.read()?; - super::workflows::made(rasterops::derive(&r, &out, vec![rasterops::band_math(&r, &expr)?])?, None) + let (cells, past) = rasterops::band_math_reported(&r, &expr)?; + let notes: Vec = rasterops::past_f32_note(past).map(|n| format!("{out}: {n}")).into_iter().collect(); + super::workflows::made_then(rasterops::derive(&r, &out, vec![cells])?, None, Some(super::workflows::notices(notes))) })) } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 6d09545f7b..dbee0e2d30 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -499,7 +499,7 @@ impl Remaps { } /// Says `notes` when the result is added. -fn notices(notes: Vec) -> Then { +pub(crate) fn notices(notes: Vec) -> Then { Box::new(move |s, _| { for note in notes { s.notify(note, false); From 69930dcd7e6af10e52866cae5b7a6e61ee298e6e Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 21:31:42 -0500 Subject: [PATCH 5/8] fix: count Kriging cells once, give SQLite cells four bytes, qualify block-margin counts A Kriging cell whose prediction and variance are both past f32's range is counted once. A SQLite cell takes at least four bytes on its page, as SQLite gives it, so two 3-byte cells one byte apart overlap. A chain that works in blocks with margins says its count of cells past f32 as at most so many. The widget test checks the guard's own message and frames an https: address as a positive control. --- apps/rustgis-python/tests/test_embed.py | 22 +++++++++++------ crates/analysis/src/kriging.rs | 9 +++++-- crates/analysis/src/rasterops.rs | 3 ++- crates/data/src/sqlite.rs | 5 +++- crates/engine/src/cmd/workflows.rs | 33 +++++++++++++++++-------- 5 files changed, 51 insertions(+), 21 deletions(-) diff --git a/apps/rustgis-python/tests/test_embed.py b/apps/rustgis-python/tests/test_embed.py index c3a5c711f4..43a63b476f 100644 --- a/apps/rustgis-python/tests/test_embed.py +++ b/apps/rustgis-python/tests/test_embed.py @@ -27,7 +27,7 @@ def test_app_src_rejects_non_http_or_hostless_urls(bad_url): _app_src(bad_url, None) -def test_widget_js_rejects_non_http_protocol(tmp_path): +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") @@ -37,15 +37,23 @@ def test_widget_js_rejects_non_http_protocol(tmp_path): import widget from {mjs.as_uri()!r}; globalThis.window = {{ location: {{ href: "https://notebook.example/" }}, addEventListener() {{}}, removeEventListener() {{}} }}; globalThis.document = {{ createElement() {{ return {{ style: {{}} }}; }} }}; -const badModel = {{ get: (k) => (k === "_src" ? "javascript:alert(1)" : ""), on() {{}}, off() {{}} }}; -let threw = false; +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: badModel, el: {{ appendChild() {{}} }} }}); + widget.render({{ model: model("javascript:alert(1)"), el }}); }} catch (e) {{ - threw = true; + message = String(e && e.message); }} -if (!threw) {{ - console.error("expected _widget.js to reject javascript: URL"); +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); }} """ diff --git a/crates/analysis/src/kriging.rs b/crates/analysis/src/kriging.rs index 0e3a76ad7e..7b53355bea 100644 --- a/crates/analysis/src/kriging.rs +++ b/crates/analysis/src/kriging.rs @@ -393,8 +393,13 @@ fn kriging_on( } let (val, var_est) = ordinary_kriging_point(c, near, params, kx, buffers); - *pred = crate::rasterops::stored_counting(val, &past); - *var = crate::rasterops::stored_counting(var_est, &past); + // A cell is counted once, whichever of its two values is past the range. + let lost = std::sync::atomic::AtomicUsize::new(0); + *pred = crate::rasterops::stored_counting(val, &lost); + *var = crate::rasterops::stored_counting(var_est, &lost); + if lost.into_inner() > 0 { + past.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } } })?; diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index c6679c9e7e..6eee5e1101 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -4088,7 +4088,8 @@ mod tests { 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); - assert_eq!(past(&krig_r).len(), 1, "{:?}", krig_r.lost); + // Each of the 4 cells once, though its variance may be past the range too. + assert_eq!(past(&krig_r), vec!["4 cells past the range of 32-bit floats (±3.4 × 10^38) have no value".to_string()]); 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()); diff --git a/crates/data/src/sqlite.rs b/crates/data/src/sqlite.rs index 9f33ee2df1..ba8ca6324d 100644 --- a/crates/data/src/sqlite.rs +++ b/crates/data/src/sqlite.rs @@ -271,7 +271,8 @@ impl> Db { let mut spans = Vec::with_capacity(cells); for i in 0..cells { let at = be16(page, ptrs + 2 * i).ok_or_else(|| bad("cell pointer"))?; - let end = at.saturating_add(span(page, at)?); + // SQLite gives every cell at least four bytes on its page. + let end = at.saturating_add(span(page, at)?.max(4)); if at < floor || end > self.usable { return Err(bad("a cell outside its page's cell area")); } @@ -877,6 +878,8 @@ mod tests { // A cell inside the pointer array, and one past the usable page. assert_eq!(rows(&leaf(&[450, 10], &[(450, [2, 1, 2, 0])])), Err(bad("a cell outside its page's cell area"))); assert_eq!(rows(&leaf(&[508], &[(508, [5, 1, 2, 0])])), Err(bad("a cell outside its page's cell area"))); + // A 3-byte cell still takes four bytes, so one starting in its fourth overlaps it. + assert_eq!(rows(&leaf(&[450, 453], &[(450, [1, 1, 8, 0]), (453, [1, 2, 9, 0])])), Err(bad("overlapping cells"))); // Distinct cells side by side are read, each once. assert_eq!(rows(&leaf(&[450, 454], &[(450, [2, 1, 2, 0]), (454, [2, 2, 2, 0])])), Ok(2)); } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index dbee0e2d30..752657bae9 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -476,8 +476,9 @@ struct Remaps { terrain: Vec<(String, rasterops::TerrainEdges)>, empty: Vec<(String, f64, f64)>, emptied: Option, - /// Each raster whose cells came out past the range of 32-bit floats, with how many. - past_f32: Vec<(String, usize)>, + /// Each raster whose cells came out past the range of 32-bit floats, with how many, and + /// whether that count may include a block's margin cells counted again in the next block. + past_f32: Vec<(String, usize, bool)>, } impl Remaps { @@ -486,7 +487,15 @@ impl Remaps { fn then(self) -> Then { let mut notes: Vec = rasterops::empty_ranges_note(&self.empty).into_iter().collect(); notes.extend(self.emptied.map(|name| format!("{name}: the remap left no cells with values"))); - notes.extend(self.past_f32.into_iter().filter_map(|(name, n)| rasterops::past_f32_note(n).map(|note| format!("{name}: {note}")))); + notes.extend(self.past_f32.into_iter().filter_map(|(name, n, at_most)| { + rasterops::past_f32_note(n).map(|note| { + if at_most { + format!("{name}: at most {note}; counts include repeated intermediate tile margins") + } else { + format!("{name}: {note}") + } + }) + })); for (stage, (name, edges)) in self.terrain.into_iter().enumerate() { if edges.clamped > 0 || edges.filled > 0 { let limit = if edges.at_most { "at most " } else { "" }; @@ -1632,6 +1641,9 @@ fn apply_function( let band = band_of(p, r)?; let zf = f(p, "zFactor").unwrap_or(1.0).clamp(0.0001, 100_000.0); let function = ps(p, "function").ok_or("function is required")?; + // Whether this block's cells include margins the next block makes again: counts are then + // at most so many. + let at_most = core.is_some_and(|(_, at_most)| at_most); let terrain = match function { "slope" => Some(match p.get("units") { None => rasterops::TerrainFunction::Slope, @@ -1661,13 +1673,13 @@ fn apply_function( "ndvi" => { let (nir, red) = (p.get("nir").and_then(Value::as_u64).unwrap_or(4), p.get("red").and_then(Value::as_u64).unwrap_or(3)); let (cells, past) = rasterops::band_math_reported(r, &format!("(b{nir} - b{red}) / (b{nir} + b{red})"))?; - remaps.past_f32.push((r.name.clone(), past)); + remaps.past_f32.push((r.name.clone(), past, at_most)); Ok(cells) } "bandMath" => { let (cells, past) = rasterops::band_math_reported(r, ps(p, "expression").ok_or("expression is required (b1, b2… with + - * /)")?)?; - remaps.past_f32.push((r.name.clone(), past)); + remaps.past_f32.push((r.name.clone(), past, at_most)); Ok(cells) } "remap" | "threshold" => { @@ -1691,7 +1703,7 @@ fn apply_function( }; let remap = rasterops::remap(r, band, &ranges, b(p, "keep").unwrap_or(false))?; remaps.empty.extend(remap.empty.into_iter().map(|(lo, hi)| (r.name.clone(), lo, hi))); - remaps.past_f32.push((r.name.clone(), remap.past_f32)); + remaps.past_f32.push((r.name.clone(), remap.past_f32, at_most)); if !rasterops::has_values(&remap.cells, r.width as usize)? { remaps.emptied.get_or_insert_with(|| r.name.clone()); } @@ -1855,7 +1867,7 @@ struct BlockRemaps { /// Whether every block so far was left with no value, and the raster it was said of. emptied: Option>, /// Cells past the range of 32-bit floats, by step, added up over the blocks. - past_f32: Vec<(String, usize)>, + past_f32: Vec<(String, usize, bool)>, } #[cfg(not(target_arch = "wasm32"))] @@ -1871,11 +1883,12 @@ impl BlockRemaps { self.terrain.push((name, edges)); } } - for (i, (name, n)) in r.past_f32.into_iter().enumerate() { - if let Some((_, total)) = self.past_f32.get_mut(i) { + for (i, (name, n, at_most)) in r.past_f32.into_iter().enumerate() { + if let Some((_, total, any_at_most)) = self.past_f32.get_mut(i) { *total = total.saturating_add(n); + *any_at_most |= at_most; } else { - self.past_f32.push((name, n)); + self.past_f32.push((name, n, at_most)); } } self.empty = Some(match self.empty.take() { From 50a57c8674df53bfb71a3679abd32aa5c7daf10f Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 16:51:58 -0500 Subject: [PATCH 6/8] fix(kriging): say which output lost cells past the f32 range The prediction and the variance are counted apart, and each note names its output layer (the prediction, or _variance), so a user can tell which file lost the values. --- crates/analysis/src/kriging.rs | 19 +++++++++---------- crates/analysis/src/rasterops.rs | 10 ++++++++-- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/crates/analysis/src/kriging.rs b/crates/analysis/src/kriging.rs index 7b53355bea..62a67e7b04 100644 --- a/crates/analysis/src/kriging.rs +++ b/crates/analysis/src/kriging.rs @@ -368,7 +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 = std::sync::atomic::AtomicUsize::new(0); + 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. @@ -393,21 +393,20 @@ fn kriging_on( } let (val, var_est) = ordinary_kriging_point(c, near, params, kx, buffers); - // A cell is counted once, whichever of its two values is past the range. - let lost = std::sync::atomic::AtomicUsize::new(0); - *pred = crate::rasterops::stored_counting(val, &lost); - *var = crate::rasterops::stored_counting(var_est, &lost); - if lost.into_inner() > 0 { - past.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - } + // 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 }; 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())?; - 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, note)); + // 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) } diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 8f7c2022c7..d921fa3a12 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -4077,8 +4077,14 @@ mod tests { 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 of the 4 cells once, though its variance may be past the range too. - assert_eq!(past(&krig_r), vec!["4 cells past the range of 32-bit floats (±3.4 × 10^38) have no value".to_string()]); + // 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()); From 675bc44c9332efb41ae4f5a3e72c8b617cb4bfa0 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 17:21:04 -0500 Subject: [PATCH 7/8] fix(raster): one f32-range notice per chain, bounded after any halo A function chain said the cells past the range of 32-bit floats once per step; it now says the kind once, summed over the steps that lost cells. A step's count is qualified "at most" whenever its input holds cells outside its block's own, which every step does once the chain reads a halo, not only when a later step needs one: slope then band math counted the margins of each block twice and called the sum exact. Tests cover a two-step chain read whole (one exact notice), a slope then band math chain read a block at a time (one bounded notice), and an IDW surface past the range (one notice, from the layer's notes). --- crates/engine/src/cmd/workflows.rs | 33 ++++++++----- crates/engine/src/tests.rs | 26 ++++++++++ crates/engine/src/tests/tiled_files.rs | 67 ++++++++++++++++++++++++++ 3 files changed, 114 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index c2054c3284..2105ce8357 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -487,15 +487,23 @@ impl Remaps { fn then(self) -> Then { let mut notes: Vec = rasterops::empty_ranges_note(&self.empty).into_iter().collect(); notes.extend(self.emptied.map(|name| format!("{name}: the remap left no cells with values"))); - notes.extend(self.past_f32.into_iter().filter_map(|(name, n, at_most)| { - rasterops::past_f32_note(n).map(|note| { - if at_most { - format!("{name}: at most {note}; counts include repeated intermediate tile margins") - } else { - format!("{name}: {note}") - } - }) - })); + // One notice for the kind, over every step that lost cells. + let mut past = (Vec::::new(), 0usize, false); + for (name, n, at_most) in self.past_f32.into_iter().filter(|(_, n, _)| *n > 0) { + if !past.0.contains(&name) { + past.0.push(name); + } + past.1 = past.1.saturating_add(n); + past.2 |= at_most; + } + if let Some(note) = rasterops::past_f32_note(past.1) { + let names = past.0.join(", "); + notes.push(if past.2 { + format!("{names}: at most {note}; counts include repeated intermediate tile margins") + } else { + format!("{names}: {note}") + }); + } for (stage, (name, edges)) in self.terrain.into_iter().enumerate() { if edges.clamped > 0 || edges.filled > 0 { let limit = if edges.at_most { "at most " } else { "" }; @@ -1641,9 +1649,10 @@ fn apply_function( let band = band_of(p, r)?; let zf = f(p, "zFactor").unwrap_or(1.0).clamp(0.0001, 100_000.0); let function = ps(p, "function").ok_or("function is required")?; - // Whether this block's cells include margins the next block makes again: counts are then - // at most so many. - let at_most = core.is_some_and(|(_, at_most)| at_most); + // Whether this input holds cells outside its block's own (margins its neighbours read too, + // for this step or a later one): a count over all of it is then at most so many. + let whole = [0, 0, r.width as usize, r.height as usize]; + let at_most = core.is_some_and(|(kept, later)| later || kept != whole); let terrain = match function { "slope" => Some(match p.get("units") { None => rasterops::TerrainFunction::Slope, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f060157010..e30bd0c792 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -59644,6 +59644,32 @@ fn interpolation_says_the_features_it_leaves_out() { assert!(e.contains("(2 features with no geometry or no usable point, 1 whose value isn't a number left out)"), "{e}"); } +/// `analysis.interpolate` says the cells its surface leaves without a value because they come out +/// past the range of 32-bit floats, once, with a count (the layer's notes, said as it is added); +/// a surface that fits says nothing of it. +#[test] +fn interpolation_says_the_cells_past_the_range_of_32_bit_floats() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as V}; + use rustgis_geom::Coord; + let mut s = world(); + for (name, depth) in [("huge wells", 1e40), ("wells", 10.0)] { + let mut wells = Dataset::new(name, GeometryType::Point, vec![Field::new("depth", FieldType::Double)]); + for i in 0..3 { + wells.push(Some(Geometry::Point(Coord::new(i as f64, i as f64))), vec![V::Float(depth)]); + } + crate::cmd::layer::add_dataset(&mut s, wells); + let mark = s.notice_mark(); + s.run("analysis.interpolate", &json!({"layer": name, "field": "depth", "cellSize": 0.5, "name": "surface"})).unwrap(); + let past: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("32-bit floats")).map(|n| n.text.clone()).collect(); + if depth > 1e38 { + assert_eq!(past.len(), 1, "{past:?}"); + assert!(past[0].starts_with("surface: ") && past[0].contains("cells past the range"), "{past:?}"); + } else { + assert!(past.is_empty(), "{past:?}"); + } + } +} + /// The Geostatistical Wizard makes its surface in a projected system (#1743): the one given as /// `crs`, else the environment's (`gp.env` `crs`, with a cell size in its units), else the projected /// one the layer was read in, and says so; `EPSG:4326` asks for degrees. The environment keeps its diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index 35b357d16d..19a2cb6e80 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -692,6 +692,73 @@ fn terrain_notices_and_pixels_agree_across_block_margins() { } } +/// Cells a chain's band math leaves past the range of 32-bit floats are said in one notice for +/// the run, with a count: exact when the raster is read whole, and qualified "at most" when it is +/// read a block at a time after a step over neighbours, whose margins later steps count again. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn chained_band_math_says_cells_past_the_range_once_and_bounds_block_counts() { + // 10^37, then 10^37 · 100 = 10^39: past the range. 1 · 10^37 fits, and 10^37 · 1000 doesn't. + let big = format!("1{}", "0".repeat(37)); + let d = dir("past-f32-chain"); + let small = d.join("small.tif"); + let mut values = vec![1.0f32; 25]; + for v in values.iter_mut().step_by(2) { + *v = 100.0; + } + let gt = GeoTransform { origin_x: 0.0, origin_y: 5.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r = Raster::new("small", 5, 5, vec![values], gt, Crs::WebMercator, Some(-9999.0), ColorHint::Gray, "Float32").unwrap(); + std::fs::write(&small, rustgis_data::raster::geotiff::write(&r, 0).unwrap()).unwrap(); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": small})).unwrap(); + let steps = json!([{"function": "bandMath", "expression": format!("b1 * {big}")}, {"function": "bandMath", "expression": "b1 * 1000"}]); + let mark = s.notice_mark(); + s.run("raster.functionChain", &json!({"layer": "small", "steps": steps, "name": "out"})).unwrap(); + let past: Vec<_> = said(&s, mark).into_iter().filter(|n| n.contains("32-bit floats")).collect(); + // 13 cells in the first step, the other 12 in the second: one notice for all 25. + assert_eq!(past.len(), 1, "{past:?}"); + assert!(past[0].contains("25 cells past the range") && !past[0].contains("at most"), "{past:?}"); + // A chain that fits says nothing of it. + let mark = s.notice_mark(); + s.run("raster.functionChain", &json!({"layer": "small", "steps": [{"function": "bandMath", "expression": "b1 * 2"}], "name": "fits"})) + .unwrap(); + assert!(said(&s, mark).iter().all(|n| !n.contains("32-bit floats")), "{:?}", said(&s, mark)); + + // A slope, then band math past the range, over a file read a block at a time. + let path = d.join("height.tif"); + let (w, h) = (1025, 1025); + let dem = Raster::new( + "height", + w, + h, + vec![vec![10.0; (w * h) as usize]], + GeoTransform { origin_x: 0.0, origin_y: h as f64, pixel_width: 1.0, pixel_height: -1.0 }, + Crs::WebMercator, + Some(-9999.0), + ColorHint::Gray, + "Float32", + ) + .unwrap(); + rustgis_data::raster::cogwrite::write_file(&dem, 0, &path).unwrap(); + let p = json!({"layer": "height", "steps": [{"function": "slope"}, {"function": "bandMath", "expression": format!("(b1 + 1) * {big} * 1000")}], "name": "out"}); + let mut whole = Session::new(Project::default()); + whole.run("layer.addData", &json!({"path": path})).unwrap(); + let mark = whole.notice_mark(); + whole.run("raster.functionChain", &p).unwrap(); + let exact: Vec<_> = said(&whole, mark).into_iter().filter(|n| n.contains("32-bit floats")).collect(); + assert_eq!(exact.len(), 1, "{exact:?}"); + assert!(!exact[0].contains("at most"), "{exact:?}"); + let (_held, _blocks) = (HeldWhole::at(1000), BlocksPast::at(1_100_000)); + let mut blocked = Session::new(Project::default()); + blocked.run("layer.addData", &json!({"path": path})).unwrap(); + assert!(raster(&blocked, "height").tiled); + let mark = blocked.notice_mark(); + blocked.run("raster.functionChain", &p).unwrap(); + let bounded: Vec<_> = said(&blocked, mark).into_iter().filter(|n| n.contains("32-bit floats")).collect(); + assert_eq!(bounded.len(), 1, "{bounded:?}"); + assert!(bounded[0].contains("at most") && bounded[0].contains("repeated intermediate tile margins"), "{bounded:?}"); +} + /// The other commands that work cell by cell, or over a cell's neighbours, run a block at a time /// over a file too large to read whole too (#2865), each making the raster it makes of the file /// held whole, held or written to the results folder: Raster Functions by cell and over a cell's From 80cdeda64a932fd36555d0917068a9ebd51af03c Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 17:47:10 -0500 Subject: [PATCH 8/8] fix(suitability): one f32-range notice for all criteria A suitability said the cells past the range of 32-bit floats once per criterion; it now says the kind once, with the total and each criterion that lost cells, as a function chain does. --- crates/engine/src/cmd/workflows.rs | 12 +++++++++--- crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 2105ce8357..052846d0ae 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -2059,20 +2059,26 @@ fn suitability_work(s: &Session, p: &Value) -> Result { let first = first.read()?; let mut scored = Vec::new(); let mut empty = Vec::new(); - let mut past_f32 = Vec::new(); + // One notice for cells past the range of 32-bit floats, over every criterion that lost some. + let (mut past_names, mut past_f32) = (Vec::::new(), 0usize); for (r, band, ranges, weight) in &criteria { let r = r.read()?; let on_grid = rasterops::resample_to(&r, *band, &first)?; let remap = rasterops::remap(&rasterops::derive(&first, &r.name, vec![on_grid])?, 0, ranges, false)?; empty.extend(remap.empty.into_iter().map(|(lo, hi)| (r.name.clone(), lo, hi))); - past_f32.extend(rasterops::past_f32_note(remap.past_f32).map(|note| format!("{}: {note}", r.name))); + if remap.past_f32 > 0 { + past_f32 = past_f32.saturating_add(remap.past_f32); + if !past_names.contains(&r.name) { + past_names.push(r.name.clone()); + } + } scored.push((remap.cells, *weight)); } let out = rasterops::weighted_overlay(&scored)?; // A cell is scored only where every criterion scores it. let none = !rasterops::has_values(&out, first.width as usize)?; let mut notes: Vec = rasterops::empty_ranges_note(&empty).into_iter().collect(); - notes.extend(past_f32); + notes.extend(rasterops::past_f32_note(past_f32).map(|note| format!("{}: {note}", past_names.join(", ")))); if none { notes.push(format!("{name}: no cell is scored by every criterion, so the result has no cells with values")); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e30bd0c792..8d91185849 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -19976,6 +19976,31 @@ fn the_graticule_takes_a_type_and_a_measured_grids_system() { assert!(!text.contains("graticule_type") && !text.contains("graticule_crs")); } +/// A suitability whose criteria score cells past the range of 32-bit floats says so once for the +/// run, with the total and each criterion that lost cells; criteria that fit say nothing of it. +#[test] +fn suitability_says_cells_past_the_range_of_32_bit_floats_once() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + let mut s = Session::new(Project::default()); + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 0.1, pixel_height: -0.1 }; + for name in ["a", "b"] { + let r = Raster::new(name, 3, 1, vec![vec![1.0, 2.0, 3.0]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let bytes = geotiff::write(&r, 0).unwrap(); + crate::cmd::raster::add_raster(&mut s, name, rustgis_map::RasterLayer::from_bytes(r, format!("{name}.tif"), bytes)).unwrap(); + } + for (score, want) in [(1e40, Some("a, b: 6 cells past the range of 32-bit floats")), (5.0, None)] { + let ranges = json!([[0, 10, score]]); + let p = json!({"criteria": [{"layer": "a", "ranges": ranges, "weight": 1}, {"layer": "b", "ranges": ranges, "weight": 1}]}); + let mark = s.notice_mark(); + s.run("analysis.suitability", &p).unwrap(); + let past: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("32-bit floats")).map(|n| n.text.clone()).collect(); + match want { + Some(start) => assert!(past.len() == 1 && past[0].starts_with(start), "{past:?}"), + None => assert!(past.is_empty(), "{past:?}"), + } + } +} + /// Ranges whose ends are equal or reversed still match nothing; Raster Functions, a chain and a /// suitability say which, and a result with no values, once per kind, also after a background run. #[test]