diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index bfbd782e85..7664ce5a5f 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -289,9 +289,14 @@ def _app_src(url: Optional[str], lang: Optional[str]) -> str: Args: url: The web app's address, or None for ``RUSTGIS_WEB_URL`` or the default. lang: The interface language code, or None. + + Raises: + ValueError: When the address is not an ``http://`` or ``https://`` URL with a host. """ base = url or os.environ.get("RUSTGIS_WEB_URL") or DEFAULT_URL parts = urlsplit(base) + if parts.scheme.lower() not in ("http", "https") or not parts.netloc or not parts.hostname: + raise ValueError(f"web app url must be an http:// or https:// address with a host, got {base!r}") kept = [q for q in parts.query.split("&") if q] if lang: # The app reads the first `lang`: an explicit one replaces any the address holds. diff --git a/apps/rustgis-python/python/rustgis/_widget.js b/apps/rustgis-python/python/rustgis/_widget.js index b41ccc713e..850e388306 100644 --- a/apps/rustgis-python/python/rustgis/_widget.js +++ b/apps/rustgis-python/python/rustgis/_widget.js @@ -5,9 +5,13 @@ function render({ model, el }) { const src = model.get("_src"); - const origin = new URL(src, window.location.href).origin; + const parsed = new URL(src, window.location.href); + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + throw new Error(`Refusing non-HTTP(S) RustGIS app URL: ${parsed.protocol}`); + } + const origin = parsed.origin; const iframe = document.createElement("iframe"); - iframe.src = src; + iframe.src = parsed.href; iframe.style.width = "100%"; iframe.style.height = model.get("height") || "800px"; iframe.style.border = "0"; diff --git a/apps/rustgis-python/tests/test_embed.py b/apps/rustgis-python/tests/test_embed.py new file mode 100644 index 0000000000..43a63b476f --- /dev/null +++ b/apps/rustgis-python/tests/test_embed.py @@ -0,0 +1,61 @@ +"""URL construction and validation for the embedded web app widgets.""" + +import shutil +import subprocess + +import pytest + +from rustgis._embed import WIDGET_JS, _app_src + + +@pytest.mark.parametrize( + "bad_url", + [ + "javascript:alert(1)", + "JAVASCRIPT:alert(1)", + "data:text/html,

x

", + "file:///etc/passwd", + "https://", + "http://", + "https://:443", + "/relative/path", + "ftp://example.org/app", + ], +) +def test_app_src_rejects_non_http_or_hostless_urls(bad_url): + with pytest.raises(ValueError): + _app_src(bad_url, None) + + +def test_widget_js_refuses_non_http_and_frames_https(tmp_path): + node = shutil.which("node") + if node is None: + pytest.skip("node not installed") + mjs = tmp_path / "_widget.mjs" + mjs.write_text(WIDGET_JS.read_text(encoding="utf-8"), encoding="utf-8") + script = f""" +import widget from {mjs.as_uri()!r}; +globalThis.window = {{ location: {{ href: "https://notebook.example/" }}, addEventListener() {{}}, removeEventListener() {{}} }}; +globalThis.document = {{ createElement() {{ return {{ style: {{}} }}; }} }}; +const model = (src) => ({{ get: (k) => (k === "_src" ? src : ""), on() {{}}, off() {{}} }}); +const el = {{ appended: 0, appendChild() {{ this.appended += 1; }} }}; +// The guard refuses a javascript: address with its own message, not some other failure. +let message = null; +try {{ + widget.render({{ model: model("javascript:alert(1)"), el }}); +}} catch (e) {{ + message = String(e && e.message); +}} +if (!message || !message.includes("Refusing non-HTTP(S) RustGIS app URL")) {{ + console.error(`expected the scheme guard to refuse javascript:, got ${{message}}`); + process.exit(1); +}} +// The same harness frames an https: address. +const cleanup = widget.render({{ model: model("https://web.rustgis.app/?embed"), el }}); +if (el.appended !== 1 || typeof cleanup !== "function") {{ + console.error("expected an https: address to be framed"); + process.exit(1); +}} +""" + proc = subprocess.run([node, "--input-type=module", "-e", script], capture_output=True, text=True) + assert proc.returncode == 0, proc.stderr diff --git a/crates/analysis/src/kriging.rs b/crates/analysis/src/kriging.rs index 9fa3276999..62a67e7b04 100644 --- a/crates/analysis/src/kriging.rs +++ b/crates/analysis/src/kriging.rs @@ -368,6 +368,7 @@ fn kriging_on( let scratch = || (Vec::<(f64, f64, Coord)>::with_capacity(points.len()), KrigingBuffers::new(), crate::control::Pace::default()); let (mut pred_data, mut var_data) = (crate::rasterops::new_band(w, h, NODATA)?, crate::rasterops::new_band(w, h, NODATA)?); let rows = pred_data.chunks_mut(w).zip(var_data.chunks_mut(w)); + let (past_pred, past_var) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0)); crate::control::begin(h); crate::parallel::for_each_row(rows, threads, scratch, |(near, buffers, pace), row, (pred, var): (&mut [f32], &mut [f32])| { // East-west degrees shrink with latitude; a projected system's units don't. @@ -387,19 +388,27 @@ fn kriging_on( })); if k < near.len() { - near.select_nth_unstable_by(k - 1, |a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); + near.select_nth_unstable_by(k - 1, |a, b| a.0.total_cmp(&b.0)); near.truncate(k); } let (val, var_est) = ordinary_kriging_point(c, near, params, kx, buffers); - *pred = if val.is_finite() { val as f32 } else { NODATA }; - *var = if var_est.is_finite() { var_est as f32 } else { NODATA }; + // Each band counted on its own, so its note says which output lost the values. + *pred = crate::rasterops::stored_counting(val, &past_pred); + *var = crate::rasterops::stored_counting(var_est, &past_var); } })?; let gt = GeoTransform { origin_x: extent.min_x, origin_y: extent.max_y, pixel_width: cell, pixel_height: -cell }; - Raster::new(name, w as u32, h as u32, vec![pred_data, var_data], gt, crs, Some(NODATA as f64), ColorHint::Gray, "Float32") - .map_err(|e| e.to_string()) + let mut r = Raster::new(name, w as u32, h as u32, vec![pred_data, var_data], gt, crs, Some(NODATA as f64), ColorHint::Gray, "Float32") + .map_err(|e| e.to_string())?; + // Named as the tool names its two outputs: the prediction, and `{name}_variance`. + for (band, past) in [(name.to_string(), past_pred), (format!("{name}_variance"), past_var)] { + if let Some(note) = crate::rasterops::past_f32_note(past.into_inner()) { + r.lost.push(rustgis_data::loss::Note::loss(rustgis_data::loss::LossCode::DroppedValue, format!("{band}: {note}"))); + } + } + Ok(r) } #[cfg(test)] diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index f63ea3671d..da83928b7b 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -30,7 +30,7 @@ impl PartialOrd for State { } impl Ord for State { fn cmp(&self, o: &Self) -> std::cmp::Ordering { - o.0.partial_cmp(&self.0).unwrap_or(std::cmp::Ordering::Equal) + o.0.total_cmp(&self.0) } } @@ -1061,7 +1061,7 @@ pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result (d.is_finite() && d <= radius_m).then_some((*r, d)) }) .collect(); - out.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)); + out.sort_by(|a, b| a.1.total_cmp(&b.1)); WithinReport { rows: out, bounded, invalid_latitudes, missing_coordinates } } diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index aa97b0b4ab..18450d6ac7 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -433,20 +433,52 @@ pub fn hillshade_on(r: &Raster, b: usize, azimuth: f64, altitude: f64, zf: f64, terrain_reported(r, b, zf, ground, None, TerrainFunction::Hillshade { azimuth, altitude }).map(|(pixels, _, _)| pixels) } +/// What a result says of its `n` cells whose value is finite but past the range of 32-bit floats, +/// which are stored as no-data: none when there are none. +pub fn past_f32_note(n: usize) -> Option { + match n { + 0 => None, + 1 => Some("1 cell past the range of 32-bit floats (±3.4 × 10^38) has no value".into()), + n => Some(format!("{n} cells past the range of 32-bit floats (±3.4 × 10^38) have no value")), + } +} + +/// `v` as a cell: no-data when it is not finite, and when it is finite but past the range of +/// 32-bit floats, which is counted in `past` for [`past_f32_note`]. +pub(crate) fn stored_counting(v: f64, past: &std::sync::atomic::AtomicUsize) -> f32 { + if !v.is_finite() { + return NODATA; + } + let out = v as f32; + if out.is_finite() { + out + } else { + past.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + NODATA + } +} + /// A band arithmetic expression over `b1`, `b2`… (+ - * / and parentheses, numbers). pub fn band_math(r: &Raster, expr: &str) -> Result, String> { + band_math_reported(r, expr).map(|(cells, _)| cells) +} + +/// [`band_math`], with how many cells came out finite but past the range of 32-bit floats and +/// were stored as no-data ([`past_f32_note`]). +pub fn band_math_reported(r: &Raster, expr: &str) -> Result<(Vec, usize), String> { band_math_on(None, r, expr) } -/// [`band_math`] on `threads` threads (none: as many as pay off): each cell on its own, so rows go -/// on several threads (#1252), each with its own band values. -fn band_math_on(threads: Option, r: &Raster, expr: &str) -> Result, String> { +/// [`band_math_reported`] on `threads` threads (none: as many as pay off): each cell on its own, +/// so rows go on several threads (#1252), each with its own band values. +fn band_math_on(threads: Option, r: &Raster, expr: &str) -> Result<(Vec, usize), String> { let e = Expr::parse(expr, r.band_count())?; let (w, h) = (r.width as usize, r.height as usize); let mut out = new_band(w, h, NODATA)?; if w == 0 { - return Ok(out); + return Ok((out, 0)); } + let past = std::sync::atomic::AtomicUsize::new(0); // A cell reads every band and evaluates the expression: about a unit a band. let work = w.saturating_mul(h).saturating_mul(r.band_count().max(1)); let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_rows(h, work, 0)); @@ -458,29 +490,26 @@ fn band_math_on(threads: Option, r: &Raster, expr: &str) -> Result, pub empty: Vec<(f64, f64)>, + pub past_f32: usize, } /// Remaps value ranges `[lo, hi)` to new values; other values become no-data unless `keep`. @@ -489,6 +518,7 @@ pub struct Remap { pub fn remap(r: &Raster, b: usize, ranges: &[(f64, f64, f64)], keep: bool) -> Result { let d = band(r, b)?; let n = r.width as usize * r.height as usize; + let past = std::sync::atomic::AtomicUsize::new(0); // A lookup in the ranges: about a unit a cell. let cells = per_index( n, @@ -499,14 +529,14 @@ pub fn remap(r: &Raster, b: usize, ranges: &[(f64, f64, f64)], keep: bool) -> Re let Some(v) = d.get(i).copied().filter(|v| r.is_valid(*v)) else { return NODATA }; let x = v as f64; match ranges.iter().find(|(lo, hi, _)| x >= *lo && x < *hi) { - Some((_, _, new)) => *new as f32, + Some((_, _, new)) => stored_counting(*new, &past), None if keep => v, None => NODATA, } }, )?; let empty = ranges.iter().filter(|(lo, hi, _)| lo >= hi).map(|(lo, hi, _)| (*lo, *hi)).collect(); - Ok(Remap { cells, empty }) + Ok(Remap { cells, empty, past_f32: past.into_inner() }) } /// The one notice for remap ranges that match nothing, each with the raster it was given for, @@ -854,6 +884,9 @@ fn viewshed_on( radius_m: f64, heights: Heights, ) -> Result { + if !height.is_finite() { + return Err("the observer height must be a finite number".into()); + } let (oc, or) = r.pixel_at(observer).ok_or("the observer is outside the raster")?; let z0 = r.value(b, oc, or).ok_or("the observer stands on no-data")? as f64 + height; // The radius and the Earth's curvature are metres: so are the cells, in a system in feet too. @@ -1217,7 +1250,8 @@ fn idw_on( let every = every_point.then(|| IdwColumns::new(points)); let mut data = new_band(w, h, NODATA)?; crate::control::begin(h); - let stored = |v: f64| if v.is_finite() { v as f32 } else { NODATA }; + let past = std::sync::atomic::AtomicUsize::new(0); + let stored = |v: f64| stored_counting(v, &past); crate::parallel::for_each_row( data.chunks_mut(w), threads, @@ -1258,7 +1292,7 @@ fn idw_on( near.extend(points.iter().map(|(p, v)| (d2(c, kx, p.x, p.y).sqrt(), *v))); } if k < near.len() { - near.select_nth_unstable_by(k - 1, |a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); + near.select_nth_unstable_by(k - 1, |a, b| a.0.total_cmp(&b.0)); near.truncate(k); } let v = if let Some(on) = near.iter().find(|(d, _)| *d < exact) { @@ -1278,7 +1312,12 @@ fn idw_on( }, )?; let gt = GeoTransform { origin_x: extent.min_x, origin_y: extent.max_y, pixel_width: cell, pixel_height: -cell }; - Raster::new(name, w as u32, h as u32, vec![data], gt, crs, Some(NODATA as f64), ColorHint::Gray, "Float32").map_err(|e| e.to_string()) + let mut r = Raster::new(name, w as u32, h as u32, vec![data], gt, crs, Some(NODATA as f64), ColorHint::Gray, "Float32") + .map_err(|e| e.to_string())?; + if let Some(note) = past_f32_note(past.into_inner()) { + r.lost.push(rustgis_data::loss::Note::loss(rustgis_data::loss::LossCode::DroppedValue, note)); + } + Ok(r) } /// Unsupervised k-means classes (1..=k) of the pixels over the given bands. @@ -1329,7 +1368,7 @@ fn kmeans_on(threads: Option, r: &Raster, bands: &[usize], k: usize, iter cs.iter() .enumerate() .map(|(i, c)| (i, c.iter().zip(p).map(|(a, b)| (a - b).powi(2)).sum::())) - .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)) + .min_by(|a, b| a.1.total_cmp(&b.1)) .map_or(0, |x| x.0) }; let mut sums = vec![vec![0.0; data.len()]; centres.len()]; @@ -1362,7 +1401,9 @@ fn kmeans_on(threads: Option, r: &Raster, bands: &[usize], k: usize, iter // Classes numbered by the first band's centre, low to high. let mut order: Vec = (0..centres.len()).collect(); order.sort_by(|a, b| { - centres.get(*a).and_then(|c| c.first()).partial_cmp(¢res.get(*b).and_then(|c| c.first())).unwrap_or(std::cmp::Ordering::Equal) + let fa = centres.get(*a).and_then(|c| c.first().copied()).unwrap_or(f64::NAN); + let fb = centres.get(*b).and_then(|c| c.first().copied()).unwrap_or(f64::NAN); + fa.total_cmp(&fb) }); let rank: Vec = (0..centres.len()).map(|c| order.iter().position(|o| *o == c).unwrap_or(0)).collect(); let (w, h) = (r.width as usize, r.height as usize); @@ -1415,7 +1456,7 @@ pub fn classify_min_distance(r: &Raster, bands: &[usize], means: &[(f32, Vec())) - .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)) + .min_by(|a, b| a.1.total_cmp(&b.1)) .map_or(NODATA, |x| x.0) }, ) @@ -2985,9 +3026,9 @@ mod tests { .unwrap(); let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); for expr in ["(b1 - b2) / (b1 + b2)", "b3 * 2 + 1 / b1"] { - let one = band_math_on(Some(1), &r, expr).unwrap(); + let one = band_math_on(Some(1), &r, expr).unwrap().0; for threads in [2, 7, 16] { - assert_eq!(bits(&band_math_on(Some(threads), &r, expr).unwrap()), bits(&one), "{expr}, {threads} threads"); + assert_eq!(bits(&band_math_on(Some(threads), &r, expr).unwrap().0), bits(&one), "{expr}, {threads} threads"); } } let f = |c: i64, row: i64| (c % 5 != 0).then(|| r.value(1, c, row).map(|v| f64::from(v) / ((c - row) as f64))).flatten(); @@ -4004,6 +4045,79 @@ mod tests { } } + #[test] + fn band_math_ignores_nodata_in_unreferenced_band() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 }; + let b1 = vec![10.0, NODATA, 30.0, 40.0]; + let b2 = vec![NODATA, 2.0, NODATA, 4.0]; + let r = Raster::new("m", 2, 2, vec![b1, b2], gt, Crs::LonLat, Some(NODATA as f64), ColorHint::Gray, "Float32").unwrap(); + let out = band_math(&r, "b1 * 2").unwrap(); + assert_eq!(out, vec![20.0, NODATA, 60.0, 80.0]); + let both = band_math(&r, "b1 + b2").unwrap(); + assert_eq!(both, vec![NODATA, NODATA, NODATA, 44.0]); + } + + #[test] + fn raster_ops_turn_f64_to_f32_overflow_into_nodata() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r = Raster::new( + "big", + 2, + 1, + vec![vec![1e20f32, 2.0], vec![1e20f32, 3.0]], + gt, + Crs::LonLat, + Some(NODATA as f64), + ColorHint::Gray, + "Float32", + ) + .unwrap(); + // Each cell past the range is counted, and said; a clean result says nothing. + assert_eq!(band_math_reported(&r, "b1 * b2").unwrap(), (vec![NODATA, 6.0], 1)); + assert_eq!(band_math_reported(&r, "b1 + b2").unwrap(), (vec![2e20, 5.0], 0)); + assert_eq!(past_f32_note(1).as_deref(), Some("1 cell past the range of 32-bit floats (±3.4 × 10^38) has no value")); + assert_eq!(past_f32_note(0), None); + + let remapped = remap(&r, 0, &[(0.0, 10.0, 1e40)], true).unwrap(); + assert_eq!((remapped.cells[1], remapped.past_f32), (NODATA, 1)); + assert_eq!(remap(&r, 0, &[(0.0, 10.0, 1e30)], true).unwrap().past_f32, 0); + + let past = + |r: &Raster| r.lost.texts().filter(|t| t.contains("past the range of 32-bit floats")).map(String::from).collect::>(); + let pts = vec![(Coord::new(0.0, 0.0), 1e40), (Coord::new(1.0, 1.0), 1e40)]; + let ext = Extent::new(0.0, 0.0, 1.0, 1.0); + let idw_r = idw(&pts, &ext, 0.5, 2.0, 0, "idw", Crs::LonLat).unwrap(); + assert!(idw_r.bands[0].data.iter().all(|&v| v == NODATA), "{:?}", idw_r.bands[0].data); + assert_eq!(past(&idw_r), vec!["4 cells past the range of 32-bit floats (±3.4 × 10^38) have no value".to_string()]); + + let vp = crate::kriging::auto_variogram(&pts, &ext, crate::kriging::VariogramModel::Spherical); + let krig_r = crate::kriging::kriging(&pts, &ext, 0.5, &vp, 2, "krig", Crs::LonLat).unwrap(); + assert!(krig_r.bands[0].data.iter().all(|&v| v == NODATA), "{:?}", krig_r.bands[0].data); + // Each note names the output that lost the values: here the prediction. + assert_eq!(past(&krig_r), vec!["krig: 4 cells past the range of 32-bit floats (±3.4 × 10^38) have no value".to_string()]); + // Values that fit but spread past it: the prediction keeps them, the variance can't. + let spread = vec![(Coord::new(0.0, 0.0), 0.0), (Coord::new(1.0, 1.0), 1e30)]; + let vp = crate::kriging::auto_variogram(&spread, &ext, crate::kriging::VariogramModel::Spherical); + let spread_r = crate::kriging::kriging(&spread, &ext, 0.5, &vp, 2, "krig", Crs::LonLat).unwrap(); + let notes = past(&spread_r); + assert!(!notes.is_empty() && notes.iter().all(|n| n.starts_with("krig_variance: ")), "{notes:?}"); + + let clean = vec![(Coord::new(0.0, 0.0), 1.0), (Coord::new(1.0, 1.0), 3.0)]; + assert!(past(&idw(&clean, &ext, 0.5, 2.0, 0, "idw", Crs::LonLat).unwrap()).is_empty()); + let vp = crate::kriging::auto_variogram(&clean, &ext, crate::kriging::VariogramModel::Spherical); + assert!(past(&crate::kriging::kriging(&clean, &ext, 0.5, &vp, 2, "krig", Crs::LonLat).unwrap()).is_empty()); + } + + #[test] + fn viewshed_rejects_non_finite_observer_height() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 0.003, pixel_width: 0.001, pixel_height: -0.001 }; + let r = Raster::new("dem", 3, 3, vec![vec![100.0; 9]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let obs = Coord::new(0.0015, 0.0015); + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(viewshed(&r, 0, obs, bad, 1_000.0, Heights::Nearest).is_err(), "height={bad}"); + } + } + #[test] fn profile_guards_nan_and_interpolates_across_antimeridian() { // Global 1-degree LonLat raster: elevation 100 near +/-180 deg, 0 elsewhere. diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 501ea9a95b..f187aaa6b2 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5422,12 +5422,21 @@ fn idw_interpolation(inp: &dyn Inputs, p: &Json) -> Result { let bytes = rustgis_data::raster::geotiff::write(&r, 0).map_err(|e| e.to_string())?; let msg = format!("IDW Interpolation: {} × {} cells from {} points", r.width, r.height, pts.len()); Ok(ToolResult { - losses: left_out.losses("IDW Interpolation", picked.len(), field, "a coordinate is not a finite number"), + losses: left_out + .losses("IDW Interpolation", picked.len(), field, "a coordinate is not a finite number") + .into_iter() + .chain(raster_losses(&r)) + .collect(), output: Output::Layers(vec![OutputLayer::Raster { file_name: format!("{name}.tif"), name, bytes }]), messages: std::iter::once(msg).chain(beyond_note).chain(crs_note).collect(), }) } +/// The losses an interpolated raster's notes give, such as cells past the range of 32-bit floats. +fn raster_losses(r: &rustgis_data::raster::Raster) -> Vec { + r.lost.iter().filter_map(|n| n.loss.map(|code| rustgis_data::loss::LossMessage { code, text: n.text.clone() })).collect() +} + /// The automatic IDW cell size: 300 cells across the extent, coarsened until every cell weighing /// every one of `n` points stays within the interpolation's work limit. fn idw_auto_cell(extent: &Extent, n: usize) -> f64 { @@ -5572,12 +5581,11 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result, b: &geo::Rect) -> bool { pub fn overlaps(ds: &Dataset, rows: &[usize]) -> Checked { let mut p = polygons(ds, rows); // Sweep from west to east: only polygons whose boxes overlap in x are compared. - p.sort_by(|a, b| a.2.min().x.partial_cmp(&b.2.min().x).unwrap_or(std::cmp::Ordering::Equal)); + p.sort_by(|a, b| a.2.min().x.total_cmp(&b.2.min().x)); let mut out = Vec::new(); let mut work = 0usize; crate::control::begin(p.len()); diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index adedacaff6..5357f80e7b 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -1119,6 +1119,9 @@ impl Agent { // Its steps count against this message's budget; its "always" approvals stay. self.steps = self.steps.saturating_add(child.steps); for key in &child.always { + if self.always.contains(key) { + continue; + } if self.always.len() >= 64 { self.always.remove(0); } @@ -1194,6 +1197,7 @@ impl Agent { if allow && always && let Some(remembered) = self.pending_policy.as_ref().and_then(Pending::remember) + && !self.always.contains(&remembered) { if self.always.len() >= 64 { self.always.remove(0); @@ -1475,3 +1479,89 @@ impl Drop for Agent { self.live.0.store(false, Ordering::SeqCst); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::provider::Config; + use rustgis_engine::{Project, Session}; + use serde_json::json; + + fn test_cfg() -> Config { + let mut c = Config::from_env("openai"); + c.key = "k".into(); + c + } + + #[test] + fn repeated_subagent_delegation_does_not_duplicate_or_evict_always_approvals() { + let mut s = Session::new(Project::default()); + let mut a = Agent::new(test_cfg(), &s); + + let reply = |body: serde_json::Value| Ok(HttpResponse { status: 200, body: body.to_string().into_bytes(), headers: vec![] }); + let call_msg = |id: &str, name: &str, args: serde_json::Value| { + reply(json!({ + "choices": [{ + "message": { + "role": "assistant", + "content": null, + "tool_calls": [{ + "id": id, + "type": "function", + "function": { "name": name, "arguments": args.to_string() } + }] + } + }] + })) + }; + let say_msg = |text: &str| reply(json!({ "choices": [{ "message": { "role": "assistant", "content": text } }] })); + + // Approve one action with always=true, then delegate to a subagent three times. + assert!(matches!(a.ask("add data", &s), Step::Send(_))); + let add = call_msg("e0", "run_command", json!({"command": "layer.addData", "params": {"path": "nonexistent-always.geojson"}})); + assert_eq!(a.receive(a.generation(), add, &mut s), Step::Confirm); + let asked = a.asking().unwrap_or_else(|| panic!("no approval waiting")); + assert!(matches!(a.decide(&asked, true, true, &mut s), Some(Step::Send(_)))); + assert_eq!(a.always.len(), 1); + + for i in 0..3 { + let del = call_msg(&format!("d{i}"), "delegate", json!({"task": "check map"})); + assert!(matches!(a.receive(a.generation(), del, &mut s), Step::Send(_))); + assert!(matches!(a.receive(a.generation(), say_msg("done"), &mut s), Step::Send(_))); + assert_eq!(a.always.len(), 1, "delegation {i} duplicated always approvals"); + } + assert_eq!(a.receive(a.generation(), say_msg("all done"), &mut s), Step::Done); + + // Filling all 64 slots and merging a child with an already-remembered key must not evict slot 0. + let mut parent = Agent::new(test_cfg(), &s); + for i in 0..64 { + assert!(matches!(parent.ask("run", &s), Step::Send(_))); + let c = call_msg( + &format!("k{i}"), + "run_command", + json!({"command": "layer.addData", "params": {"path": format!("nonexistent-{i}.geojson")}}), + ); + assert_eq!(parent.receive(parent.generation(), c, &mut s), Step::Confirm); + let asked = parent.asking().unwrap_or_else(|| panic!("no approval waiting")); + assert!(matches!(parent.decide(&asked, true, true, &mut s), Some(Step::Send(_)))); + assert_eq!(parent.receive(parent.generation(), say_msg("ok"), &mut s), Step::Done); + } + assert_eq!(parent.always.len(), 64); + assert!(matches!(parent.ask("delegate", &s), Step::Send(_))); + let del = call_msg("d-full", "delegate", json!({"task": "noop"})); + assert!(matches!(parent.receive(parent.generation(), del, &mut s), Step::Send(_))); + // Simulate a child that carries only the newest remembered key (already in parent.always). + if let Some(child) = parent.child.as_mut() { + child.always.drain(..63); + } + assert!(matches!(parent.receive(parent.generation(), say_msg("done"), &mut s), Step::Send(_))); + assert_eq!(parent.always.len(), 64); + // Re-running the oldest approved call must still be covered without prompting again. + let repeat_first = + call_msg("k0-again", "run_command", json!({"command": "layer.addData", "params": {"path": "nonexistent-0.geojson"}})); + assert!( + matches!(parent.receive(parent.generation(), repeat_first, &mut s), Step::Send(_)), + "duplicate key from child evicted oldest approval" + ); + } +} diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 0ac677118d..6a022dce0e 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -4088,7 +4088,7 @@ enum Phase { order: WfsOrder, }, /// An OGC API or WFS page, retaining the largest reported legacy total across the chain. - Linked { total: Option }, + Linked { total: Option, pages: usize, empty_streak: usize }, /// An ArcGIS page, `size` long from an offset, in `order`. `start` is the first such page's /// first feature (a server that ignores the offset sends it again), once it is read; until /// then `first` keeps the first page as it came, to fall back on (none: the address asked @@ -4142,6 +4142,11 @@ fn split_page(bytes: &[u8]) -> Result, max: usize, paging: Option = None; let following = match &mut self.phase { Phase::WfsOffsets { matched, offset, size, ids, unidentified, overlap, duplicates, order } => { let returned = more.len(); @@ -4674,9 +4687,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), }; @@ -4689,6 +4718,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); @@ -4701,7 +4733,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(); @@ -10137,4 +10169,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 <= MAX_EMPTY_LINKED_PAGES * 2, "linked paging did not stop on endless empty next links"); + Ok(empty(calls + 1)) + }); + assert!(calls <= MAX_EMPTY_LINKED_PAGES, "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 c20dfd9999..7a73f7d5d6 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -201,6 +201,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), @@ -472,6 +473,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. @@ -1292,7 +1294,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 8a063384ff..72fbcf147a 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())); diff --git a/crates/data/src/raster/grib/rows.rs b/crates/data/src/raster/grib/rows.rs index 33fc079c99..c0fa7d98ec 100644 --- a/crates/data/src/raster/grib/rows.rs +++ b/crates/data/src/raster/grib/rows.rs @@ -67,6 +67,7 @@ fn why(s: Skip) -> 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/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index f446d25001..2aa505cd7d 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -1551,6 +1551,57 @@ 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 first = Cx::new(&[(7, 3, &[5]), (300, 0, &[0; 5]), (2, 9, &[0, 511, 100])]).message(); + // Append a second valid field inside the same GRIB2 message so we also prove decoding stops + // immediately after cancellation instead of continuing to later fields. + let mut two_fields = first[16 + 21..first.len() - 4].to_vec(); + two_fields.extend(F2::new(2, 1, vec![1, 2]).sections()); + let msg = message_of(&two_fields); + let _guard = crate::progress::install(Some(std::sync::Arc::new(AlwaysCancelled))); + let decoded = grib2(&msg, usize::MAX, None, Uncounted::default()); + assert_eq!(decoded.len(), 1, "expected decoding to stop after cancellation"); + assert!(matches!(decoded.first(), Some(Err(Skip::Cancelled))), "expected Skip::Cancelled"); +} + /// The rows of `bbox` of `file` (one record) as [`plan`] and [`Rows::read`] give them from its /// first octets and one run of the others, checked against the whole record read and [`cut`]: /// the raster, and the octets of the run. diff --git a/crates/data/src/sqlite.rs b/crates/data/src/sqlite.rs index 6e2d4d33b7..80d0f89ff9 100644 --- a/crates/data/src/sqlite.rs +++ b/crates/data/src/sqlite.rs @@ -126,9 +126,9 @@ impl> Db { match kind { // An interior table page: child pointers, then the right-most child. 0x05 => { + 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"))?; + 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"))?); @@ -136,8 +136,12 @@ impl> Db { } // A leaf table page: (payload size, rowid, payload) cells. 0x0d => { - 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"))?; let payload = self.payload_seen(page, a, size, &mut seen)?; @@ -185,11 +189,16 @@ 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 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"))?; - steps.push(Step::Page(be32(page, at).ok_or_else(|| bad("interior cell"))?)); + 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"))?; + 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"))?)); @@ -197,8 +206,11 @@ impl> Db { } // A leaf index page: (payload size, payload) cells. 0x0a => { - 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"))?; let payload = self.payload_with(page, a, size, max_local, Some(&mut seen))?; if f(record(&payload)?).is_break() { @@ -228,8 +240,7 @@ impl> Db { let cells = be16(page, hdr + 3).ok_or_else(|| bad("page header"))?; match page.get(hdr) { Some(0x05) => { - for i in 0..cells { - let at = be16(page, hdr + 12 + 2 * i).ok_or_else(|| bad("cell pointer"))?; + 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"))?); @@ -241,6 +252,65 @@ 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"))?; + // 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")); + } + 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 { + 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> { @@ -255,13 +325,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"))?); @@ -359,6 +423,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)?]))) @@ -748,6 +819,106 @@ 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")); + + // 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"))); + // 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)); + } + #[test] fn create_table_columns() { let (cols, pk) = parse_create_table( diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 7dbf9ecca4..3cf5643a5a 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/stac_bands.rs b/crates/engine/src/cmd/stac_bands.rs index 71fe9c2814..e086a1a199 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 8177a8ff22..e417065ffb 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -476,6 +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, 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 { @@ -484,6 +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"))); + // 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 { "" }; @@ -496,7 +516,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); @@ -1629,6 +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 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, @@ -1657,9 +1681,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, 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, at_most)); + 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 +1712,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, at_most)); if !rasterops::has_values(&remap.cells, r.width as usize)? { remaps.emptied.get_or_insert_with(|| r.name.clone()); } @@ -1843,6 +1875,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, bool)>, } #[cfg(not(target_arch = "wasm32"))] @@ -1858,6 +1892,14 @@ impl BlockRemaps { self.terrain.push((name, edges)); } } + 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, at_most)); + } + } self.empty = Some(match self.empty.take() { None => r.empty, Some(mut e) => { @@ -1876,7 +1918,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 +2059,26 @@ fn suitability_work(s: &Session, p: &Value) -> Result { let first = first.read()?; let mut scored = Vec::new(); let mut empty = 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))); + 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(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/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/engine/src/tests.rs b/crates/engine/src/tests.rs index 047037f1f9..a71710720f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -19978,6 +19978,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] @@ -59651,6 +59676,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 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 b43c5f1db4..e06e537938 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 }