From aacde49754d219551a43a989c8c9dd40bf121e67 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 08:51:58 -0500 Subject: [PATCH 01/14] Harden parser bounds, numeric precision, and URL/range handling Fixes ten parser, bounds, and correctness bugs across rustgis-data and rustgis-tiles: - Spreadsheets: compute sheet cell spans and error-message row indices in u64 so u32::MAX coordinates cannot overflow or wrap. - LandXML: skip nested elements to prevent quadratic face amplification, enforce MAX_FACES across the full file, and poll Cancel in the

and loops. - OSM PBF: track and cap cumulative decoded tag and role text bytes on Osm to bound StringTable amplification. - FileGDB: reject duplicate non-zero row offsets in .gdbtablx, reject non-finite decoded point and delta coordinates, and count kind == 3 multipatch inner rings against the ring cap. - WKT CSV export: reuse io::csv_needs_guard in wkt_csv_text for parity with CSV formula-injection guarding. - Pure-Rust SQLite: ignore commas, parentheses, and quotes inside SQL line (--) and block (/* */) comments in split_top, and handle doubled quotes inside quoted identifiers and literals. - GRIB2 complex packing: guard the all-ones missing-value check with width > 0 so 0-bit constant groups with ref_bits == 0 decode to their value rather than NaN. - Expressions: validate min()/max() arguments through number() so non-numeric values record faults while NULLs are skipped, and preserve exact i64 ordering above 2^53. - Byte ranges: use checked arithmetic in tiles::cache, pmtiles::read, pmtiles::find, and cog::read so overflowing offsets return an error instead of wrapping or falling back to a full-file GET. - STAC URL resolution: align stac::resolve_plain with RFC 3986 for query/fragment-only links, strict scheme detection before ://, and authority splitting on /, ?, and #. --- crates/data/src/filegdb.rs | 66 +++++++++--- crates/data/src/filegdb/tests.rs | 46 ++++++++ crates/data/src/interop.rs | 12 ++- crates/data/src/io.rs | 2 +- crates/data/src/landxml.rs | 77 ++++++++++++-- crates/data/src/osm.rs | 141 +++++++++++++++++++++---- crates/data/src/query.rs | 13 ++- crates/data/src/query/tests.rs | 35 ++++++ crates/data/src/raster/grib/complex.rs | 11 +- crates/data/src/raster/grib_tests.rs | 11 ++ crates/data/src/sheets.rs | 49 ++++++--- crates/data/src/sqlite.rs | 84 ++++++++++++--- crates/tiles/src/cache.rs | 34 +++++- crates/tiles/src/cog.rs | 15 ++- crates/tiles/src/pmtiles.rs | 23 +++- crates/tiles/src/stac.rs | 75 ++++++++++--- 16 files changed, 583 insertions(+), 111 deletions(-) diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index 00f125b966..7380928652 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -937,6 +937,7 @@ fn row_offsets(x: &[u8]) -> Result> { Some(bits) => total.div_ceil(1024).min(bits.len().saturating_mul(8)), }; let mut out = Vec::new(); + let mut seen = std::collections::HashSet::new(); let mut stored_before = 0usize; for block in 0..in_blocks { let present = bitmap.is_none_or(|bits| bits.get(block / 8).is_some_and(|b| b >> (block % 8) & 1 == 1)); @@ -960,6 +961,9 @@ fn row_offsets(x: &[u8]) -> Result> { continue; } if let Ok(offset) = usize::try_from(offset) { + if !seen.insert(offset) { + return Err(bad("duplicate row offset")); + } out.push((row as u64 + 1, offset)); } } @@ -1005,7 +1009,11 @@ fn decode_geometry(b: &[u8], def: &GeomDef, budget: &mut usize) -> std::result:: if vx == 0 || vy == 0 { return Ok(Decoded::Empty); } - Ok(Decoded::Geometry(Geometry::Point(Coord::new(x((vx - 1) as f64), y((vy - 1) as f64))), 0)) + let (px, py) = (x((vx - 1) as f64), y((vy - 1) as f64)); + if !px.is_finite() || !py.is_finite() { + return Err(()); + } + Ok(Decoded::Geometry(Geometry::Point(Coord::new(px, py)), 0)) } // Multipoints. 8 | 18 | 20 | 28 | 53 => { @@ -1112,7 +1120,11 @@ fn deltas(c: &mut Cur, n: usize, def: &GeomDef) -> std::result::Result f64 { } /// A multipatch's faces, each its outer ring and then its holes: triangles from strips, fans and -/// triangle lists, and rings. At most [`MAX_FACES`]; the flag says some were left out. +/// triangle lists, and rings. At most [`MAX_FACES`] rings in total; the flag says some were left +/// out. fn faces(parts: &[Vec], kinds: &[u64]) -> (Vec>>, bool) { + faces_limited(parts, kinds, MAX_FACES) +} + +fn faces_limited(parts: &[Vec], kinds: &[u64], limit: usize) -> (Vec>>, bool) { let mut faces: Vec>> = Vec::new(); + let mut rings = 0usize; let mut truncated = false; for (part, &kind) in parts.iter().zip(kinds) { - // Faces past the cap are left out, within a part too (one strip can hold millions). - let room = MAX_FACES.saturating_sub(faces.len()); + // Faces and inner rings past the cap are left out, within a part too (one strip can hold millions). + let room = limit.saturating_sub(rings); let has = match kind { 0 | 1 => part.len().saturating_sub(2), 6 => part.len() / 3, - 3 => 0, _ => 1, }; if has > room { truncated = true; } if room == 0 { - break; + if truncated { + break; + } + continue; } match kind { // Triangle strip, fan, triangles. - 0 => faces.extend(part.windows(3).take(room).map(|w| vec![w.to_vec()])), + 0 => { + let take = part.len().saturating_sub(2).min(room); + faces.extend(part.windows(3).take(take).map(|w| vec![w.to_vec()])); + rings += take; + } 1 => { if let Some((first, rest)) = part.split_first() { + let take = rest.len().saturating_sub(1).min(room); faces.extend( rest.windows(2) .filter_map(|w| match w { [a, b] => Some(vec![vec![*first, *a, *b]]), _ => None, }) - .take(room), + .take(take), ); + rings += take; } } - 6 => faces.extend(part.as_chunks::<3>().0.iter().take(room).map(|w| vec![w.to_vec()])), + 6 => { + let take = (part.len() / 3).min(room); + faces.extend(part.as_chunks::<3>().0.iter().take(take).map(|w| vec![w.to_vec()])); + rings += take; + } // An inner ring is a hole in the face before. - 3 => match faces.last_mut() { - Some(face) => face.push(part.clone()), - None => faces.push(vec![part.clone()]), - }, + 3 => { + match faces.last_mut() { + Some(face) => face.push(part.clone()), + None => faces.push(vec![part.clone()]), + } + rings += 1; + } // Outer, first and plain rings. - _ => faces.push(vec![part.clone()]), + _ => { + faces.push(vec![part.clone()]); + rings += 1; + } } } (faces, truncated) diff --git a/crates/data/src/filegdb/tests.rs b/crates/data/src/filegdb/tests.rs index c45d707b69..8437389363 100644 --- a/crates/data/src/filegdb/tests.rs +++ b/crates/data/src/filegdb/tests.rs @@ -956,3 +956,49 @@ fn filegdb_temporal_fields_keep_days_offsets_and_null_notices() { } } } + +#[test] +fn duplicate_row_offsets_are_refused() { + let (t, mut x) = table(0, &[F::Oid, F::Text("name")], &[vec![V::Text(Some("a"))], vec![V::Text(Some("b"))]]); + // Row index entries start at byte 16 with width 4; copy row 0's offset into row 1's slot. + let first_offset: [u8; 4] = x[16..20].try_into().unwrap(); + x[20..24].copy_from_slice(&first_offset); + let err = row_offsets(&x).unwrap_err().to_string(); + assert!(err.contains("duplicate row offset"), "{err}"); + assert!(read_table("dup", &t, &x, None).is_err()); +} + +#[test] +fn non_finite_coordinates_are_rejected() { + let tiny_scale = GeomDef { wkt: String::new(), x0: 0.0, y0: 0.0, xy_scale: 1e-308, z0: 0.0, z_scale: 1.0 }; + // Point (code 1): vx = 2, vy = 2 -> (1.0 / 1e-308) is finite; vx = 1000 -> 999 / 1e-308 = inf. + let mut pt = varuint(1); + pt.extend(varuint(1000)); + pt.extend(varuint(2)); + assert!(decode_geometry(&pt, &tiny_scale, &mut 100).is_err()); + + // Polyline (code 3): 2 points, 1 part, bbox(4 varuints), delta (1000, 0) overflows to inf. + let mut line = varuint(3); + line.extend(varuint(2)); + line.extend(varuint(1)); + for _ in 0..4 { + line.extend(varuint(0)); + } + line.extend(varint(1000)); + line.extend(varint(0)); + line.extend(varint(0)); + line.extend(varint(0)); + assert!(decode_geometry(&line, &tiny_scale, &mut 100).is_err()); +} + +#[test] +fn multipatch_inner_rings_respect_ring_budget() { + let ring = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]; + let parts = vec![ring; 6]; + // 1 outer ring (kind 2) followed by 5 inner rings (kind 3). + let kinds = [2, 3, 3, 3, 3, 3]; + let (got, truncated) = faces_limited(&parts, &kinds, 3); + assert!(truncated, "inner rings past the ring budget must set truncated"); + let total_rings: usize = got.iter().map(Vec::len).sum(); + assert_eq!(total_rings, 3); +} diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index 646dac96ca..f0b3bfc2aa 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -523,7 +523,7 @@ impl WktParser { /// A [`to_wkt_csv`] cell's text before quoting: text starting like a formula is prefixed with `'` /// so spreadsheets show it rather than run it. pub(crate) fn wkt_csv_text(s: &str) -> String { - if s.starts_with(['=', '+', '-', '@']) && s.parse::().is_err() { format!("'{s}") } else { s.to_string() } + if crate::io::csv_needs_guard(s) { format!("'{s}") } else { s.to_string() } } /// CSV with a `wkt` geometry column and every attribute; cancellable between features. @@ -609,4 +609,14 @@ mod tests { let c = to_wkt_csv(&ds).unwrap(); assert!(c.contains("POINT (1 2),,0.1234567891\n") && c.contains(",B,0.000000001\n"), "{c}"); } + + #[test] + fn wkt_csv_formula_guard_matches_csv() { + for guarded in ["=SUM(A1)", "@cmd", "\t=1", "\r+1", "+Inf", "-NaN", "+0123", "-007", "+1234567890123456", "-1234567890123456"] { + assert_eq!(wkt_csv_text(guarded), format!("'{guarded}"), "{guarded:?}"); + } + for plain in ["-12.5", "+42", "-0.5", "Paris"] { + assert_eq!(wkt_csv_text(plain), plain, "{plain:?}"); + } + } } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 6db7769c20..da6b9757c7 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3269,7 +3269,7 @@ const FORMULA_START: [char; 6] = ['=', '+', '-', '@', '\t', '\r']; /// Text needs an apostrophe if it starts like a spreadsheet formula. The numeric exception /// keeps finite numbers that fit Double precision and have at most 15 significant digits. /// A leading-zero code stays guarded unless its mantissa has digits after a decimal point. -fn csv_needs_guard(text: &str) -> bool { +pub(crate) fn csv_needs_guard(text: &str) -> bool { if !text.starts_with(FORMULA_START) { return false; } diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index 347911e41e..19e8dea014 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -20,7 +20,7 @@ use crate::{DataError, Dataset, Field, FieldType, Geometry, GeometryType, ReadRe /// LandXML file types (often plain `.xml`, read when its contents say so). pub const EXTENSIONS: &[&str] = &["landxml"]; -/// The most TIN faces read from one surface. +/// The most TIN faces read from a LandXML file. const MAX_FACES: usize = 2_000_000; pub fn is_landxml_name(name: &str) -> bool { @@ -58,6 +58,10 @@ fn nez(s: &str) -> Option<(Coord, Option)> { /// Reads a LandXML file into its layers (those with features). `crs` is the coordinate system of /// a file that doesn't say. pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result> { + read_with_max_faces(file_name, bytes, crs, MAX_FACES) +} + +fn read_with_max_faces(file_name: &str, bytes: &[u8], crs: Option, max_faces: usize) -> Result> { let name = std::path::Path::new(file_name).file_stem().and_then(|s| s.to_str()).unwrap_or("landxml").to_string(); let text = std::str::from_utf8(bytes).map_err(|_| DataError::Format(format!("{file_name} is not UTF-8 text")))?; let opts = ParsingOptions { allow_dtd: false, nodes_limit: crate::io::XML_NODES, ..ParsingOptions::default() }; @@ -199,10 +203,20 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result = Vec::new(); let mut faces_left_out = 0usize; + let mut total_faces = 0usize; for s in elements(&root, "Surface") { + // Nested `` elements would revisit every descendant `

` and ``, multiplying + // work and face counts quadratically. + if s.ancestors().skip(1).any(|a| a.is_element() && local(&a) == "Surface") { + continue; + } + crate::progress::check()?; let sname = s.attribute("name").unwrap_or("").to_string(); let mut pnts: HashMap<&str, (Coord, Option)> = HashMap::new(); - for p in elements(&s, "P") { + for (pi, p) in elements(&s, "P").enumerate() { + if pi.is_multiple_of(1024) { + crate::progress::check()?; + } // A point that can't be read isn't kept. The faces that name it are left out, and // counted as features, so the point is said on its own without a code. match (p.attribute("id"), nez(&text_of(&p))) { @@ -214,15 +228,21 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result= MAX_FACES { - if i == MAX_FACES { + let mut s_over_limit = false; + for (fi, f) in elements(&s, "F").filter(|f| f.attribute("i") != Some("1")).enumerate() { + if fi.is_multiple_of(1024) { + crate::progress::check()?; + } + // Past the file-wide limit, a face is only counted, so the notice says how many are left out. + if total_faces >= max_faces { + if !s_over_limit { over_limit.push(sname.clone()); + s_over_limit = true; } faces_left_out += 1; continue; } + total_faces += 1; let tri: Option)>> = text_of(&f).split_whitespace().map(|id| pnts.get(id).copied()).collect(); match tri.as_deref() { Some([a, b, c]) => { @@ -246,7 +266,7 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result {} [one] => report.messages.push(crate::loss::Note::loss( crate::loss::LossCode::DroppedOverLimit, - format!("surface '{one}' has more than {MAX_FACES} faces: the {faces_left_out} past the limit are left out"), + format!("surface '{one}' has more than {max_faces} faces: the {faces_left_out} past the limit are left out"), )), many => { let shown: Vec = many.iter().take(10).map(|n| format!("'{n}'")).collect(); @@ -254,7 +274,7 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result + + + +

0 0 1

0 1 1

1 0 1

+ 1 2 3 + +
+ + "#; + let layers = read("nested.xml", nested.as_bytes(), None).unwrap(); + assert_eq!(layers.len(), 1); + assert_eq!(layers[0].0.features.len(), 1, "nested must not duplicate faces"); + + let two_surfaces = r#" + +

0 0 1

0 1 1

1 0 1

+ 1 2 31 2 31 2 3 +
+ +

0 0 2

0 1 2

1 0 2

+ 1 2 31 2 31 2 3 +
+
"#; + let layers = read_with_max_faces("two.xml", two_surfaces.as_bytes(), None, 4).unwrap(); + assert_eq!(layers[0].0.features.len(), 4, "file-wide face cap must bound sibling surfaces"); + assert!( + layers[0].1.messages.iter().any(|m| m.loss == Some(crate::loss::LossCode::DroppedOverLimit) && m.contains("2 past the limit")) + ); + } + + #[test] + fn a_cancelled_landxml_surface_read_stops() { + let probe = std::sync::Arc::new(crate::progress::tests::Counted::default()); + probe.cancel.store(true, std::sync::atomic::Ordering::Relaxed); + let _g = crate::progress::install(Some(probe)); + assert!(matches!(read("site.xml", LANDXML.as_bytes(), None), Err(DataError::Cancelled))); + } } diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 0c98e1f060..5328fbbb20 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -24,6 +24,9 @@ const MAX_MEMBERS: usize = 100_000; const MAX_WAYS: usize = MAX_NODES / 4; const MAX_REFS: usize = MAX_NODES * 2; const MAX_RELATIONS: usize = MAX_NODES / 40; +/// The most decoded tag and role text bytes kept across an OSM PBF file: a small compressed block +/// can repeat one string-table entry across thousands of entities. +const MAX_TEXT_BYTES: usize = if cfg!(target_arch = "wasm32") { 64 << 20 } else { 256 << 20 }; /// Keys with a field of their own (as GDAL's OSM driver gives them). const KEYS: &[&str] = &[ @@ -256,12 +259,21 @@ fn ignored(key: &str) -> bool { || key.starts_with("openGeoDB:") } -fn tags(strings: &[String], keys: &[u64], vals: &[u64]) -> Tags { - keys.iter() - .zip(vals) - .filter_map(|(k, v)| Some((strings.get(usize::try_from(*k).ok()?)?.clone(), strings.get(usize::try_from(*v).ok()?)?.clone()))) - .filter(|(k, _)| !ignored(k)) - .collect() +fn tags(osm: &mut Osm, strings: &[String], keys: &[u64], vals: &[u64]) -> Result { + let mut out = Vec::new(); + for (k, v) in keys.iter().zip(vals) { + let (Some(k), Some(v)) = + (usize::try_from(*k).ok().and_then(|i| strings.get(i)), usize::try_from(*v).ok().and_then(|i| strings.get(i))) + else { + continue; + }; + if ignored(k) { + continue; + } + osm.charge_text(k.len().saturating_add(v.len()))?; + out.push((k.clone(), v.clone())); + } + Ok(out) } fn tag<'t>(t: &'t [(String, String)], k: &str) -> Option<&'t str> { @@ -269,7 +281,6 @@ fn tag<'t>(t: &'t [(String, String)], k: &str) -> Option<&'t str> { } /// What was read: nodes (sorted by id), tagged nodes, ways, and relations. -#[derive(Default)] struct Osm { nodes: Vec<(i64, i32, i32)>, points: Vec<(i64, Coord, Tags)>, @@ -281,6 +292,34 @@ struct Osm { capped: bool, /// Members omitted at the per-relation limit; wide enough for all bounded relations. omitted_members: u64, + /// Cumulative bytes of decoded tag and role strings retained across the file. + text_bytes: usize, + text_limit: usize, +} + +impl Osm { + fn with_text_limit(text_limit: usize) -> Self { + Osm { + nodes: Vec::new(), + points: Vec::new(), + ways: Vec::new(), + refs: 0, + relations: Vec::new(), + capped: false, + omitted_members: 0, + text_bytes: 0, + text_limit, + } + } + + fn charge_text(&mut self, bytes: usize) -> Result<()> { + let next = self.text_bytes.saturating_add(bytes); + if next > self.text_limit { + return Err(DataError::Format(format!("OSM PBF decoded text exceeds the limit of {} bytes", self.text_limit))); + } + self.text_bytes = next; + Ok(()) + } } /// Degrees from OSM's fixed point (1e-7°), and back. @@ -346,7 +385,8 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { _ => {} } } - keep(osm, id, lat, lon, tags(&strings, &k, &vv)); + let t = tags(osm, &strings, &k, &vv)?; + keep(osm, id, lat, lon, t); } // Dense nodes. 2 => { @@ -374,6 +414,7 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { if let (Some(k), Some(v)) = (at(k), at(v)) && !ignored(k) { + osm.charge_text(k.len().saturating_add(v.len()))?; t.push((k.clone(), v.clone())); } } @@ -407,8 +448,9 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { .map(|(la, lo)| Coord::new(nano(lon_off, *lo) as f64 * 1e-9, nano(lat_off, *la) as f64 * 1e-9)) .collect() }); + let t = tags(osm, &strings, &k, &vv)?; osm.refs += refs.len(); - osm.ways.push((id, refs, tags(&strings, &k, &vv), places)); + osm.ways.push((id, refs, t, places)); } // A relation. 4 => { @@ -435,7 +477,7 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { previous }) .collect(); - let t = tags(&strings, &k, &vv); + let t = tags(osm, &strings, &k, &vv)?; // Only the relations drawn are kept, so only they meet the cap: one of // another type is left out either way. let drawn = matches!(tag(&t, "type"), Some("multipolygon" | "boundary")); @@ -454,15 +496,12 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { // left out by it. let omitted = types.iter().skip(MAX_MEMBERS).filter(|ty| **ty != 0).count() as u64; osm.omitted_members = osm.omitted_members.saturating_add(omitted); - let members = mems - .into_iter() - .zip(types) - .zip(roles) - .take(MAX_MEMBERS) - .map(|((m, ty), role)| { - (ty, m, usize::try_from(role).ok().and_then(|r| strings.get(r)).cloned().unwrap_or_default()) - }) - .collect(); + let mut members = Vec::new(); + for ((m, ty), role) in mems.into_iter().zip(types).zip(roles).take(MAX_MEMBERS) { + let role = usize::try_from(role).ok().and_then(|r| strings.get(r)).map(String::as_str).unwrap_or(""); + osm.charge_text(role.len())?; + members.push((ty, m, role.to_string())); + } osm.relations.push((id, members, t)); } } @@ -475,7 +514,11 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { /// Reads the file's blocks. fn blocks(bytes: &[u8]) -> Result { - let mut osm = Osm::default(); + blocks_with_text_limit(bytes, MAX_TEXT_BYTES) +} + +fn blocks_with_text_limit(bytes: &[u8], text_limit: usize) -> Result { + let mut osm = Osm::with_text_limit(text_limit); let mut i = 0usize; let mut saw_header = false; while i < bytes.len() { @@ -1474,4 +1517,62 @@ pub(crate) mod tests { let _g = crate::progress::install(Some(probe)); assert!(matches!(read("a.osm.pbf", &sample()), Err(DataError::Cancelled))); } + + #[test] + fn string_table_amplification_is_capped() { + let mut out = Vec::new(); + let mut header = Vec::new(); + field_bytes(4, b"OsmSchema-V0.6", &mut header); + field_bytes(4, b"DenseNodes", &mut header); + blob("OSMHeader", &header, false, &mut out); + + let big = "x".repeat(512); + let mut st = Vec::new(); + for s in ["", "name", big.as_str(), "type", "multipolygon"] { + field_bytes(1, s.as_bytes(), &mut st); + } + // Ten dense nodes all referencing the same 512-byte string entry (> 5 KiB decoded). + let ids: Vec = (1..=10).collect(); + let coords = vec![0i64; 10]; + let mut kv = Vec::new(); + for _ in 0..10 { + kv.extend([1u64, 2, 0]); + } + let mut dense = Vec::new(); + field_bytes(1, &delta(&ids), &mut dense); + field_bytes(8, &delta(&coords), &mut dense); + field_bytes(9, &delta(&coords), &mut dense); + field_bytes(10, &packed_of(&kv), &mut dense); + + let mut pg = Vec::new(); + field_bytes(2, &dense, &mut pg); + let mut prim = Vec::new(); + field_bytes(1, &st, &mut prim); + field_bytes(2, &pg, &mut prim); + blob("OSMData", &prim, true, &mut out); + + let err = blocks_with_text_limit(&out, 1024).err().expect("must fail when text exceeds limit"); + assert!(matches!(err, DataError::Format(ref m) if m.contains("limit")), "{err}"); + assert!(blocks_with_text_limit(&out, 64 * 1024).is_ok()); + + // Relation member roles referencing a repeated large string are budgeted too. + let mut rel_out = Vec::new(); + blob("OSMHeader", &header, false, &mut rel_out); + let mut rel = Vec::new(); + field_varint(1, 500, &mut rel); + field_bytes(2, &packed_of(&[3]), &mut rel); + field_bytes(3, &packed_of(&[4]), &mut rel); + field_bytes(8, &packed_of(&[2; 10]), &mut rel); + field_bytes(9, &delta(&ids), &mut rel); + field_bytes(10, &packed_of(&[1; 10]), &mut rel); + let mut rel_pg = Vec::new(); + field_bytes(4, &rel, &mut rel_pg); + let mut rel_prim = Vec::new(); + field_bytes(1, &st, &mut rel_prim); + field_bytes(2, &rel_pg, &mut rel_prim); + blob("OSMData", &rel_prim, true, &mut rel_out); + + assert!(matches!(blocks_with_text_limit(&rel_out, 1024), Err(DataError::Format(_)))); + assert!(blocks_with_text_limit(&rel_out, 64 * 1024).is_ok()); + } } diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 98b9e9e2ad..a83c3775d4 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -2132,10 +2132,19 @@ impl<'a> Eval<'a> { let mut best: Option<(f64, Cow<'a, Value>)> = None; for a in args { let v = read(a); - let Some(x) = v.as_f64() else { continue }; + let Some(x) = number(&v) else { continue }; let better = match &best { None => true, - Some((b, _)) => (f == Func::Min && x < *b) || (f == Func::Max && x > *b), + Some((b, bv)) => { + let ord = match (&*v, &**bv) { + (Value::Int(i), Value::Int(j)) => i.cmp(j), + (Value::Int(_), _) | (_, Value::Int(_)) => { + v.partial_cmp(bv).unwrap_or_else(|| x.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) + } + _ => x.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal), + }; + (f == Func::Min && ord.is_lt()) || (f == Func::Max && ord.is_gt()) + } }; if better { best = Some((x, v)); diff --git a/crates/data/src/query/tests.rs b/crates/data/src/query/tests.rs index 58e005836a..3ff05128e1 100644 --- a/crates/data/src/query/tests.rs +++ b/crates/data/src/query/tests.rs @@ -906,3 +906,38 @@ fn errors_say_why_they_are_null() { } assert_eq!(why("sqrt(0)", 0), (Value::Float(0.0), None)); } + +#[test] +fn min_and_max_report_non_number_faults_and_keep_i64_precision() { + let mut odd = Dataset::new( + "odd", + GeometryType::None, + vec![ + Field::new("x", FieldType::Double), + Field::new("label", FieldType::Text), + Field::new("n", FieldType::Integer), + Field::new("a", FieldType::Integer), + Field::new("b", FieldType::Integer), + ], + ); + odd.push( + None, + vec![ + Value::Float(f64::NAN), + Value::Text("abc".into()), + Value::Null, + Value::Int(9_007_199_254_740_992), + Value::Int(9_007_199_254_740_993), + ], + ); + let run = |text: &str| { + let e = parse(text, &odd).unwrap_or_else(|e| panic!("{text}: {e}")); + value_or_fault(&e, &odd, 0, &Env::default()) + }; + assert_eq!(run("min(label, n)"), (Value::Null, Some(Fault::Text))); + assert_eq!(run("max(x, n)"), (Value::Null, Some(Fault::NotANumber))); + assert_eq!(run("min(n, 5)"), (Value::Int(5), None)); + assert_eq!(run("max(a, b)"), (Value::Int(9_007_199_254_740_993), None)); + assert_eq!(run("min(b, a)"), (Value::Int(9_007_199_254_740_992), None)); + assert_eq!(run("min('2', '10')"), (Value::Text("2".into()), None)); +} diff --git a/crates/data/src/raster/grib/complex.rs b/crates/data/src/raster/grib/complex.rs index 318e8a0cb7..8a063384ff 100644 --- a/crates/data/src/raster/grib/complex.rs +++ b/crates/data/src/raster/grib/complex.rs @@ -195,12 +195,15 @@ impl Values<'_> { let packed = bits(self.data, self.at, self.width); self.at += u64::from(self.width); // Missing: every bit set (one less, the secondary missing value) in the value, or in the - // reference of a group of no bits. + // reference of a group of no bits. When both widths are 0 there are no bits to carry a + // missing sentinel, so the group is a constant value. 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..1ada68f886 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -1429,6 +1429,17 @@ fn complex_packing_marks_missing_values() { assert!(r.rounded.is_empty() && r.lost.len() == 1, "{:?}", r.lost); } +#[test] +fn complex_packing_zero_bit_constant_group_with_missing_management() { + for missing in [1, 2] { + let mut c = Cx::new(&[(0, 0, &[0, 0, 0])]); + c.ref_bits = 0; + c.r = 12.5; + c.missing = missing; + assert_eq!(c.values(), vec![12.5, 12.5, 12.5], "missing={missing}"); + } +} + #[test] fn spatial_differencing_is_undone() { // 100, 103, 101, 101, 90: differences 3, −2, 0, −11, the least −11. diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 495010e739..b9f2d2c6ea 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -495,6 +495,24 @@ fn damaged(what: &str) -> Result { Err(DataError::Format(format!("spreadsheet: the .xls file is damaged ({what})"))) } +/// Grows `bounds` (`r0, r1, c0, c1`) to include `(r, c)` and refuses spans past [`MAX_CELLS`]. +fn grow_sheet_bounds(bounds: &mut Option<(u32, u32, u32, u32)>, (r, c): (u32, u32), sheet: &str) -> Result<()> { + let (r0, r1, c0, c1) = bounds.map_or((r, r, c, c), |(r0, r1, c0, c1)| (r0.min(r), r1.max(r), c0.min(c), c1.max(c))); + *bounds = Some((r0, r1, c0, c1)); + let rows = u64::from(r1 - r0) + 1; + let cols = u64::from(c1 - c0) + 1; + if rows.saturating_mul(cols) > MAX_CELLS as u64 { + return Err(DataError::Format(format!( + "sheet '{sheet}' is too large (cells from row {} to {}, column {} to {})", + u64::from(r0) + 1, + u64::from(r1) + 1, + column_letter(c0 as usize), + column_letter(c1 as usize) + ))); + } + Ok(()) +} + /// Refuses a sheet whose cells span more than [`MAX_CELLS`] before calamine lays it out as a dense /// grid (one cell at `XFD1048576` would ask for 17 billion): an `.xlsx` or `.xlsb` sheet's cells /// are read one at a time for their extent first. Every `.xls` sheet's BIFF records and cell @@ -502,33 +520,18 @@ fn damaged(what: &str) -> Result { /// extents are checked by [`check_expansion`] before its eagerly loaded sheets are allocated. fn check_size(wb: &mut Sheets>, sheet: &str) -> Result<()> { let mut b: Option<(u32, u32, u32, u32)> = None; - let mut grow = |(r, c): (u32, u32)| -> Result<()> { - let (r0, r1, c0, c1) = b.map_or((r, r, c, c), |(r0, r1, c0, c1)| (r0.min(r), r1.max(r), c0.min(c), c1.max(c))); - b = Some((r0, r1, c0, c1)); - let cells = ((r1 - r0) as usize + 1).saturating_mul((c1 - c0) as usize + 1); - if cells > MAX_CELLS { - return Err(DataError::Format(format!( - "sheet '{sheet}' is too large (cells from row {} to {}, column {} to {})", - r0 + 1, - r1 + 1, - column_letter(c0 as usize), - column_letter(c1 as usize) - ))); - } - Ok(()) - }; let bad = |e: String| DataError::Format(format!("sheet '{sheet}': {e}")); match wb { Sheets::Xlsx(x) => { let mut cells = x.worksheet_cells_reader(sheet).map_err(|e| bad(e.to_string()))?; while let Some(c) = cells.next_cell().map_err(|e| bad(e.to_string()))? { - grow(c.get_position())?; + grow_sheet_bounds(&mut b, c.get_position(), sheet)?; } } Sheets::Xlsb(x) => { let mut cells = x.worksheet_cells_reader(sheet).map_err(|e| bad(e.to_string()))?; while let Some(c) = cells.next_cell().map_err(|e| bad(e.to_string()))? { - grow(c.get_position())?; + grow_sheet_bounds(&mut b, c.get_position(), sheet)?; } } Sheets::Xls(_) | Sheets::Ods(_) => {} @@ -1591,4 +1594,16 @@ mod tests { let names: Vec<&str> = ds.fields.iter().map(|f| f.name.as_str()).collect(); assert_eq!(names, ["name", "D"]); } + + #[test] + fn sheet_bounds_never_overflow_u32_max() { + let mut bounds = None; + grow_sheet_bounds(&mut bounds, (0, 0), "S").unwrap(); + let err = grow_sheet_bounds(&mut bounds, (u32::MAX, 0), "S").unwrap_err().to_string(); + assert!(err.contains("row 1 to 4294967296"), "{err}"); + + let mut col_bounds = None; + grow_sheet_bounds(&mut col_bounds, (0, 0), "S").unwrap(); + assert!(grow_sheet_bounds(&mut col_bounds, (0, u32::MAX), "S").is_err()); + } } diff --git a/crates/data/src/sqlite.rs b/crates/data/src/sqlite.rs index 7fd2368f4e..9b454d7da2 100644 --- a/crates/data/src/sqlite.rs +++ b/crates/data/src/sqlite.rs @@ -586,36 +586,71 @@ fn column_list(sql: &str) -> Option<(usize, usize)> { None } -/// Splits on commas outside parentheses and quotes. +/// Splits on commas outside parentheses, quotes and SQL comments. fn split_top(s: &str) -> Vec { + let cs: Vec = s.chars().collect(); let mut out = Vec::new(); let mut cur = String::new(); let mut depth = 0usize; let mut quote: Option = None; - for c in s.chars() { + let mut i = 0; + while let Some(&c) = cs.get(i) { match quote { Some(q) => { cur.push(c); - if c == q || (q == '[' && c == ']') { + let close = if q == '[' { ']' } else { q }; + if c == close { + if close != ']' && cs.get(i + 1) == Some(&close) { + cur.push(close); + i += 2; + continue; + } quote = None; } + i += 1; } - None => match c { - '"' | '\'' | '`' | '[' => { - quote = Some(c); - cur.push(c); - } - '(' => { - depth += 1; - cur.push(c); - } - ')' => { - depth = depth.saturating_sub(1); + None => { + if c == '-' && cs.get(i + 1) == Some(&'-') { + while let Some(&d) = cs.get(i) { + cur.push(d); + i += 1; + if d == '\n' { + break; + } + } + } else if c == '/' && cs.get(i + 1) == Some(&'*') { cur.push(c); + cur.push('*'); + i += 2; + while let Some(&d) = cs.get(i) { + cur.push(d); + i += 1; + if d == '*' && cs.get(i) == Some(&'/') { + cur.push('/'); + i += 1; + break; + } + } + } else { + match c { + '"' | '\'' | '`' | '[' => { + quote = Some(c); + cur.push(c); + } + '(' => { + depth += 1; + cur.push(c); + } + ')' => { + depth = depth.saturating_sub(1); + cur.push(c); + } + ',' if depth == 0 => out.push(std::mem::take(&mut cur)), + c => cur.push(c), + } + i += 1; } - ',' if depth == 0 => out.push(std::mem::take(&mut cur)), - c => cur.push(c), - }, + } } } if !cur.trim().is_empty() { @@ -729,6 +764,21 @@ mod tests { assert_eq!(p.stored_order.as_deref(), Some(&[1, 2, 3, 0][..])); } + #[test] + fn create_table_with_comments_containing_commas_parens_and_quotes() { + let sql = "CREATE TABLE t ( + a INTEGER, -- don't, split (here) + /* block, comment with 'apostrophe and (paren */ + b TEXT DEFAULT 'don''t, split', + c REAL /* trailing, (comment) */ + )"; + let (cols, _) = parse_create_table(sql).unwrap(); + let names: Vec<&str> = cols.iter().map(|c| c.name.as_str()).collect(); + let decls: Vec<&str> = cols.iter().map(|c| c.decl.as_str()).collect(); + assert_eq!(names, ["a", "b", "c"]); + assert_eq!(decls, ["INTEGER", "TEXT", "REAL"]); + } + #[test] fn varints_and_records() { assert_eq!(varint(&[0x7f], 0), Some((127, 1))); diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index 0eab06da51..55a640a69f 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -1559,6 +1559,11 @@ fn decode_with( /// a fragment, so it never reaches the server, which gets a `Range` header instead. pub const RANGE: &str = "#rustgis-range="; +/// Length of an inclusive byte range `a..=b`, or `None` when `a > b` or `b - a + 1` overflows `u64`. +pub fn range_len(a: u64, b: u64) -> Option { + b.checked_sub(a)?.checked_add(1) +} + /// Splits an address into the address to fetch and the byte range it asks for, if any. pub fn split_range(url: &str) -> (&str, Option<(u64, u64)>) { match url.rsplit_once(RANGE) { @@ -3648,7 +3653,8 @@ 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) + let len = super::range_len(a, b).ok_or("a local read with an overflowing range")?; + return crate::pmtiles::read_file(path, a, len) .map(|bytes| Fetched { bytes, origin: Origin::named(url) }) .map_err(Failure::from); } @@ -3656,6 +3662,11 @@ mod native { let max = limit.unwrap_or(MAX_BYTES); let (url, mut tail) = super::split_tail(url); let (url, mut range) = super::split_range(url); + if let Some((a, b)) = range + && super::range_len(a, b).is_none() + { + return Err("byte range length overflows".into()); + } // The last bytes asked for, while the file's length is asked for instead (see below). let mut measuring: Option = None; // Explicit service logins outrank implicit S3 endpoint signing. @@ -3856,10 +3867,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 len = super::range_len(a, b).ok_or("byte range length overflows")?; + if buf.len() as u64 > len { 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(len).unwrap_or(usize::MAX)); } Ok(Fetched { bytes: buf, origin }) })(); @@ -8033,4 +8045,20 @@ Connection: close assert_eq!(ceiling_for(&tile), crate::address::Reach::Public); assert!(matches!(get_tile(&tile, Want::Image), State::Failed(_))); } + + #[test] + fn byte_range_overflow_is_rejected() { + assert_eq!(range_len(5, 5), Some(1)); + assert_eq!(range_len(10, 5), None); + assert_eq!(range_len(0, u64::MAX), None); + #[cfg(not(target_arch = "wasm32"))] + { + let _turn = turn(); + let (tx, rx) = std::sync::mpsc::channel(); + let url = format!("https://example.invalid/data.bin{RANGE}0-{}", u64::MAX); + native::fetch_reached(url, crate::address::Reach::Public, Box::new(move |r| tx.send(r).unwrap()), &[]); + let err = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap().unwrap_err(); + assert!(err.contains("overflows"), "{err}"); + } + } } diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index 98e788d9ca..55aaf5cbc0 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -547,7 +547,10 @@ fn read(url: &str, at: u64, len: u64, ceiling: crate::address::Reach, done: Done done(Err(format!("{len} bytes is too large to read from a GeoTIFF"))); return; } - let end = at.saturating_add(len) - 1; + let Some(end) = at.checked_add(len).and_then(|e| e.checked_sub(1)) else { + done(Err("byte range overflows GeoTIFF offset".into())); + return; + }; if is_local_file(url) { if let Err(e) = local_read_allowed(url, ceiling) { done(Err(e)); @@ -2786,4 +2789,14 @@ mod tests { forget_local_file(&url); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn overflowing_byte_range_returns_error() { + let _turn = crate::cache::turn(); + crate::cache::set_fetcher(|url, _done| panic!("unexpected fetch for overflowing range: {url}")); + let (tx, rx) = std::sync::mpsc::channel(); + read("https://example.invalid/a.tif", u64::MAX, 16, crate::address::Reach::Public, Box::new(move |r| tx.send(r).unwrap())); + let err = rx.recv_timeout(Duration::from_secs(5)).unwrap().unwrap_err(); + assert!(err.contains("overflows"), "{err}"); + } } diff --git a/crates/tiles/src/pmtiles.rs b/crates/tiles/src/pmtiles.rs index f058827d3e..19c5097050 100644 --- a/crates/tiles/src/pmtiles.rs +++ b/crates/tiles/src/pmtiles.rs @@ -679,7 +679,7 @@ fn find(archive: String, info: Arc, id: u64, dir: Arc>, depth: if e.run_length > 0 { let tile = info.tile; // Within the tile data section (when the header gives its length). - let inside = info.data_length == 0 || e.offset.saturating_add(e.length) <= info.data_length; + let inside = info.data_length == 0 || e.offset.checked_add(e.length).is_some_and(|end| end <= info.data_length); let Some(at) = info.data_offset.checked_add(e.offset).filter(|_| inside) else { done(Err("a tile outside the archive".into())); return; @@ -692,11 +692,11 @@ fn find(archive: String, info: Arc, id: u64, dir: Arc>, depth: done(Err("PMTiles directories nested too deep".into())); return; } - if e.offset.saturating_add(e.length) > info.leaf_length { + let inside = e.offset.checked_add(e.length).is_some_and(|end| end <= info.leaf_length); + let Some(at) = info.leaf_offset.checked_add(e.offset).filter(|_| inside) else { done(Err("a leaf directory outside the archive".into())); return; - } - let at = info.leaf_offset.saturating_add(e.offset); + }; let key = (archive.clone(), at); // Continues the lookup once the leaf is there. let next: Box>, String>) + Send> = { @@ -804,7 +804,10 @@ fn read(archive: &str, at: u64, len: u64, done: Done) { done(Err(format!("{len} bytes is too large to read from an archive"))); return; } - let end = at.saturating_add(len) - 1; + let Some(end) = at.checked_add(len).and_then(|e| e.checked_sub(1)) else { + done(Err("byte range overflows archive offset".into())); + return; + }; let url = format!("{archive}{}{at}-{end}", crate::cache::RANGE); if is_local(archive) { if let Err(e) = check_local(archive) { @@ -2076,4 +2079,14 @@ pub(crate) mod tests { } let _ = std::fs::remove_dir_all(dir); } + + #[test] + fn overflowing_byte_range_returns_error() { + let _turn = crate::cache::turn(); + crate::cache::set_fetcher(|url, _done| panic!("unexpected fetch for overflowing range: {url}")); + let (tx, rx) = std::sync::mpsc::channel(); + read("https://example.invalid/a.pmtiles", u64::MAX, 16, Box::new(move |r| tx.send(r).unwrap())); + let err = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap().unwrap_err(); + assert!(err.contains("overflows"), "{err}"); + } } diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index b4dd88b69e..6127029b34 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -905,39 +905,67 @@ pub fn resolve(base: &str, href: &str) -> Option { Some(crate::logins::inherit(base, &resolved)) } +/// Whether `s` begins with an RFC 3986 scheme followed by `://`. +fn has_scheme(s: &str) -> bool { + let Some((scheme, _)) = s.split_once("://") else { return false }; + let mut bytes = scheme.bytes(); + bytes.next().is_some_and(|b| b.is_ascii_alphabetic()) && bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.')) +} + fn resolve_plain(base: &str, href: &str) -> Option { let href = href.trim(); if href.is_empty() || href.len() > MAX_TEXT || href.chars().any(char::is_control) { return None; } - if href.contains("://") { + if has_scheme(href) { return Some(href.to_string()); } let (scheme, rest) = base.split_once("://")?; - let host_end = rest.find('/').unwrap_or(rest.len()); + let host_end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); let origin = format!("{scheme}://{}", rest.get(..host_end)?); if let Some(abs) = href.strip_prefix("//") { return Some(format!("{scheme}://{abs}")); } + let (href_path, tail) = match href.find(['?', '#']) { + Some(i) => (href.get(..i)?, href.get(i..)?), + None => (href, ""), + }; + let normalize = |raw: &str| { + let mut out: Vec<&str> = Vec::new(); + let segments: Vec<&str> = raw.split('/').collect(); + let last = segments.len().saturating_sub(1); + for (i, seg) in segments.iter().enumerate() { + match *seg { + "." => {} + ".." => { + if out.len() > 1 { + out.pop(); + } + } + s => out.push(s), + } + if i == last && matches!(*seg, "." | "..") { + out.push(""); + } + } + out.join("/") + }; if href.starts_with('/') { - return Some(format!("{origin}{href}")); + return Some(format!("{origin}{}{tail}", normalize(href_path))); } - // Relative to the base's folder, with `./` and `../` worked out. let path = rest.get(host_end..).unwrap_or("").split(['?', '#']).next().unwrap_or(""); - let mut parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect(); - if !path.ends_with('/') { - parts.pop(); - } - for seg in href.split('/') { - match seg { - "." => {} - ".." => { - parts.pop(); - } - s => parts.push(s), - } + if href_path.is_empty() { + // RFC 3986 section 5.2.2: an empty reference path keeps the document path, and keeps its + // query only when the reference supplies none. A base fragment is never inherited. + let query = if href.starts_with('?') { + "" + } else { + rest.split('#').next().and_then(|r| r.find('?').and_then(|i| r.get(i..))).unwrap_or("") + }; + return Some(format!("{origin}{path}{query}{tail}")); } - Some(format!("{origin}/{}", parts.join("/"))) + let dir = path.rfind('/').map_or("/", |i| path.get(..=i).unwrap_or("/")); + Some(format!("{origin}{}{tail}", normalize(&format!("{dir}{href_path}")))) } impl Asset { @@ -1647,6 +1675,19 @@ mod tests { assert_eq!(resolve("https://x.org/a", "//y.org/d.tif").as_deref(), Some("https://y.org/d.tif")); assert_eq!(resolve("https://x.org/a", "s3://b/k").as_deref(), Some("s3://b/k")); assert_eq!(resolve("https://x.org/a", ""), None); + // RFC 3986 query/fragment links, scheme detection, and authority boundary on `?` and `#`. + assert_eq!(resolve("https://api.example/v1/search", "?token=page2").as_deref(), Some("https://api.example/v1/search?token=page2")); + assert_eq!( + resolve("https://api.example/v1/search?limit=10", "?next=https://other.example/x").as_deref(), + Some("https://api.example/v1/search?next=https://other.example/x") + ); + assert_eq!( + resolve("https://api.example/v1/search?limit=10#old", "#new").as_deref(), + Some("https://api.example/v1/search?limit=10#new") + ); + assert_eq!(resolve("https://stac.example?f=json", "/items/1").as_deref(), Some("https://stac.example/items/1")); + assert_eq!(resolve("https://stac.example?f=json", "items/1").as_deref(), Some("https://stac.example/items/1")); + assert_eq!(resolve("https://x.org/a/b", "rel/https://not-a-scheme").as_deref(), Some("https://x.org/a/rel/https://not-a-scheme")); } /// JAXA Earth's codes for a failed retrieval: read whole, or the asset says they weren't. From 09feddf171efbd364c76d9000dcb5bc3566c1451 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:14:37 -0500 Subject: [PATCH 02/14] Address review feedback - WKT CSV export: reuse io::csv_cell for attributes so only Value::Text cells receive formula guarding (preserving 16-digit negative integers and header field names like +0123 across round trips), and match this in the export loss path. - LandXML: update both single-surface and multi-surface face-cap notices to state that the file-wide face limit was reached, and assert both wordings in tests. - OSM PBF: cap retained tagged entities and drawn relations via osm.capped (reporting through the existing DroppedOverLimit notice) rather than aborting the read, and charge text only for entities that are kept. - Web range fetches: reject overflowing inclusive byte ranges via cache::range_len in apps/rustgis-web/src/web.rs before sending a Range header. - FileGDB: check duplicate row offsets in place by sorting out by offset, checking adjacent pairs, and sorting back by row, avoiding an auxiliary HashSet allocation. --- apps/rustgis-web/src/web.rs | 5 + crates/data/src/filegdb.rs | 10 +- crates/data/src/interop.rs | 29 +++--- crates/data/src/io.rs | 7 +- crates/data/src/landxml.rs | 32 ++++++- crates/data/src/osm.rs | 179 ++++++++++++++++++++++++++++-------- 6 files changed, 201 insertions(+), 61 deletions(-) diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index e0c7628e58..4aaee35888 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -749,6 +749,11 @@ async fn fetch_reached( let max = limit.map(|n| n as u64).unwrap_or(64 << 20); let (url, tail) = cache::split_tail(url); let (url, range) = cache::split_range(url); + if let Some((a, b)) = range + && cache::range_len(a, b).is_none() + { + return Err("byte range length overflows".into()); + } // Share native GET routing: explicit service logins outrank implicit S3 endpoint signing. let bound = url; let prepared = cache::prepare_get(url)?; diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index 7380928652..757b2e9b24 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -937,7 +937,6 @@ fn row_offsets(x: &[u8]) -> Result> { Some(bits) => total.div_ceil(1024).min(bits.len().saturating_mul(8)), }; let mut out = Vec::new(); - let mut seen = std::collections::HashSet::new(); let mut stored_before = 0usize; for block in 0..in_blocks { let present = bitmap.is_none_or(|bits| bits.get(block / 8).is_some_and(|b| b >> (block % 8) & 1 == 1)); @@ -961,13 +960,16 @@ fn row_offsets(x: &[u8]) -> Result> { continue; } if let Ok(offset) = usize::try_from(offset) { - if !seen.insert(offset) { - return Err(bad("duplicate row offset")); - } out.push((row as u64 + 1, offset)); } } } + // Check for duplicate offsets in place without allocating an auxiliary hash set. + out.sort_unstable_by_key(|&(_, offset)| offset); + if out.windows(2).any(|w| matches!(w, [(_, a), (_, b)] if a == b)) { + return Err(bad("duplicate row offset")); + } + out.sort_unstable_by_key(|&(row, _)| row); Ok(out) } diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index f0b3bfc2aa..ce214c19c5 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -520,17 +520,10 @@ impl WktParser { } } -/// A [`to_wkt_csv`] cell's text before quoting: text starting like a formula is prefixed with `'` -/// so spreadsheets show it rather than run it. -pub(crate) fn wkt_csv_text(s: &str) -> String { - if crate::io::csv_needs_guard(s) { format!("'{s}") } else { s.to_string() } -} - /// CSV with a `wkt` geometry column and every attribute; cancellable between features. pub fn to_wkt_csv(ds: &Dataset) -> crate::Result { let q = |s: &str| { - let s = wkt_csv_text(s); - if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s } + if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() } }; let mut out = String::from("wkt"); for f in &ds.fields { @@ -543,7 +536,7 @@ pub fn to_wkt_csv(ds: &Dataset) -> crate::Result { out.push_str(&q(&f.geometry.as_ref().map(wkt).unwrap_or_default())); for v in &f.attrs { out.push(','); - out.push_str(&q(&v.to_file_text())); + out.push_str(&q(&crate::io::csv_cell(v))); } out.push('\n'); } @@ -613,10 +606,24 @@ mod tests { #[test] fn wkt_csv_formula_guard_matches_csv() { for guarded in ["=SUM(A1)", "@cmd", "\t=1", "\r+1", "+Inf", "-NaN", "+0123", "-007", "+1234567890123456", "-1234567890123456"] { - assert_eq!(wkt_csv_text(guarded), format!("'{guarded}"), "{guarded:?}"); + assert_eq!(crate::io::csv_cell(&Value::Text(guarded.into())), format!("'{guarded}"), "{guarded:?}"); } for plain in ["-12.5", "+42", "-0.5", "Paris"] { - assert_eq!(wkt_csv_text(plain), plain, "{plain:?}"); + assert_eq!(crate::io::csv_cell(&Value::Text(plain.into())), plain, "{plain:?}"); } + // Round-trip: field names like `+0123` stay unchanged, 16-digit negative integers stay + // Integer, and formula-like text values are guarded in the CSV output. + let mut ds = + Dataset::new("rt", GeometryType::Point, vec![Field::new("+0123", FieldType::Text), Field::new("big_id", FieldType::Integer)]); + ds.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Text("\t=1".into()), Value::Int(-1_234_567_890_123_456)]); + let csv = to_wkt_csv(&ds).unwrap(); + assert!(csv.starts_with("wkt,+0123,big_id\n"), "header must stay unguarded: {csv}"); + assert!(csv.contains("'\t=1,-1234567890123456\n"), "text guarded, integer unguarded: {csv}"); + let (back, _) = crate::io::read_csv(&csv, "rt").unwrap(); + let names: Vec<&str> = back.fields.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["+0123", "big_id"]); + assert_eq!(back.fields[1].ty, FieldType::Integer); + assert_eq!(back.features[0].attrs[0], Value::Text("\t=1".into())); + assert_eq!(back.features[0].attrs[1], Value::Int(-1_234_567_890_123_456)); } } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index da6b9757c7..637dd814cf 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3269,7 +3269,7 @@ const FORMULA_START: [char; 6] = ['=', '+', '-', '@', '\t', '\r']; /// Text needs an apostrophe if it starts like a spreadsheet formula. The numeric exception /// keeps finite numbers that fit Double precision and have at most 15 significant digits. /// A leading-zero code stays guarded unless its mantissa has digits after a decimal point. -pub(crate) fn csv_needs_guard(text: &str) -> bool { +fn csv_needs_guard(text: &str) -> bool { if !text.starts_with(FORMULA_START) { return false; } @@ -3282,7 +3282,7 @@ pub(crate) fn csv_needs_guard(text: &str) -> bool { } /// A cell's file text, with an apostrophe when the spreadsheet guard applies. -fn csv_cell(v: &Value) -> String { +pub(crate) fn csv_cell(v: &Value) -> String { match v { Value::Text(t) if csv_needs_guard(t) => format!("'{t}"), other => other.to_file_text(), @@ -5149,8 +5149,7 @@ impl TextLosses { && !column.is_text() { let text = match ext { - "csv" => csv_cell(v), - "wkt" => crate::interop::wkt_csv_text(&v.to_file_text()), + "csv" | "wkt" => csv_cell(v), _ => v.to_file_text(), }; // CSV's `` reads as null, so it types a column no more than an empty cell. diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index 19e8dea014..fe97bdac12 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -266,7 +266,7 @@ fn read_with_max_faces(file_name: &str, bytes: &[u8], crs: Option, max_face [] => {} [one] => report.messages.push(crate::loss::Note::loss( crate::loss::LossCode::DroppedOverLimit, - format!("surface '{one}' has more than {max_faces} faces: the {faces_left_out} past the limit are left out"), + format!("the file has more than {max_faces} faces: the {faces_left_out} past the limit are left out, from surface '{one}' on"), )), many => { let shown: Vec = many.iter().take(10).map(|n| format!("'{n}'")).collect(); @@ -274,7 +274,7 @@ fn read_with_max_faces(file_name: &str, bytes: &[u8], crs: Option, max_face report.messages.push(crate::loss::Note::loss( crate::loss::LossCode::DroppedOverLimit, format!( - "{} surfaces ({}{more}) have more than {max_faces} faces: the {faces_left_out} past the limit are left out", + "the file has more than {max_faces} faces: the {faces_left_out} past the limit are left out, across {} surfaces ({}{more})", many.len(), shown.join(", ") ), @@ -521,9 +521,31 @@ mod tests { "#; let layers = read_with_max_faces("two.xml", two_surfaces.as_bytes(), None, 4).unwrap(); assert_eq!(layers[0].0.features.len(), 4, "file-wide face cap must bound sibling surfaces"); - assert!( - layers[0].1.messages.iter().any(|m| m.loss == Some(crate::loss::LossCode::DroppedOverLimit) && m.contains("2 past the limit")) - ); + assert!(layers[0].1.messages.iter().any(|m| { + m.loss == Some(crate::loss::LossCode::DroppedOverLimit) + && m.as_str() == "the file has more than 4 faces: the 2 past the limit are left out, from surface 'b' on" + })); + + let three_surfaces = r#" + +

0 0 1

0 1 1

1 0 1

+ 1 2 31 2 31 2 3 +
+ +

0 0 2

0 1 2

1 0 2

+ 1 2 31 2 3 +
+ +

0 0 3

0 1 3

1 0 3

+ 1 2 31 2 3 +
+
"#; + let layers = read_with_max_faces("three.xml", three_surfaces.as_bytes(), None, 4).unwrap(); + assert_eq!(layers[0].0.features.len(), 4); + assert!(layers[0].1.messages.iter().any(|m| { + m.loss == Some(crate::loss::LossCode::DroppedOverLimit) + && m.as_str() == "the file has more than 4 faces: the 3 past the limit are left out, across 2 surfaces ('b', 'c')" + })); } #[test] diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 5328fbbb20..c31e6fe457 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -259,8 +259,10 @@ fn ignored(key: &str) -> bool { || key.starts_with("openGeoDB:") } -fn tags(osm: &mut Osm, strings: &[String], keys: &[u64], vals: &[u64]) -> Result { - let mut out = Vec::new(); +/// Whether `keys`/`vals` hold any non-ignored tags and their combined UTF-8 byte length. +fn tags_info(strings: &[String], keys: &[u64], vals: &[u64]) -> (bool, usize) { + let mut any = false; + let mut bytes = 0usize; for (k, v) in keys.iter().zip(vals) { let (Some(k), Some(v)) = (usize::try_from(*k).ok().and_then(|i| strings.get(i)), usize::try_from(*v).ok().and_then(|i| strings.get(i))) @@ -270,10 +272,18 @@ fn tags(osm: &mut Osm, strings: &[String], keys: &[u64], vals: &[u64]) -> Result if ignored(k) { continue; } - osm.charge_text(k.len().saturating_add(v.len()))?; - out.push((k.clone(), v.clone())); + any = true; + bytes = bytes.saturating_add(k.len()).saturating_add(v.len()); } - Ok(out) + (any, bytes) +} + +fn tags(strings: &[String], keys: &[u64], vals: &[u64]) -> Tags { + keys.iter() + .zip(vals) + .filter_map(|(k, v)| Some((strings.get(usize::try_from(*k).ok()?)?.clone(), strings.get(usize::try_from(*v).ok()?)?.clone()))) + .filter(|(k, _)| !ignored(k)) + .collect() } fn tag<'t>(t: &'t [(String, String)], k: &str) -> Option<&'t str> { @@ -312,13 +322,15 @@ impl Osm { } } - fn charge_text(&mut self, bytes: usize) -> Result<()> { + /// Reserves `bytes` from the retained tag/role text budget, or marks the extract capped. + fn try_charge_text(&mut self, bytes: usize) -> bool { let next = self.text_bytes.saturating_add(bytes); if next > self.text_limit { - return Err(DataError::Format(format!("OSM PBF decoded text exceeds the limit of {} bytes", self.text_limit))); + self.capped = true; + return false; } self.text_bytes = next; - Ok(()) + true } } @@ -385,7 +397,15 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { _ => {} } } - let t = tags(osm, &strings, &k, &vv)?; + let (has_tags, cost) = tags_info(&strings, &k, &vv); + let t = if !has_tags { + Vec::new() + } else if osm.points.len() >= MAX_NODES || !osm.try_charge_text(cost) { + osm.capped = true; + Vec::new() + } else { + tags(&strings, &k, &vv) + }; keep(osm, id, lat, lon, t); } // Dense nodes. @@ -401,23 +421,51 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { _ => {} } } - let mut kvi = kv.into_iter(); + let mut pos = 0usize; + let at = |i: u64| usize::try_from(i).ok().and_then(|i| strings.get(i)); for ((id, lat), lon) in ids.into_iter().zip(lats).zip(lons) { - let mut t = Vec::new(); - // Key, value pairs up to a 0. - while let Some(k) = kvi.next() { + let start = pos; + let mut has_tags = false; + let mut cost = 0usize; + // Key, value pairs up to a 0; measure cost before cloning any strings. + while let Some(&k) = kv.get(pos) { + pos += 1; if k == 0 { break; } - let Some(v) = kvi.next() else { break }; - let at = |i: u64| usize::try_from(i).ok().and_then(|i| strings.get(i)); + let Some(&v) = kv.get(pos) else { break }; + pos += 1; if let (Some(k), Some(v)) = (at(k), at(v)) && !ignored(k) { - osm.charge_text(k.len().saturating_add(v.len()))?; - t.push((k.clone(), v.clone())); + has_tags = true; + cost = cost.saturating_add(k.len()).saturating_add(v.len()); } } + let t = if !has_tags { + Vec::new() + } else if osm.points.len() >= MAX_NODES || !osm.try_charge_text(cost) { + osm.capped = true; + Vec::new() + } else { + let mut t = Vec::new(); + let mut p = start; + while p < pos { + let Some(&k) = kv.get(p) else { break }; + p += 1; + if k == 0 { + break; + } + let Some(&v) = kv.get(p) else { break }; + p += 1; + if let (Some(k), Some(v)) = (at(k), at(v)) + && !ignored(k) + { + t.push((k.clone(), v.clone())); + } + } + t + }; keep(osm, id, lat, lon, t); } } @@ -442,13 +490,17 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { osm.capped = true; continue; } + let (has_tags, cost) = tags_info(&strings, &k, &vv); + if has_tags && !osm.try_charge_text(cost) { + continue; + } let places = (!lats.is_empty() && lats.len() == refs.len() && lons.len() == refs.len()).then(|| { lats.iter() .zip(&lons) .map(|(la, lo)| Coord::new(nano(lon_off, *lo) as f64 * 1e-9, nano(lat_off, *la) as f64 * 1e-9)) .collect() }); - let t = tags(osm, &strings, &k, &vv)?; + let t = if has_tags { tags(&strings, &k, &vv) } else { Vec::new() }; osm.refs += refs.len(); osm.ways.push((id, refs, t, places)); } @@ -477,10 +529,17 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { previous }) .collect(); - let t = tags(osm, &strings, &k, &vv)?; - // Only the relations drawn are kept, so only they meet the cap: one of - // another type is left out either way. - let drawn = matches!(tag(&t, "type"), Some("multipolygon" | "boundary")); + // Only the relations drawn are kept, so check before cloning or charging tags. + let drawn = k + .iter() + .zip(&vv) + .filter_map(|(ki, vi)| { + let k = usize::try_from(*ki).ok().and_then(|i| strings.get(i))?; + let v = usize::try_from(*vi).ok().and_then(|i| strings.get(i))?; + (!ignored(k)).then_some((k.as_str(), v.as_str())) + }) + .find(|(k, _)| *k == "type") + .is_some_and(|(_, v)| matches!(v, "multipolygon" | "boundary")); if drawn && osm.relations.len() >= MAX_RELATIONS { osm.capped = true; } else if drawn { @@ -492,17 +551,29 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { types.len() ))); } + let (_, tag_bytes) = tags_info(&strings, &k, &vv); + let role_bytes = roles + .iter() + .take(MAX_MEMBERS) + .map(|r| usize::try_from(*r).ok().and_then(|i| strings.get(i)).map_or(0, String::len)) + .fold(0usize, usize::saturating_add); + if !osm.try_charge_text(tag_bytes.saturating_add(role_bytes)) { + continue; + } // Node members are never read, so only the others past the limit are // left out by it. let omitted = types.iter().skip(MAX_MEMBERS).filter(|ty| **ty != 0).count() as u64; osm.omitted_members = osm.omitted_members.saturating_add(omitted); - let mut members = Vec::new(); - for ((m, ty), role) in mems.into_iter().zip(types).zip(roles).take(MAX_MEMBERS) { - let role = usize::try_from(role).ok().and_then(|r| strings.get(r)).map(String::as_str).unwrap_or(""); - osm.charge_text(role.len())?; - members.push((ty, m, role.to_string())); - } - osm.relations.push((id, members, t)); + let members = mems + .into_iter() + .zip(types) + .zip(roles) + .take(MAX_MEMBERS) + .map(|((m, ty), role)| { + (ty, m, usize::try_from(role).ok().and_then(|r| strings.get(r)).cloned().unwrap_or_default()) + }) + .collect(); + osm.relations.push((id, members, tags(&strings, &k, &vv))); } } _ => {} @@ -1528,7 +1599,7 @@ pub(crate) mod tests { let big = "x".repeat(512); let mut st = Vec::new(); - for s in ["", "name", big.as_str(), "type", "multipolygon"] { + for s in ["", "name", big.as_str(), "type", "multipolygon", "route"] { field_bytes(1, s.as_bytes(), &mut st); } // Ten dense nodes all referencing the same 512-byte string entry (> 5 KiB decoded). @@ -1551,11 +1622,39 @@ pub(crate) mod tests { field_bytes(2, &pg, &mut prim); blob("OSMData", &prim, true, &mut out); - let err = blocks_with_text_limit(&out, 1024).err().expect("must fail when text exceeds limit"); - assert!(matches!(err, DataError::Format(ref m) if m.contains("limit")), "{err}"); - assert!(blocks_with_text_limit(&out, 64 * 1024).is_ok()); - - // Relation member roles referencing a repeated large string are budgeted too. + // Under a 1024-byte budget, only the first 516-byte tagged node is kept and `capped` is set. + let capped = blocks_with_text_limit(&out, 1024).unwrap(); + assert!(capped.capped, "extract past text budget must be marked capped"); + assert_eq!(capped.points.len(), 1); + assert!(capped.text_bytes <= 1024); + + let full = blocks_with_text_limit(&out, 64 * 1024).unwrap(); + assert!(!full.capped); + assert_eq!(full.points.len(), 10); + + // Discarded relations (type=route) must not charge the text budget or cap the extract. + let mut route_out = Vec::new(); + blob("OSMHeader", &header, false, &mut route_out); + let mut route_pg = Vec::new(); + for rid in 1..=10u64 { + let mut rel = Vec::new(); + field_varint(1, rid, &mut rel); + field_bytes(2, &packed_of(&[3, 1]), &mut rel); + field_bytes(3, &packed_of(&[5, 2]), &mut rel); + field_bytes(8, &packed_of(&[2; 10]), &mut rel); + field_bytes(9, &delta(&ids), &mut rel); + field_bytes(10, &packed_of(&[1; 10]), &mut rel); + field_bytes(4, &rel, &mut route_pg); + } + let mut route_prim = Vec::new(); + field_bytes(1, &st, &mut route_prim); + field_bytes(2, &route_pg, &mut route_prim); + blob("OSMData", &route_prim, true, &mut route_out); + let route_osm = blocks_with_text_limit(&route_out, 1024).unwrap(); + assert!(!route_osm.capped, "discarded relations must not cap the extract"); + assert_eq!(route_osm.text_bytes, 0); + + // Drawn relation member roles referencing a repeated large string are capped too. let mut rel_out = Vec::new(); blob("OSMHeader", &header, false, &mut rel_out); let mut rel = Vec::new(); @@ -1572,7 +1671,13 @@ pub(crate) mod tests { field_bytes(2, &rel_pg, &mut rel_prim); blob("OSMData", &rel_prim, true, &mut rel_out); - assert!(matches!(blocks_with_text_limit(&rel_out, 1024), Err(DataError::Format(_)))); - assert!(blocks_with_text_limit(&rel_out, 64 * 1024).is_ok()); + let capped_rel = blocks_with_text_limit(&rel_out, 1024).unwrap(); + assert!(capped_rel.capped); + assert!(capped_rel.relations.is_empty()); + assert!(capped_rel.text_bytes <= 1024); + + let full_rel = blocks_with_text_limit(&rel_out, 64 * 1024).unwrap(); + assert!(!full_rel.capped); + assert_eq!(full_rel.relations.len(), 1); } } From d2622c021fb6ac56009298cc010d30c20a7f8e0f Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:52:03 -0500 Subject: [PATCH 03/14] Address Claude review feedback - CSV/WKT CSV headers: add reversible io::csv_header / unguard_header so formula-like field names (=1+1, =HYPERLINK(...), +0123) are apostrophe- guarded on export and restored on read, while literal leading-apostrophe names ('=1+1, 'note) round-trip unchanged. - OSM PBF text budget: track exact omitted tagged node, tagged way, relation, and text byte counts when text_limit is reached, report them in a dedicated DroppedOverLimit notice naming what, how much, and where, and assert the notice text and counts in tests. --- crates/data/src/interop.rs | 45 +++++++--- crates/data/src/io.rs | 19 ++++- crates/data/src/osm.rs | 171 ++++++++++++++++++++++++------------- 3 files changed, 164 insertions(+), 71 deletions(-) diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index ce214c19c5..e128dbece1 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -528,7 +528,7 @@ pub fn to_wkt_csv(ds: &Dataset) -> crate::Result { let mut out = String::from("wkt"); for f in &ds.fields { out.push(','); - out.push_str(&q(&f.name)); + out.push_str(&q(&crate::io::csv_header(&f.name))); } out.push('\n'); for f in &ds.features { @@ -611,19 +611,42 @@ mod tests { for plain in ["-12.5", "+42", "-0.5", "Paris"] { assert_eq!(crate::io::csv_cell(&Value::Text(plain.into())), plain, "{plain:?}"); } - // Round-trip: field names like `+0123` stay unchanged, 16-digit negative integers stay - // Integer, and formula-like text values are guarded in the CSV output. - let mut ds = - Dataset::new("rt", GeometryType::Point, vec![Field::new("+0123", FieldType::Text), Field::new("big_id", FieldType::Integer)]); - ds.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Text("\t=1".into()), Value::Int(-1_234_567_890_123_456)]); + // Round-trip: formula-like headers (`=1+1`, `=HYPERLINK(...)`, `+0123`) and literal + // leading-apostrophe headers (`'=1+1`, `'note`) are guarded on export and restored on + // read; 16-digit negative integers stay Integer; formula-like text cells stay guarded. + let mut ds = Dataset::new( + "rt", + GeometryType::Point, + vec![ + Field::new("=1+1", FieldType::Text), + Field::new("=HYPERLINK(\"https://example.com\",\"x\")", FieldType::Text), + Field::new("+0123", FieldType::Text), + Field::new("'=1+1", FieldType::Text), + Field::new("'note", FieldType::Text), + Field::new("big_id", FieldType::Integer), + ], + ); + ds.push( + Some(Geometry::Point(Coord::new(1.0, 2.0))), + vec![ + Value::Text("\t=1".into()), + Value::Text("ok".into()), + Value::Text("+0123".into()), + Value::Text("a".into()), + Value::Text("b".into()), + Value::Int(-1_234_567_890_123_456), + ], + ); let csv = to_wkt_csv(&ds).unwrap(); - assert!(csv.starts_with("wkt,+0123,big_id\n"), "header must stay unguarded: {csv}"); - assert!(csv.contains("'\t=1,-1234567890123456\n"), "text guarded, integer unguarded: {csv}"); + let header_line = csv.lines().next().unwrap_or(""); + assert_eq!(header_line, "wkt,'=1+1,\"'=HYPERLINK(\"\"https://example.com\"\",\"\"x\"\")\",'+0123,''=1+1,'note,big_id"); + assert!(csv.contains("'\t=1,ok,'+0123,a,b,-1234567890123456\n"), "text guarded, integer unguarded: {csv}"); let (back, _) = crate::io::read_csv(&csv, "rt").unwrap(); let names: Vec<&str> = back.fields.iter().map(|f| f.name.as_str()).collect(); - assert_eq!(names, ["+0123", "big_id"]); - assert_eq!(back.fields[1].ty, FieldType::Integer); + assert_eq!(names, ["=1+1", "=HYPERLINK(\"https://example.com\",\"x\")", "+0123", "'=1+1", "'note", "big_id"]); + assert_eq!(back.fields[5].ty, FieldType::Integer); assert_eq!(back.features[0].attrs[0], Value::Text("\t=1".into())); - assert_eq!(back.features[0].attrs[1], Value::Int(-1_234_567_890_123_456)); + assert_eq!(back.features[0].attrs[2], Value::Text("+0123".into())); + assert_eq!(back.features[0].attrs[5], Value::Int(-1_234_567_890_123_456)); } } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 637dd814cf..2d8202a531 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -2779,7 +2779,7 @@ fn read_csv_records( || DataError::Format(format!("CSV retained table exceeds the {allowance}-byte remaining memory budget; import a smaller file")); let header = reader.headers().map_err(refused)?; let mut left = budget.checked_sub(cost(header, header.len())).ok_or_else(too_large)?; - let headers: Vec = header.iter().map(str::to_string).collect(); + let headers: Vec = header.iter().map(unguard_header).collect(); let mut malformed = 0; let mut rows = Vec::new(); for record in reader.records() { @@ -3289,6 +3289,21 @@ pub(crate) fn csv_cell(v: &Value) -> String { } } +/// A CSV header name, prefixed with an apostrophe when it starts like a spreadsheet formula +/// (or starts with apostrophes before one, so [`unguard_header`] reverses it losslessly). +pub(crate) fn csv_header(name: &str) -> String { + if csv_needs_guard(name.trim_start_matches('\'')) { format!("'{name}") } else { name.to_string() } +} + +/// Reverses [`csv_header`]: strips one leading apostrophe only when what follows would be guarded +/// on export, so literal leading apostrophes round-trip unchanged. +fn unguard_header(header: &str) -> String { + match header.strip_prefix('\'') { + Some(rest) if csv_needs_guard(rest.trim_start_matches('\'')) => rest.to_string(), + _ => header.to_string(), + } +} + /// The names of a point layer's longitude and latitude columns in CSV: the first of the names /// reading takes for each that no field has, ignoring case and the spaces around a name (reading /// trims them). @@ -3352,7 +3367,7 @@ impl CsvWriter { // The coordinate columns come first, before any attributes using recognised names. head.extend(csv_names_in(fields, crs)); } - head.extend(fields.iter().map(|f| f.name.clone())); + head.extend(fields.iter().map(|f| csv_header(&f.name))); w.write_record(&head).map_err(|e| DataError::Format(e.to_string()))?; Ok(CsvWriter { w, point }) } diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index c31e6fe457..587394dae9 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -305,6 +305,11 @@ struct Osm { /// Cumulative bytes of decoded tag and role strings retained across the file. text_bytes: usize, text_limit: usize, + /// Entities and decoded tag/role text bytes omitted after reaching `text_limit`. + text_capped_nodes: u64, + text_capped_ways: u64, + text_capped_relations: u64, + text_capped_bytes: u64, } impl Osm { @@ -319,14 +324,17 @@ impl Osm { omitted_members: 0, text_bytes: 0, text_limit, + text_capped_nodes: 0, + text_capped_ways: 0, + text_capped_relations: 0, + text_capped_bytes: 0, } } - /// Reserves `bytes` from the retained tag/role text budget, or marks the extract capped. + /// Reserves `bytes` from the retained tag/role text budget. fn try_charge_text(&mut self, bytes: usize) -> bool { let next = self.text_bytes.saturating_add(bytes); if next > self.text_limit { - self.capped = true; return false; } self.text_bytes = next; @@ -400,9 +408,13 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { let (has_tags, cost) = tags_info(&strings, &k, &vv); let t = if !has_tags { Vec::new() - } else if osm.points.len() >= MAX_NODES || !osm.try_charge_text(cost) { + } else if osm.points.len() >= MAX_NODES { osm.capped = true; Vec::new() + } else if !osm.try_charge_text(cost) { + osm.text_capped_nodes = osm.text_capped_nodes.saturating_add(1); + osm.text_capped_bytes = osm.text_capped_bytes.saturating_add(cost as u64); + Vec::new() } else { tags(&strings, &k, &vv) }; @@ -444,9 +456,13 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { } let t = if !has_tags { Vec::new() - } else if osm.points.len() >= MAX_NODES || !osm.try_charge_text(cost) { + } else if osm.points.len() >= MAX_NODES { osm.capped = true; Vec::new() + } else if !osm.try_charge_text(cost) { + osm.text_capped_nodes = osm.text_capped_nodes.saturating_add(1); + osm.text_capped_bytes = osm.text_capped_bytes.saturating_add(cost as u64); + Vec::new() } else { let mut t = Vec::new(); let mut p = start; @@ -492,6 +508,8 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { } let (has_tags, cost) = tags_info(&strings, &k, &vv); if has_tags && !osm.try_charge_text(cost) { + osm.text_capped_ways = osm.text_capped_ways.saturating_add(1); + osm.text_capped_bytes = osm.text_capped_bytes.saturating_add(cost as u64); continue; } let places = (!lats.is_empty() && lats.len() == refs.len() && lons.len() == refs.len()).then(|| { @@ -557,7 +575,10 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { .take(MAX_MEMBERS) .map(|r| usize::try_from(*r).ok().and_then(|i| strings.get(i)).map_or(0, String::len)) .fold(0usize, usize::saturating_add); - if !osm.try_charge_text(tag_bytes.saturating_add(role_bytes)) { + let cost = tag_bytes.saturating_add(role_bytes); + if !osm.try_charge_text(cost) { + osm.text_capped_relations = osm.text_capped_relations.saturating_add(1); + osm.text_capped_bytes = osm.text_capped_bytes.saturating_add(cost as u64); continue; } // Node members are never read, so only the others past the limit are @@ -583,11 +604,7 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { Ok(()) } -/// Reads the file's blocks. -fn blocks(bytes: &[u8]) -> Result { - blocks_with_text_limit(bytes, MAX_TEXT_BYTES) -} - +/// Reads the file's blocks within a `text_limit`-byte retained tag/role budget. fn blocks_with_text_limit(bytes: &[u8], text_limit: usize) -> Result { let mut osm = Osm::with_text_limit(text_limit); let mut i = 0usize; @@ -728,9 +745,13 @@ fn inside(p: Coord, ring: &[Coord]) -> bool { /// between blocks and between the ways and relations built from them; decoding one block is one /// step without a look. pub fn read(file_name: &str, bytes: &[u8]) -> Result> { + read_with_text_limit(file_name, bytes, MAX_TEXT_BYTES) +} + +fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Result> { let stem = std::path::Path::new(file_name).file_name().and_then(|s| s.to_str()).unwrap_or("osm"); let stem = stem.trim_end_matches(".pbf").trim_end_matches(".osm").to_string(); - let mut osm = blocks(bytes)?; + let mut osm = blocks_with_text_limit(bytes, text_limit)?; osm.nodes.sort_unstable_by_key(|n| n.0); let node = |id: i64| -> Option { let i = osm.nodes.binary_search_by_key(&id, |n| n.0).ok()?; @@ -909,6 +930,30 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> .messages .push(crate::loss::Note::loss(crate::loss::LossCode::DroppedOverLimit, "the extract is larger than RustGIS reads at once: the rest is left out (use a smaller extract; on the desktop, files over 256 MB open through GDAL when it is installed)")); } + let text_capped_note = (osm.text_capped_nodes > 0 || osm.text_capped_ways > 0 || osm.text_capped_relations > 0).then(|| { + let mut parts = Vec::new(); + if osm.text_capped_nodes > 0 { + let n = osm.text_capped_nodes; + parts.push(format!("{n} {} (tags dropped in points)", if n == 1 { "tagged node" } else { "tagged nodes" })); + } + if osm.text_capped_ways > 0 { + let n = osm.text_capped_ways; + parts.push(format!("{n} {} (omitted from lines/multipolygons)", if n == 1 { "tagged way" } else { "tagged ways" })); + } + if osm.text_capped_relations > 0 { + let n = osm.text_capped_relations; + parts.push(format!("{n} {} (omitted from multipolygons)", if n == 1 { "relation" } else { "relations" })); + } + format!( + "OSM tag/role text reached the {}-byte limit: {} ({} bytes of text left out)", + osm.text_limit, + parts.join(", "), + osm.text_capped_bytes, + ) + }); + if let Some(note) = &text_capped_note { + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedOverLimit, note.clone())); + } if missing > 0 { report.messages.push(crate::loss::Note::loss( crate::loss::LossCode::DroppedFeature, @@ -961,6 +1006,9 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> *first = report; } if out.is_empty() { + if let Some(note) = text_capped_note { + return Err(DataError::Format(format!("{file_name}: {note}"))); + } return Err(DataError::Format(format!("{file_name}: nothing tagged to draw"))); } Ok(out) @@ -1599,12 +1647,13 @@ pub(crate) mod tests { let big = "x".repeat(512); let mut st = Vec::new(); - for s in ["", "name", big.as_str(), "type", "multipolygon", "route"] { + for s in ["", "name", big.as_str(), "type", "multipolygon", "route", "highway", "road"] { field_bytes(1, s.as_bytes(), &mut st); } - // Ten dense nodes all referencing the same 512-byte string entry (> 5 KiB decoded). + // Ten dense nodes all referencing the same 512-byte string entry (516 bytes each), plus + // one tagged way (527 bytes) and one drawn multipolygon relation (5136 bytes of roles/tags). let ids: Vec = (1..=10).collect(); - let coords = vec![0i64; 10]; + let coords: Vec = ids.iter().map(|i| i * 1_000_000).collect(); let mut kv = Vec::new(); for _ in 0..10 { kv.extend([1u64, 2, 0]); @@ -1615,69 +1664,75 @@ pub(crate) mod tests { field_bytes(9, &delta(&coords), &mut dense); field_bytes(10, &packed_of(&kv), &mut dense); + let mut way = Vec::new(); + field_varint(1, 100, &mut way); + field_bytes(2, &packed_of(&[6, 1]), &mut way); + field_bytes(3, &packed_of(&[7, 2]), &mut way); + field_bytes(8, &delta(&[1, 2]), &mut way); + + let mut rel = Vec::new(); + field_varint(1, 500, &mut rel); + field_bytes(2, &packed_of(&[3]), &mut rel); + field_bytes(3, &packed_of(&[4]), &mut rel); + field_bytes(8, &packed_of(&[2; 10]), &mut rel); + field_bytes(9, &delta(&ids), &mut rel); + field_bytes(10, &packed_of(&[1; 10]), &mut rel); + let mut pg = Vec::new(); field_bytes(2, &dense, &mut pg); + field_bytes(3, &way, &mut pg); + field_bytes(4, &rel, &mut pg); let mut prim = Vec::new(); field_bytes(1, &st, &mut prim); field_bytes(2, &pg, &mut prim); blob("OSMData", &prim, true, &mut out); - // Under a 1024-byte budget, only the first 516-byte tagged node is kept and `capped` is set. - let capped = blocks_with_text_limit(&out, 1024).unwrap(); - assert!(capped.capped, "extract past text budget must be marked capped"); - assert_eq!(capped.points.len(), 1); - assert!(capped.text_bytes <= 1024); + // Under a 1024-byte budget: node 1 (516 bytes) fits, nodes 2..=10 (9 * 516 = 4644 bytes), + // the tagged way (527 bytes), and the drawn relation (16 + 5120 = 5136 bytes) are left out + // and reported with exact counts and byte total. + let layers = read_with_text_limit("cap.osm.pbf", &out, 1024).unwrap(); + assert_eq!(layers.len(), 1, "only points remain after way and relation are omitted"); + assert_eq!(layers[0].0.features.len(), 1); + let expected_bytes = 9 * 516 + 527 + (4 + 12 + 10 * 512); + let note = layers[0] + .1 + .messages + .iter() + .find(|m| m.loss == Some(crate::loss::LossCode::DroppedOverLimit)) + .expect("must emit a DroppedOverLimit notice"); + assert_eq!( + note.as_str(), + format!( + "OSM tag/role text reached the 1024-byte limit: 9 tagged nodes (tags dropped in points), 1 tagged way (omitted from lines/multipolygons), 1 relation (omitted from multipolygons) ({expected_bytes} bytes of text left out)" + ) + ); - let full = blocks_with_text_limit(&out, 64 * 1024).unwrap(); - assert!(!full.capped); - assert_eq!(full.points.len(), 10); + // Within a generous budget, no text-budget notice is emitted. + let full = read_with_text_limit("cap.osm.pbf", &out, 64 * 1024).unwrap(); + assert_eq!(full[0].0.features.len(), 10); + assert_eq!(full[1].0.features.len(), 1); + assert!(!full[0].1.messages.iter().any(|m| m.loss == Some(crate::loss::LossCode::DroppedOverLimit))); - // Discarded relations (type=route) must not charge the text budget or cap the extract. + // Discarded relations (type=route) must not charge the text budget or emit a notice. let mut route_out = Vec::new(); blob("OSMHeader", &header, false, &mut route_out); let mut route_pg = Vec::new(); for rid in 1..=10u64 { - let mut rel = Vec::new(); - field_varint(1, rid, &mut rel); - field_bytes(2, &packed_of(&[3, 1]), &mut rel); - field_bytes(3, &packed_of(&[5, 2]), &mut rel); - field_bytes(8, &packed_of(&[2; 10]), &mut rel); - field_bytes(9, &delta(&ids), &mut rel); - field_bytes(10, &packed_of(&[1; 10]), &mut rel); - field_bytes(4, &rel, &mut route_pg); + let mut r = Vec::new(); + field_varint(1, rid, &mut r); + field_bytes(2, &packed_of(&[3, 1]), &mut r); + field_bytes(3, &packed_of(&[5, 2]), &mut r); + field_bytes(8, &packed_of(&[2; 10]), &mut r); + field_bytes(9, &delta(&ids), &mut r); + field_bytes(10, &packed_of(&[1; 10]), &mut r); + field_bytes(4, &r, &mut route_pg); } let mut route_prim = Vec::new(); field_bytes(1, &st, &mut route_prim); field_bytes(2, &route_pg, &mut route_prim); blob("OSMData", &route_prim, true, &mut route_out); let route_osm = blocks_with_text_limit(&route_out, 1024).unwrap(); - assert!(!route_osm.capped, "discarded relations must not cap the extract"); assert_eq!(route_osm.text_bytes, 0); - - // Drawn relation member roles referencing a repeated large string are capped too. - let mut rel_out = Vec::new(); - blob("OSMHeader", &header, false, &mut rel_out); - let mut rel = Vec::new(); - field_varint(1, 500, &mut rel); - field_bytes(2, &packed_of(&[3]), &mut rel); - field_bytes(3, &packed_of(&[4]), &mut rel); - field_bytes(8, &packed_of(&[2; 10]), &mut rel); - field_bytes(9, &delta(&ids), &mut rel); - field_bytes(10, &packed_of(&[1; 10]), &mut rel); - let mut rel_pg = Vec::new(); - field_bytes(4, &rel, &mut rel_pg); - let mut rel_prim = Vec::new(); - field_bytes(1, &st, &mut rel_prim); - field_bytes(2, &rel_pg, &mut rel_prim); - blob("OSMData", &rel_prim, true, &mut rel_out); - - let capped_rel = blocks_with_text_limit(&rel_out, 1024).unwrap(); - assert!(capped_rel.capped); - assert!(capped_rel.relations.is_empty()); - assert!(capped_rel.text_bytes <= 1024); - - let full_rel = blocks_with_text_limit(&rel_out, 64 * 1024).unwrap(); - assert!(!full_rel.capped); - assert_eq!(full_rel.relations.len(), 1); + assert_eq!(route_osm.text_capped_relations, 0); } } From e80b06b514283b0285dc3921b90009f3843b9ed0 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 10:17:21 -0500 Subject: [PATCH 04/14] Address CodeRabbit review feedback - CSV/WKT CSV headers: restore exact header preservation in read_csv_records and CsvWriter::new so external CSV headers like '=geom and '-foo match CsvOptions.wkt and keep their names, while to_wkt_csv guards formula-like headers via io::csv_needs_guard and uses io::csv_cell for data cells. - LandXML nested surfaces: collect direct

and descendants of each without descending into nested elements (linear O(N) total traversal), preserving separate point-ID maps and surface names for nested surfaces while keeping the file-wide face cap. --- crates/data/src/interop.rs | 38 ++++++++++----------- crates/data/src/io.rs | 21 ++---------- crates/data/src/landxml.rs | 70 +++++++++++++++++++++++++++++++++----- 3 files changed, 82 insertions(+), 47 deletions(-) diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index e128dbece1..9855596667 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -528,7 +528,8 @@ pub fn to_wkt_csv(ds: &Dataset) -> crate::Result { let mut out = String::from("wkt"); for f in &ds.fields { out.push(','); - out.push_str(&q(&crate::io::csv_header(&f.name))); + let name = if crate::io::csv_needs_guard(&f.name) { format!("'{}", f.name) } else { f.name.clone() }; + out.push_str(&q(&name)); } out.push('\n'); for f in &ds.features { @@ -611,9 +612,9 @@ mod tests { for plain in ["-12.5", "+42", "-0.5", "Paris"] { assert_eq!(crate::io::csv_cell(&Value::Text(plain.into())), plain, "{plain:?}"); } - // Round-trip: formula-like headers (`=1+1`, `=HYPERLINK(...)`, `+0123`) and literal - // leading-apostrophe headers (`'=1+1`, `'note`) are guarded on export and restored on - // read; 16-digit negative integers stay Integer; formula-like text cells stay guarded. + // Formula-like headers (`=1+1`, `=HYPERLINK(...)`, `\t=1`, `+0123`) are apostrophe-guarded + // on export; 16-digit negative integers stay unguarded and round-trip as Integer; formula- + // like text cells are guarded on export and unguarded on read. let mut ds = Dataset::new( "rt", GeometryType::Point, @@ -621,32 +622,29 @@ mod tests { Field::new("=1+1", FieldType::Text), Field::new("=HYPERLINK(\"https://example.com\",\"x\")", FieldType::Text), Field::new("+0123", FieldType::Text), - Field::new("'=1+1", FieldType::Text), - Field::new("'note", FieldType::Text), Field::new("big_id", FieldType::Integer), ], ); ds.push( Some(Geometry::Point(Coord::new(1.0, 2.0))), - vec![ - Value::Text("\t=1".into()), - Value::Text("ok".into()), - Value::Text("+0123".into()), - Value::Text("a".into()), - Value::Text("b".into()), - Value::Int(-1_234_567_890_123_456), - ], + vec![Value::Text("\t=1".into()), Value::Text("ok".into()), Value::Text("+0123".into()), Value::Int(-1_234_567_890_123_456)], ); let csv = to_wkt_csv(&ds).unwrap(); let header_line = csv.lines().next().unwrap_or(""); - assert_eq!(header_line, "wkt,'=1+1,\"'=HYPERLINK(\"\"https://example.com\"\",\"\"x\"\")\",'+0123,''=1+1,'note,big_id"); - assert!(csv.contains("'\t=1,ok,'+0123,a,b,-1234567890123456\n"), "text guarded, integer unguarded: {csv}"); + assert_eq!(header_line, "wkt,'=1+1,\"'=HYPERLINK(\"\"https://example.com\"\",\"\"x\"\")\",'+0123,big_id"); + assert!(csv.contains("'\t=1,ok,'+0123,-1234567890123456\n"), "text guarded, integer unguarded: {csv}"); let (back, _) = crate::io::read_csv(&csv, "rt").unwrap(); - let names: Vec<&str> = back.fields.iter().map(|f| f.name.as_str()).collect(); - assert_eq!(names, ["=1+1", "=HYPERLINK(\"https://example.com\",\"x\")", "+0123", "'=1+1", "'note", "big_id"]); - assert_eq!(back.fields[5].ty, FieldType::Integer); + assert_eq!(back.fields[3].ty, FieldType::Integer); assert_eq!(back.features[0].attrs[0], Value::Text("\t=1".into())); assert_eq!(back.features[0].attrs[2], Value::Text("+0123".into())); - assert_eq!(back.features[0].attrs[5], Value::Int(-1_234_567_890_123_456)); + assert_eq!(back.features[0].attrs[3], Value::Int(-1_234_567_890_123_456)); + + // External CSVs whose headers literally start with an apostrophe keep their exact names + // and still match explicit `CsvOptions.wkt`. + let external = "'=geom,'-foo\nPOINT (1 2),bar\n"; + let opts = crate::io::CsvOptions { wkt: Some("'=geom".into()), ..Default::default() }; + let (ext, _) = crate::io::read_csv_with(external, "ext", &opts).unwrap(); + assert_eq!(ext.fields.iter().map(|f| f.name.as_str()).collect::>(), ["'-foo"]); + assert_eq!(ext.features[0].geometry, Some(Geometry::Point(Coord::new(1.0, 2.0)))); } } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 2d8202a531..17ac4bb88b 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -2779,7 +2779,7 @@ fn read_csv_records( || DataError::Format(format!("CSV retained table exceeds the {allowance}-byte remaining memory budget; import a smaller file")); let header = reader.headers().map_err(refused)?; let mut left = budget.checked_sub(cost(header, header.len())).ok_or_else(too_large)?; - let headers: Vec = header.iter().map(unguard_header).collect(); + let headers: Vec = header.iter().map(str::to_string).collect(); let mut malformed = 0; let mut rows = Vec::new(); for record in reader.records() { @@ -3269,7 +3269,7 @@ const FORMULA_START: [char; 6] = ['=', '+', '-', '@', '\t', '\r']; /// Text needs an apostrophe if it starts like a spreadsheet formula. The numeric exception /// keeps finite numbers that fit Double precision and have at most 15 significant digits. /// A leading-zero code stays guarded unless its mantissa has digits after a decimal point. -fn csv_needs_guard(text: &str) -> bool { +pub(crate) fn csv_needs_guard(text: &str) -> bool { if !text.starts_with(FORMULA_START) { return false; } @@ -3289,21 +3289,6 @@ pub(crate) fn csv_cell(v: &Value) -> String { } } -/// A CSV header name, prefixed with an apostrophe when it starts like a spreadsheet formula -/// (or starts with apostrophes before one, so [`unguard_header`] reverses it losslessly). -pub(crate) fn csv_header(name: &str) -> String { - if csv_needs_guard(name.trim_start_matches('\'')) { format!("'{name}") } else { name.to_string() } -} - -/// Reverses [`csv_header`]: strips one leading apostrophe only when what follows would be guarded -/// on export, so literal leading apostrophes round-trip unchanged. -fn unguard_header(header: &str) -> String { - match header.strip_prefix('\'') { - Some(rest) if csv_needs_guard(rest.trim_start_matches('\'')) => rest.to_string(), - _ => header.to_string(), - } -} - /// The names of a point layer's longitude and latitude columns in CSV: the first of the names /// reading takes for each that no field has, ignoring case and the spaces around a name (reading /// trims them). @@ -3367,7 +3352,7 @@ impl CsvWriter { // The coordinate columns come first, before any attributes using recognised names. head.extend(csv_names_in(fields, crs)); } - head.extend(fields.iter().map(|f| csv_header(&f.name))); + head.extend(fields.iter().map(|f| f.name.clone())); w.write_record(&head).map_err(|e| DataError::Format(e.to_string()))?; Ok(CsvWriter { w, point }) } diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index fe97bdac12..91ccc629b4 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -41,6 +41,34 @@ fn elements<'a, 'i>(n: &Node<'a, 'i>, name: &'static str) -> impl Iterator` and `` descendants of `s`, stopping at any nested `` so each surface +/// keeps its own point-ID namespace and every node is visited once even under deep nesting. +fn surface_nodes<'a, 'i>(s: &Node<'a, 'i>) -> Result<(Vec>, Vec>)> { + let (mut pts, mut fcs) = (Vec::new(), Vec::new()); + let mut stack: Vec> = s.children().collect(); + stack.reverse(); + let mut visited = 0usize; + while let Some(node) = stack.pop() { + if visited.is_multiple_of(1024) { + crate::progress::check()?; + } + visited += 1; + if !node.is_element() { + continue; + } + match local(&node) { + "Surface" => continue, + "P" => pts.push(node), + "F" => fcs.push(node), + _ => {} + } + let mut children: Vec> = node.children().collect(); + children.reverse(); + stack.extend(children); + } + Ok((pts, fcs)) +} + fn text_of(n: &Node) -> String { n.children().filter(|t| t.is_text()).filter_map(|t| t.text()).collect::() } @@ -205,15 +233,11 @@ fn read_with_max_faces(file_name: &str, bytes: &[u8], crs: Option, max_face let mut faces_left_out = 0usize; let mut total_faces = 0usize; for s in elements(&root, "Surface") { - // Nested `` elements would revisit every descendant `

` and ``, multiplying - // work and face counts quadratically. - if s.ancestors().skip(1).any(|a| a.is_element() && local(&a) == "Surface") { - continue; - } crate::progress::check()?; let sname = s.attribute("name").unwrap_or("").to_string(); + let (surf_pts, surf_faces) = surface_nodes(&s)?; let mut pnts: HashMap<&str, (Coord, Option)> = HashMap::new(); - for (pi, p) in elements(&s, "P").enumerate() { + for (pi, p) in surf_pts.into_iter().enumerate() { if pi.is_multiple_of(1024) { crate::progress::check()?; } @@ -229,7 +253,7 @@ fn read_with_max_faces(file_name: &str, bytes: &[u8], crs: Option, max_face // Invisible faces (i="1") are holes in the surface, never read, so the cap counts the // faces that are. let mut s_over_limit = false; - for (fi, f) in elements(&s, "F").filter(|f| f.attribute("i") != Some("1")).enumerate() { + for (fi, f) in surf_faces.into_iter().filter(|f| f.attribute("i") != Some("1")).enumerate() { if fi.is_multiple_of(1024) { crate::progress::check()?; } @@ -497,17 +521,45 @@ mod tests { fn nested_surfaces_do_not_multiply_faces_and_cap_is_file_wide() { let nested = r#" - +

0 0 1

0 1 1

1 0 1

1 2 3
+ + +

10 10 5

10 11 5

11 10 5

+ 1 2 3 +
+
"#; let layers = read("nested.xml", nested.as_bytes(), None).unwrap(); assert_eq!(layers.len(), 1); - assert_eq!(layers[0].0.features.len(), 1, "nested must not duplicate faces"); + assert_eq!(layers[0].0.features.len(), 2, "nested elements must not duplicate faces"); + assert_eq!(layers[0].0.value(0, 0), &Value::Text("inner_a".into())); + assert_eq!(layers[0].0.value(0, 1), &Value::Float(1.0)); + assert_eq!(layers[0].0.value(1, 0), &Value::Text("inner_b".into())); + assert_eq!(layers[0].0.value(1, 1), &Value::Float(5.0)); + assert_eq!( + layers[0].0.features[0].geometry, + Some(Geometry::Polygon(vec![vec![vec![ + Coord::new(0.0, 0.0), + Coord::new(1.0, 0.0), + Coord::new(0.0, 1.0), + Coord::new(0.0, 0.0), + ]]])) + ); + assert_eq!( + layers[0].0.features[1].geometry, + Some(Geometry::Polygon(vec![vec![vec![ + Coord::new(10.0, 10.0), + Coord::new(11.0, 10.0), + Coord::new(10.0, 11.0), + Coord::new(10.0, 10.0), + ]]])) + ); let two_surfaces = r#" From 1609251e6c8c3966af26630771880ff9a4465637 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 10:57:03 -0500 Subject: [PATCH 05/14] Address Claude review feedback - OSM PBF tag overhead: charge TAG_OVERHEAD (48 bytes) per retained tag pair and ROLE_OVERHEAD (24 bytes) per retained relation member role across regular nodes, dense nodes, ways, and relations so zero-length ("", "") pairs cannot allocate unbounded entries at zero budget cost. - OSM PBF per-kind budgets: split the text budget evenly across nodes, ways, and relations so heavy node tags early in an extract cannot starve ways and relations later in the file. - CSV / WKT CSV header guard parity and notices: guard formula-like headers via io::csv_header in both to_wkt_csv and CsvWriter::new, expose to_wkt_csv_reporting for callers wanting the guarded header count directly, and emit counted spreadsheet-protection notices for guarded field names (and WKT CSV text cells) via CsvLosses::notes and export_losses_notes_in. --- crates/data/src/interop.rs | 51 ++++++++- crates/data/src/io.rs | 60 +++++++--- crates/data/src/osm.rs | 219 ++++++++++++++++++++++++++++++++----- 3 files changed, 284 insertions(+), 46 deletions(-) diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index 9855596667..f87c331e03 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -522,13 +522,21 @@ impl WktParser { /// CSV with a `wkt` geometry column and every attribute; cancellable between features. pub fn to_wkt_csv(ds: &Dataset) -> crate::Result { + to_wkt_csv_reporting(ds).map(|(csv, _)| csv) +} + +/// As [`to_wkt_csv`], also returning how many field names were prefixed with an apostrophe to +/// guard against spreadsheet formula evaluation. +pub fn to_wkt_csv_reporting(ds: &Dataset) -> crate::Result<(String, usize)> { let q = |s: &str| { if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() } }; + let mut guarded_headers = 0usize; let mut out = String::from("wkt"); for f in &ds.fields { out.push(','); - let name = if crate::io::csv_needs_guard(&f.name) { format!("'{}", f.name) } else { f.name.clone() }; + let name = crate::io::csv_header(&f.name); + guarded_headers += usize::from(name != f.name); out.push_str(&q(&name)); } out.push('\n'); @@ -541,7 +549,7 @@ pub fn to_wkt_csv(ds: &Dataset) -> crate::Result { } out.push('\n'); } - Ok(out) + Ok((out, guarded_headers)) } #[cfg(test)] @@ -612,9 +620,10 @@ mod tests { for plain in ["-12.5", "+42", "-0.5", "Paris"] { assert_eq!(crate::io::csv_cell(&Value::Text(plain.into())), plain, "{plain:?}"); } - // Formula-like headers (`=1+1`, `=HYPERLINK(...)`, `\t=1`, `+0123`) are apostrophe-guarded - // on export; 16-digit negative integers stay unguarded and round-trip as Integer; formula- - // like text cells are guarded on export and unguarded on read. + // Formula-like headers (`=1+1`, `=HYPERLINK(...)`, `+0123`) are apostrophe-guarded on + // export in both WKT CSV and plain CSV, reported via `export_losses_notes`, and read back + // with the guard intact; 16-digit negative integers stay unguarded and round-trip as + // Integer; formula-like text cells are guarded on export and unguarded on read. let mut ds = Dataset::new( "rt", GeometryType::Point, @@ -629,11 +638,41 @@ mod tests { Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Text("\t=1".into()), Value::Text("ok".into()), Value::Text("+0123".into()), Value::Int(-1_234_567_890_123_456)], ); - let csv = to_wkt_csv(&ds).unwrap(); + let (csv, guarded_headers) = to_wkt_csv_reporting(&ds).unwrap(); + assert_eq!(guarded_headers, 3); let header_line = csv.lines().next().unwrap_or(""); assert_eq!(header_line, "wkt,'=1+1,\"'=HYPERLINK(\"\"https://example.com\"\",\"\"x\"\")\",'+0123,big_id"); assert!(csv.contains("'\t=1,ok,'+0123,-1234567890123456\n"), "text guarded, integer unguarded: {csv}"); + // Plain CSV writer has header-guard parity too. + let plain_csv = crate::io::to_csv(&ds).unwrap(); + assert_eq!( + plain_csv.lines().next().unwrap_or(""), + "longitude,latitude,'=1+1,\"'=HYPERLINK(\"\"https://example.com\"\",\"\"x\"\")\",'+0123,big_id" + ); + // Both WKT CSV and plain CSV report the guarded field names and guarded text values. + for ext in ["wkt", "csv"] { + let notes = crate::io::export_losses_notes(&ds, ext, None, "rt.csv").unwrap(); + assert!( + notes.iter().any(|n| n.contains("CSV prefixed 3 field names with an apostrophe for spreadsheet protection")), + "{ext}: {notes:?}" + ); + assert!( + notes.iter().any(|n| n.contains("CSV prefixed 2 text values with an apostrophe for spreadsheet protection")), + "{ext}: {notes:?}" + ); + } + // Clean dataset produces zero guard notices. + let mut clean = Dataset::new("clean", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + clean.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Text("Paris".into())]); + assert_eq!(to_wkt_csv_reporting(&clean).unwrap().1, 0); + assert!(crate::io::export_losses_notes(&clean, "wkt", None, "clean.csv").unwrap().is_empty()); + assert!(crate::io::export_losses_notes(&clean, "csv", None, "clean.csv").unwrap().is_empty()); + + // Round-trip: guarded field names come back with their reported apostrophe prefix; + // integer column stays Integer; text cells unguard back to their original values. let (back, _) = crate::io::read_csv(&csv, "rt").unwrap(); + let names: Vec<&str> = back.fields.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["'=1+1", "'=HYPERLINK(\"https://example.com\",\"x\")", "'+0123", "big_id"]); assert_eq!(back.fields[3].ty, FieldType::Integer); assert_eq!(back.features[0].attrs[0], Value::Text("\t=1".into())); assert_eq!(back.features[0].attrs[2], Value::Text("+0123".into())); diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 17ac4bb88b..1ae5403f9b 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3289,6 +3289,11 @@ pub(crate) fn csv_cell(v: &Value) -> String { } } +/// A CSV header name, prefixed with an apostrophe when it starts like a spreadsheet formula. +pub(crate) fn csv_header(name: &str) -> String { + if csv_needs_guard(name) { format!("'{name}") } else { name.to_string() } +} + /// The names of a point layer's longitude and latitude columns in CSV: the first of the names /// reading takes for each that no field has, ignoring case and the spaces around a name (reading /// trims them). @@ -3352,7 +3357,7 @@ impl CsvWriter { // The coordinate columns come first, before any attributes using recognised names. head.extend(csv_names_in(fields, crs)); } - head.extend(fields.iter().map(|f| f.name.clone())); + head.extend(fields.iter().map(|f| csv_header(&f.name))); w.write_record(&head).map_err(|e| DataError::Format(e.to_string()))?; Ok(CsvWriter { w, point }) } @@ -4893,19 +4898,8 @@ impl CsvLosses { let what = if self.unwritten == 1 { "1 feature".to_string() } else { format!("{} features", self.unwritten) }; notes.push(format!("{target}: CSV holds a point a row, so the geometry of {what} wasn't written, only the attributes")); } - let total: usize = self.guarded.iter().sum(); - if total > 0 { - let target: String = target.chars().map(dbf_notice_char).collect(); - let values = if total == 1 { "value" } else { "values" }; - let affected = fields - .iter() - .zip(&self.guarded) - .filter(|(_, n)| **n > 0) - .map(|(f, n)| format!("'{}' ({n})", dbf_notice_name(&f.name))) - .collect::>() - .join(", "); - notes.push(format!("{target}: CSV prefixed {total} text {values} with an apostrophe for spreadsheet protection in {affected}")); - } + notes.extend(csv_guarded_headers_note(fields, target)); + notes.extend(csv_guarded_cells_note(fields, &self.guarded, target)); notes } @@ -5299,6 +5293,37 @@ pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option, t export_losses_notes_in(ds, ext, name_field, target, Crs::LonLat) } +/// Notice for CSV/WKT CSV field names prefixed with an apostrophe for spreadsheet protection. +fn csv_guarded_headers_note(fields: &[Field], target: &str) -> Option { + let guarded: Vec = + fields.iter().filter(|f| csv_needs_guard(&f.name)).map(|f| format!("'{}'", dbf_notice_name(&f.name))).collect(); + if guarded.is_empty() { + return None; + } + let target: String = target.chars().map(dbf_notice_char).collect(); + let count = guarded.len(); + let names = if count == 1 { "field name" } else { "field names" }; + Some(format!("{target}: CSV prefixed {count} {names} with an apostrophe for spreadsheet protection ({})", guarded.join(", "))) +} + +/// Notice for CSV/WKT CSV text cells prefixed with an apostrophe for spreadsheet protection. +fn csv_guarded_cells_note(fields: &[Field], guarded: &[usize], target: &str) -> Option { + let total: usize = guarded.iter().sum(); + if total == 0 { + return None; + } + let target: String = target.chars().map(dbf_notice_char).collect(); + let values = if total == 1 { "value" } else { "values" }; + let affected = fields + .iter() + .zip(guarded) + .filter(|(_, n)| **n > 0) + .map(|(f, n)| format!("'{}' ({n})", dbf_notice_name(&f.name))) + .collect::>() + .join(", "); + Some(format!("{target}: CSV prefixed {total} text {values} with an apostrophe for spreadsheet protection in {affected}")) +} + /// As [`export_losses_notes`], for an export written in `crs`. pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option, target: &str, crs: Crs) -> Result> { let mut notes = match ext { @@ -5327,6 +5352,13 @@ pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option notes.extend(losses.coordinates_note_in(&ds.fields, target, crs)); notes } + "wkt" => { + let mut notes = Vec::new(); + notes.extend(csv_guarded_headers_note(&ds.fields, target)); + let guarded_cells = CsvLosses::of(&ds.features, GeometryType::None, &ds.fields)?; + notes.extend(csv_guarded_cells_note(&ds.fields, &guarded_cells.guarded, target)); + notes + } "kml" | "kmz" => kml_empty_fields_note(ds, target)?.into_iter().chain(kml_blank_names_note(ds, target)?).collect(), "gpx" => gpx_notes(ds, name_field, target), _ => Vec::new(), diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 587394dae9..4c203b1655 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -25,8 +25,14 @@ const MAX_WAYS: usize = MAX_NODES / 4; const MAX_REFS: usize = MAX_NODES * 2; const MAX_RELATIONS: usize = MAX_NODES / 40; /// The most decoded tag and role text bytes kept across an OSM PBF file: a small compressed block -/// can repeat one string-table entry across thousands of entities. +/// can repeat one string-table entry across thousands of entities. Split across nodes, ways and +/// relations so heavy tags on one kind cannot starve the others. const MAX_TEXT_BYTES: usize = if cfg!(target_arch = "wasm32") { 64 << 20 } else { 256 << 20 }; +/// Per-tag overhead (one `(String, String)` entry) charged beside key/value text bytes so +/// zero-length `("", "")` tag pairs from string-table index 0 cannot allocate unbounded entries. +const TAG_OVERHEAD: usize = 48; +/// Per-member role overhead (one `String`) charged beside role text bytes. +const ROLE_OVERHEAD: usize = 24; /// Keys with a field of their own (as GDAL's OSM driver gives them). const KEYS: &[&str] = &[ @@ -259,7 +265,8 @@ fn ignored(key: &str) -> bool { || key.starts_with("openGeoDB:") } -/// Whether `keys`/`vals` hold any non-ignored tags and their combined UTF-8 byte length. +/// Whether `keys`/`vals` hold any non-ignored tags and their combined retained byte cost +/// (UTF-8 key/value lengths plus [`TAG_OVERHEAD`] per entry). fn tags_info(strings: &[String], keys: &[u64], vals: &[u64]) -> (bool, usize) { let mut any = false; let mut bytes = 0usize; @@ -273,7 +280,7 @@ fn tags_info(strings: &[String], keys: &[u64], vals: &[u64]) -> (bool, usize) { continue; } any = true; - bytes = bytes.saturating_add(k.len()).saturating_add(v.len()); + bytes = bytes.saturating_add(TAG_OVERHEAD).saturating_add(k.len()).saturating_add(v.len()); } (any, bytes) } @@ -302,10 +309,16 @@ struct Osm { capped: bool, /// Members omitted at the per-relation limit; wide enough for all bounded relations. omitted_members: u64, - /// Cumulative bytes of decoded tag and role strings retained across the file. - text_bytes: usize, + /// Cumulative retained tag/role bytes (including per-entry overhead), tracked separately per + /// entity kind so heavy node tags early in a file cannot starve ways or relations. + node_text_bytes: usize, + way_text_bytes: usize, + relation_text_bytes: usize, + node_text_limit: usize, + way_text_limit: usize, + relation_text_limit: usize, text_limit: usize, - /// Entities and decoded tag/role text bytes omitted after reaching `text_limit`. + /// Entities and decoded tag/role text bytes omitted after reaching a text budget. text_capped_nodes: u64, text_capped_ways: u64, text_capped_relations: u64, @@ -314,6 +327,7 @@ struct Osm { impl Osm { fn with_text_limit(text_limit: usize) -> Self { + let share = text_limit / 3; Osm { nodes: Vec::new(), points: Vec::new(), @@ -322,7 +336,12 @@ impl Osm { relations: Vec::new(), capped: false, omitted_members: 0, - text_bytes: 0, + node_text_bytes: 0, + way_text_bytes: 0, + relation_text_bytes: 0, + node_text_limit: share, + way_text_limit: share, + relation_text_limit: text_limit.saturating_sub(share.saturating_mul(2)), text_limit, text_capped_nodes: 0, text_capped_ways: 0, @@ -331,15 +350,26 @@ impl Osm { } } - /// Reserves `bytes` from the retained tag/role text budget. - fn try_charge_text(&mut self, bytes: usize) -> bool { - let next = self.text_bytes.saturating_add(bytes); - if next > self.text_limit { + fn try_charge(used: &mut usize, limit: usize, bytes: usize) -> bool { + let next = used.saturating_add(bytes); + if next > limit { return false; } - self.text_bytes = next; + *used = next; true } + + fn try_charge_node_text(&mut self, bytes: usize) -> bool { + Self::try_charge(&mut self.node_text_bytes, self.node_text_limit, bytes) + } + + fn try_charge_way_text(&mut self, bytes: usize) -> bool { + Self::try_charge(&mut self.way_text_bytes, self.way_text_limit, bytes) + } + + fn try_charge_relation_text(&mut self, bytes: usize) -> bool { + Self::try_charge(&mut self.relation_text_bytes, self.relation_text_limit, bytes) + } } /// Degrees from OSM's fixed point (1e-7°), and back. @@ -411,7 +441,7 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { } else if osm.points.len() >= MAX_NODES { osm.capped = true; Vec::new() - } else if !osm.try_charge_text(cost) { + } else if !osm.try_charge_node_text(cost) { osm.text_capped_nodes = osm.text_capped_nodes.saturating_add(1); osm.text_capped_bytes = osm.text_capped_bytes.saturating_add(cost as u64); Vec::new() @@ -451,7 +481,7 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { && !ignored(k) { has_tags = true; - cost = cost.saturating_add(k.len()).saturating_add(v.len()); + cost = cost.saturating_add(TAG_OVERHEAD).saturating_add(k.len()).saturating_add(v.len()); } } let t = if !has_tags { @@ -459,7 +489,7 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { } else if osm.points.len() >= MAX_NODES { osm.capped = true; Vec::new() - } else if !osm.try_charge_text(cost) { + } else if !osm.try_charge_node_text(cost) { osm.text_capped_nodes = osm.text_capped_nodes.saturating_add(1); osm.text_capped_bytes = osm.text_capped_bytes.saturating_add(cost as u64); Vec::new() @@ -507,7 +537,7 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { continue; } let (has_tags, cost) = tags_info(&strings, &k, &vv); - if has_tags && !osm.try_charge_text(cost) { + if has_tags && !osm.try_charge_way_text(cost) { osm.text_capped_ways = osm.text_capped_ways.saturating_add(1); osm.text_capped_bytes = osm.text_capped_bytes.saturating_add(cost as u64); continue; @@ -573,10 +603,13 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { let role_bytes = roles .iter() .take(MAX_MEMBERS) - .map(|r| usize::try_from(*r).ok().and_then(|i| strings.get(i)).map_or(0, String::len)) + .map(|r| { + let len = usize::try_from(*r).ok().and_then(|i| strings.get(i)).map_or(0, String::len); + ROLE_OVERHEAD.saturating_add(len) + }) .fold(0usize, usize::saturating_add); let cost = tag_bytes.saturating_add(role_bytes); - if !osm.try_charge_text(cost) { + if !osm.try_charge_relation_text(cost) { osm.text_capped_relations = osm.text_capped_relations.saturating_add(1); osm.text_capped_bytes = osm.text_capped_bytes.saturating_add(cost as u64); continue; @@ -1687,13 +1720,16 @@ pub(crate) mod tests { field_bytes(2, &pg, &mut prim); blob("OSMData", &prim, true, &mut out); - // Under a 1024-byte budget: node 1 (516 bytes) fits, nodes 2..=10 (9 * 516 = 4644 bytes), - // the tagged way (527 bytes), and the drawn relation (16 + 5120 = 5136 bytes) are left out - // and reported with exact counts and byte total. - let layers = read_with_text_limit("cap.osm.pbf", &out, 1024).unwrap(); + // Under a 1800-byte total budget (600 bytes per entity kind): + // - node 1 (48 + 516 = 564 bytes) fits; nodes 2..=10 (9 * 564 = 5076 bytes) exceed the + // node share; + // - the tagged way (2 * 48 + 527 = 623 bytes) exceeds the 600-byte way share; + // - the drawn relation (48 + 16 + 10 * (24 + 512) = 5424 bytes) exceeds the 600-byte + // relation share. + let layers = read_with_text_limit("cap.osm.pbf", &out, 1800).unwrap(); assert_eq!(layers.len(), 1, "only points remain after way and relation are omitted"); assert_eq!(layers[0].0.features.len(), 1); - let expected_bytes = 9 * 516 + 527 + (4 + 12 + 10 * 512); + let expected_bytes = 9 * (TAG_OVERHEAD + 516) + (2 * TAG_OVERHEAD + 527) + (TAG_OVERHEAD + 16 + 10 * (ROLE_OVERHEAD + 512)); let note = layers[0] .1 .messages @@ -1703,7 +1739,7 @@ pub(crate) mod tests { assert_eq!( note.as_str(), format!( - "OSM tag/role text reached the 1024-byte limit: 9 tagged nodes (tags dropped in points), 1 tagged way (omitted from lines/multipolygons), 1 relation (omitted from multipolygons) ({expected_bytes} bytes of text left out)" + "OSM tag/role text reached the 1800-byte limit: 9 tagged nodes (tags dropped in points), 1 tagged way (omitted from lines/multipolygons), 1 relation (omitted from multipolygons) ({expected_bytes} bytes of text left out)" ) ); @@ -1731,8 +1767,139 @@ pub(crate) mod tests { field_bytes(1, &st, &mut route_prim); field_bytes(2, &route_pg, &mut route_prim); blob("OSMData", &route_prim, true, &mut route_out); - let route_osm = blocks_with_text_limit(&route_out, 1024).unwrap(); - assert_eq!(route_osm.text_bytes, 0); + let route_osm = blocks_with_text_limit(&route_out, 1800).unwrap(); + assert_eq!(route_osm.relation_text_bytes, 0); assert_eq!(route_osm.text_capped_relations, 0); } + + /// Zero-length `("", "")` tag pairs from string-table index 0 still charge per-tag overhead, + /// so they cannot allocate unbounded `(String, String)` entries at zero budget cost. + #[test] + fn zero_length_tags_still_hit_text_budget() { + let mut out = Vec::new(); + let mut header = Vec::new(); + field_bytes(4, b"OsmSchema-V0.6", &mut header); + field_bytes(4, b"DenseNodes", &mut header); + blob("OSMHeader", &header, false, &mut out); + + let mut st = Vec::new(); + for s in ["", "name", "ok"] { + field_bytes(1, s.as_bytes(), &mut st); + } + // Two dense nodes (first tagged so a points layer exists). + let mut dense = Vec::new(); + field_bytes(1, &delta(&[1, 2]), &mut dense); + field_bytes(8, &delta(&[0, 1_000_000]), &mut dense); + field_bytes(9, &delta(&[0, 1_000_000]), &mut dense); + field_bytes(10, &packed_of(&[1, 2, 0, 0]), &mut dense); + + // One way carrying 30 zero-length ("", "") tag pairs (30 * TAG_OVERHEAD = 1440 bytes). + let mut way = Vec::new(); + field_varint(1, 200, &mut way); + field_bytes(2, &packed_of(&[0; 30]), &mut way); + field_bytes(3, &packed_of(&[0; 30]), &mut way); + field_bytes(8, &delta(&[1, 2]), &mut way); + + let mut pg = Vec::new(); + field_bytes(2, &dense, &mut pg); + field_bytes(3, &way, &mut pg); + let mut prim = Vec::new(); + field_bytes(1, &st, &mut prim); + field_bytes(2, &pg, &mut prim); + blob("OSMData", &prim, true, &mut out); + + // Total budget 3000 -> 1000-byte way share < 1440-byte zero-length tag overhead. + let layers = read_with_text_limit("empty-tags.osm.pbf", &out, 3000).unwrap(); + assert_eq!(layers.len(), 1, "way with excess zero-length tags must be omitted"); + let expected = 30 * TAG_OVERHEAD; + let note = layers[0] + .1 + .messages + .iter() + .find(|m| m.loss == Some(crate::loss::LossCode::DroppedOverLimit)) + .expect("must emit DroppedOverLimit notice for zero-length tags"); + assert_eq!( + note.as_str(), + format!( + "OSM tag/role text reached the 3000-byte limit: 1 tagged way (omitted from lines/multipolygons) ({expected} bytes of text left out)" + ) + ); + } + + /// Exhausting the node text budget early in a file must not starve tagged ways or drawn + /// relations that appear later. + #[test] + fn node_text_budget_does_not_starve_ways_or_relations() { + let mut out = Vec::new(); + let mut header = Vec::new(); + field_bytes(4, b"OsmSchema-V0.6", &mut header); + field_bytes(4, b"DenseNodes", &mut header); + blob("OSMHeader", &header, false, &mut out); + + let big = "x".repeat(512); + let mut st = Vec::new(); + for s in ["", "name", big.as_str(), "highway", "road", "type", "multipolygon", "outer"] { + field_bytes(1, s.as_bytes(), &mut st); + } + // Ten dense nodes (first 4 form a square for the relation), all with 512-byte names. + let ids: Vec = (1..=10).collect(); + let lons = vec![0, 1_000_000, 1_000_000, 0, 2_000_000, 3_000_000, 4_000_000, 5_000_000, 6_000_000, 7_000_000]; + let lats = vec![0, 0, 1_000_000, 1_000_000, 0, 0, 0, 0, 0, 0]; + let mut kv = Vec::new(); + for _ in 0..10 { + kv.extend([1u64, 2, 0]); + } + let mut dense = Vec::new(); + field_bytes(1, &delta(&ids), &mut dense); + field_bytes(8, &delta(&lats), &mut dense); + field_bytes(9, &delta(&lons), &mut dense); + field_bytes(10, &packed_of(&kv), &mut dense); + + // Way 100: small tagged road (fits easily in way share). + let mut road = Vec::new(); + field_varint(1, 100, &mut road); + field_bytes(2, &packed_of(&[3]), &mut road); + field_bytes(3, &packed_of(&[4]), &mut road); + field_bytes(8, &delta(&[5, 6]), &mut road); + + // Way 101: untagged closed outer ring for relation 200. + let mut ring = Vec::new(); + field_varint(1, 101, &mut ring); + field_bytes(8, &delta(&[1, 2, 3, 4, 1]), &mut ring); + + // Relation 200: small multipolygon (fits easily in relation share). + let mut rel = Vec::new(); + field_varint(1, 200, &mut rel); + field_bytes(2, &packed_of(&[5]), &mut rel); + field_bytes(3, &packed_of(&[6]), &mut rel); + field_bytes(8, &packed_of(&[7]), &mut rel); + field_bytes(9, &delta(&[101]), &mut rel); + field_bytes(10, &packed_of(&[1]), &mut rel); + + let mut pg = Vec::new(); + field_bytes(2, &dense, &mut pg); + field_bytes(3, &road, &mut pg); + field_bytes(3, &ring, &mut pg); + field_bytes(4, &rel, &mut pg); + let mut prim = Vec::new(); + field_bytes(1, &st, &mut prim); + field_bytes(2, &pg, &mut prim); + blob("OSMData", &prim, true, &mut out); + + // Budget 1800 -> 600 per kind: only 1 of 10 tagged nodes fits, but both road and + // multipolygon relation remain intact. + let layers = read_with_text_limit("isolated.osm.pbf", &out, 1800).unwrap(); + assert_eq!(layers.len(), 3, "points, lines, and multipolygons must all be present"); + assert_eq!(layers[0].0.features.len(), 1, "only 1 tagged node fits in node budget"); + assert_eq!(layers[1].0.features.len(), 1, "tagged way must not be starved by nodes"); + assert_eq!(layers[2].0.features.len(), 1, "multipolygon relation must not be starved by nodes"); + let note = layers[0] + .1 + .messages + .iter() + .find(|m| m.loss == Some(crate::loss::LossCode::DroppedOverLimit)) + .expect("node cap notice must be emitted"); + assert!(note.contains("9 tagged nodes (tags dropped in points)"), "{note:?}"); + assert!(!note.contains("tagged way") && !note.contains("relation"), "{note:?}"); + } } From 2ad5cb17985b97f64c555cd787095d42e0a1309e Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 11:22:04 -0500 Subject: [PATCH 06/14] Address Claude review feedback - Clarify the CSV/WKT CSV guarded-header export notice so it explicitly states that formula-prefixed field names read back with the leading apostrophe, and assert that wording alongside the read-back field names in tests. --- crates/data/src/interop.rs | 8 ++++++-- crates/data/src/io.rs | 7 +++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index f87c331e03..d12315ef67 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -649,11 +649,15 @@ mod tests { plain_csv.lines().next().unwrap_or(""), "longitude,latitude,'=1+1,\"'=HYPERLINK(\"\"https://example.com\"\",\"\"x\"\")\",'+0123,big_id" ); - // Both WKT CSV and plain CSV report the guarded field names and guarded text values. + // Both WKT CSV and plain CSV report the guarded field names (including that they read back + // with the apostrophe prefix) and guarded text values. for ext in ["wkt", "csv"] { let notes = crate::io::export_losses_notes(&ds, ext, None, "rt.csv").unwrap(); assert!( - notes.iter().any(|n| n.contains("CSV prefixed 3 field names with an apostrophe for spreadsheet protection")), + notes.iter().any(|n| { + n.contains("CSV prefixed 3 field names with an apostrophe for spreadsheet protection") + && n.ends_with("; they read back with that prefix") + }), "{ext}: {notes:?}" ); assert!( diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 1ae5403f9b..b214315aac 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -5302,8 +5302,11 @@ fn csv_guarded_headers_note(fields: &[Field], target: &str) -> Option { } let target: String = target.chars().map(dbf_notice_char).collect(); let count = guarded.len(); - let names = if count == 1 { "field name" } else { "field names" }; - Some(format!("{target}: CSV prefixed {count} {names} with an apostrophe for spreadsheet protection ({})", guarded.join(", "))) + let (names, pronoun) = if count == 1 { ("field name", "it reads") } else { ("field names", "they read") }; + Some(format!( + "{target}: CSV prefixed {count} {names} with an apostrophe for spreadsheet protection ({}); {pronoun} back with that prefix", + guarded.join(", ") + )) } /// Notice for CSV/WKT CSV text cells prefixed with an apostrophe for spreadsheet protection. From fd493fd049b5d7d7565fa023dcb76e382311f87e Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 11:59:33 -0500 Subject: [PATCH 07/14] Address Claude review feedback - FileGDB: count unreadable and non-finite geometries in read_table and emit a LossCode::DroppedGeometry notice when > 0, with tests checking both lossy input (notice emitted) and clean input (no notice). --- crates/data/src/filegdb.rs | 14 +++++++++++++- crates/data/src/filegdb/tests.rs | 24 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index 757b2e9b24..420e9eb84c 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -370,6 +370,7 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result) -> Result {} - Err(()) => report.skipped += 1, + Err(()) => { + bad_geometries += 1; + report.skipped += 1; + } } } // Kept as the file holds it, in its own system; counted when it has no place in @@ -478,6 +482,14 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result 0 { + let what = if bad_geometries == 1 { + "1 feature had an unreadable or non-finite geometry and is kept without geometry".to_string() + } else { + format!("{bad_geometries} features had unreadable or non-finite geometries and are kept without geometry") + }; + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedGeometry, what)); + } Ok(Some((ds, report))) } diff --git a/crates/data/src/filegdb/tests.rs b/crates/data/src/filegdb/tests.rs index 8437389363..ec39793686 100644 --- a/crates/data/src/filegdb/tests.rs +++ b/crates/data/src/filegdb/tests.rs @@ -989,6 +989,30 @@ fn non_finite_coordinates_are_rejected() { line.extend(varint(0)); line.extend(varint(0)); assert!(decode_geometry(&line, &tiny_scale, &mut 100).is_err()); + + // End-to-end through `read_table`: lossy input emits a DroppedGeometry notice; clean input emits none. + let (mut t, x) = table(1, &[F::Oid, F::Shape { z: false, wkt: "" }], &[vec![V::Blob(pt.clone())]]); + let scale_bytes = 1000.0f64.to_le_bytes(); + let pos = t.windows(8).position(|w| w == scale_bytes).expect("xy_scale in shape field header"); + t[pos..pos + 8].copy_from_slice(&1e-308f64.to_le_bytes()); + let (lossy_ds, lossy_report) = read_table("nonfinite", &t, &x, None).unwrap().unwrap(); + assert_eq!(lossy_ds.features.len(), 1); + assert!(lossy_ds.features[0].geometry.is_none()); + assert_eq!(lossy_report.skipped, 1); + assert!( + lossy_report.messages.iter().any(|m| { + m.loss == Some(crate::loss::LossCode::DroppedGeometry) + && m.as_str() == "1 feature had an unreadable or non-finite geometry and is kept without geometry" + }), + "{lossy_report:?}" + ); + + let (clean_t, clean_x) = table(1, &[F::Oid, F::Shape { z: false, wkt: "" }], &[vec![V::Blob(pt)]]); + let (clean_ds, clean_report) = read_table("clean", &clean_t, &clean_x, None).unwrap().unwrap(); + assert_eq!(clean_ds.features.len(), 1); + assert!(clean_ds.features[0].geometry.is_some()); + assert_eq!(clean_report.skipped, 0); + assert!(!clean_report.messages.iter().any(|m| m.loss == Some(crate::loss::LossCode::DroppedGeometry)), "{clean_report:?}"); } #[test] From 87d0ebeebe8246ba31448a5302e39ea9e99cb609 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 12:31:14 -0500 Subject: [PATCH 08/14] Address Claude review feedback - Clarify the OSM PBF node text-budget notice from "(tags dropped in points)" to "(left out of points)" since tagged nodes past the budget are omitted from the points layer while keeping their positions for ways, and update the two test assertions to match. --- crates/data/src/osm.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 4c203b1655..ebd57e4f65 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -967,7 +967,7 @@ fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Res let mut parts = Vec::new(); if osm.text_capped_nodes > 0 { let n = osm.text_capped_nodes; - parts.push(format!("{n} {} (tags dropped in points)", if n == 1 { "tagged node" } else { "tagged nodes" })); + parts.push(format!("{n} {} (left out of points)", if n == 1 { "tagged node" } else { "tagged nodes" })); } if osm.text_capped_ways > 0 { let n = osm.text_capped_ways; @@ -1739,7 +1739,7 @@ pub(crate) mod tests { assert_eq!( note.as_str(), format!( - "OSM tag/role text reached the 1800-byte limit: 9 tagged nodes (tags dropped in points), 1 tagged way (omitted from lines/multipolygons), 1 relation (omitted from multipolygons) ({expected_bytes} bytes of text left out)" + "OSM tag/role text reached the 1800-byte limit: 9 tagged nodes (left out of points), 1 tagged way (omitted from lines/multipolygons), 1 relation (omitted from multipolygons) ({expected_bytes} bytes of text left out)" ) ); @@ -1899,7 +1899,7 @@ pub(crate) mod tests { .iter() .find(|m| m.loss == Some(crate::loss::LossCode::DroppedOverLimit)) .expect("node cap notice must be emitted"); - assert!(note.contains("9 tagged nodes (tags dropped in points)"), "{note:?}"); + assert!(note.contains("9 tagged nodes (left out of points)"), "{note:?}"); assert!(!note.contains("tagged way") && !note.contains("relation"), "{note:?}"); } } From e88603cb5322d717fedb908867b82e2be432095f Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 17:56:28 -0500 Subject: [PATCH 09/14] Address review: exact whole-number text in min/max, drop unused to_wkt_csv_reporting, clearer OSM notice min and max now compare whole-number text exactly as i64, as they do integers. to_wkt_csv_reporting had no caller; the notice comes from export_losses_notes. The OSM text-limit notice says its byte count includes per-entry overhead. --- crates/data/src/interop.rs | 12 ++---------- crates/data/src/osm.rs | 6 +++--- crates/data/src/query.rs | 9 ++++++++- crates/data/src/query/tests.rs | 3 +++ 4 files changed, 16 insertions(+), 14 deletions(-) diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index 8ecb69231f..33e777fc7a 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -636,13 +636,6 @@ pub fn to_wkt_csv(ds: &Dataset) -> crate::Result { text(out) } -/// As [`to_wkt_csv`], also returning how many field names were prefixed with an apostrophe to -/// guard against spreadsheet formula evaluation. -pub fn to_wkt_csv_reporting(ds: &Dataset) -> crate::Result<(String, usize)> { - let guarded_headers = ds.fields.iter().filter(|f| crate::io::csv_needs_guard(&f.name)).count(); - Ok((to_wkt_csv(ds)?, guarded_headers)) -} - /// [`to_wkt_csv`]'s text, written to `out` as it is made. Field names and text cells that start /// like a spreadsheet formula take an apostrophe, as in plain CSV. pub(crate) fn write_wkt_csv(ds: &Dataset, out: &mut impl Write) -> crate::Result<()> { @@ -758,8 +751,7 @@ mod tests { Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Text("\t=1".into()), Value::Text("ok".into()), Value::Text("+0123".into()), Value::Int(-1_234_567_890_123_456)], ); - let (csv, guarded_headers) = to_wkt_csv_reporting(&ds).unwrap(); - assert_eq!(guarded_headers, 3); + let csv = to_wkt_csv(&ds).unwrap(); let header_line = csv.lines().next().unwrap_or(""); assert_eq!(header_line, "wkt,'=1+1,\"'=HYPERLINK(\"\"https://example.com\"\",\"\"x\"\")\",'+0123,big_id"); assert!(csv.contains("'\t=1,ok,'+0123,-1234567890123456\n"), "text guarded, integer unguarded: {csv}"); @@ -788,7 +780,7 @@ mod tests { // Clean dataset produces zero guard notices. let mut clean = Dataset::new("clean", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); clean.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Text("Paris".into())]); - assert_eq!(to_wkt_csv_reporting(&clean).unwrap().1, 0); + assert!(!to_wkt_csv(&clean).unwrap().contains('\'')); assert!(crate::io::export_losses_notes(&clean, "wkt", None, "clean.csv").unwrap().is_empty()); assert!(crate::io::export_losses_notes(&clean, "csv", None, "clean.csv").unwrap().is_empty()); diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index ebd57e4f65..72da78d212 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -978,7 +978,7 @@ fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Res parts.push(format!("{n} {} (omitted from multipolygons)", if n == 1 { "relation" } else { "relations" })); } format!( - "OSM tag/role text reached the {}-byte limit: {} ({} bytes of text left out)", + "OSM tag/role text reached the {}-byte limit: {} ({} bytes of text and per-entry overhead left out)", osm.text_limit, parts.join(", "), osm.text_capped_bytes, @@ -1739,7 +1739,7 @@ pub(crate) mod tests { assert_eq!( note.as_str(), format!( - "OSM tag/role text reached the 1800-byte limit: 9 tagged nodes (left out of points), 1 tagged way (omitted from lines/multipolygons), 1 relation (omitted from multipolygons) ({expected_bytes} bytes of text left out)" + "OSM tag/role text reached the 1800-byte limit: 9 tagged nodes (left out of points), 1 tagged way (omitted from lines/multipolygons), 1 relation (omitted from multipolygons) ({expected_bytes} bytes of text and per-entry overhead left out)" ) ); @@ -1821,7 +1821,7 @@ pub(crate) mod tests { assert_eq!( note.as_str(), format!( - "OSM tag/role text reached the 3000-byte limit: 1 tagged way (omitted from lines/multipolygons) ({expected} bytes of text left out)" + "OSM tag/role text reached the 3000-byte limit: 1 tagged way (omitted from lines/multipolygons) ({expected} bytes of text and per-entry overhead left out)" ) ); } diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index b95d200e9d..ba0044c64c 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -2386,8 +2386,15 @@ impl<'a> Eval<'a> { let better = match &best { None => true, Some((b, bv)) => { + // Whole numbers, as integers or as text, compare exactly: through + // f64, neighbours above 2^53 would be equal. + let whole = |v: &Value| match v { + Value::Int(i) => Some(*i), + Value::Text(t) => t.trim().parse::().ok(), + _ => None, + }; let ord = match (&*v, &**bv) { - (Value::Int(i), Value::Int(j)) => i.cmp(j), + _ if whole(&v).is_some() && whole(bv).is_some() => whole(&v).cmp(&whole(bv)), (Value::Int(_), _) | (_, Value::Int(_)) => { v.partial_cmp(bv).unwrap_or_else(|| x.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) } diff --git a/crates/data/src/query/tests.rs b/crates/data/src/query/tests.rs index 8b7df0f159..90863ecd27 100644 --- a/crates/data/src/query/tests.rs +++ b/crates/data/src/query/tests.rs @@ -977,6 +977,9 @@ fn min_and_max_report_non_number_faults_and_keep_i64_precision() { assert_eq!(run("max(a, b)"), (Value::Int(9_007_199_254_740_993), None)); assert_eq!(run("min(b, a)"), (Value::Int(9_007_199_254_740_992), None)); assert_eq!(run("min('2', '10')"), (Value::Text("2".into()), None)); + // Whole-number text above 2^53 compares exactly too. + assert_eq!(run("min('9007199254740993', '9007199254740992')"), (Value::Text("9007199254740992".into()), None)); + assert_eq!(run("max('9007199254740992', '9007199254740993')"), (Value::Text("9007199254740993".into()), None)); } #[test] From 6dd02d2009bebe92e89422d609f210a1e851b750 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 19:02:33 -0500 Subject: [PATCH 10/14] Walk LandXML surface children without a temporary Vec per element --- crates/data/src/landxml.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index 91ccc629b4..9f695caa6a 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -45,8 +45,7 @@ fn elements<'a, 'i>(n: &Node<'a, 'i>, name: &'static str) -> impl Iterator(s: &Node<'a, 'i>) -> Result<(Vec>, Vec>)> { let (mut pts, mut fcs) = (Vec::new(), Vec::new()); - let mut stack: Vec> = s.children().collect(); - stack.reverse(); + let mut stack: Vec> = s.children().rev().collect(); let mut visited = 0usize; while let Some(node) = stack.pop() { if visited.is_multiple_of(1024) { @@ -62,9 +61,7 @@ fn surface_nodes<'a, 'i>(s: &Node<'a, 'i>) -> Result<(Vec>, Vec fcs.push(node), _ => {} } - let mut children: Vec> = node.children().collect(); - children.reverse(); - stack.extend(children); + stack.extend(node.children().rev()); } Ok((pts, fcs)) } From 0c55841d620609e732394cd669d82c61a185023a Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 19:42:36 -0500 Subject: [PATCH 11/14] Size the OSM tag text budget from the file, not a fixed 256 MiB Measured on Geofabrik extracts, real files hold 3.5 to 7.5 times their size in tag text with per-entry overhead (Berlin, 100 MB: 721 MiB), so the fixed budget dropped tags from ordinary extracts. The budget is now 24 times the file size, between 256 MiB and 4 GiB (64 MiB and 1 GiB in the browser). --- crates/data/src/osm.rs | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 72da78d212..071b3640b3 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -24,10 +24,25 @@ const MAX_MEMBERS: usize = 100_000; const MAX_WAYS: usize = MAX_NODES / 4; const MAX_REFS: usize = MAX_NODES * 2; const MAX_RELATIONS: usize = MAX_NODES / 40; -/// The most decoded tag and role text bytes kept across an OSM PBF file: a small compressed block -/// can repeat one string-table entry across thousands of entities. Split across nodes, ways and -/// relations so heavy tags on one kind cannot starve the others. -const MAX_TEXT_BYTES: usize = if cfg!(target_arch = "wasm32") { 64 << 20 } else { 256 << 20 }; +/// The decoded tag and role text bytes kept across an OSM PBF file, as a multiple of the file's +/// size: a small compressed block can repeat one string-table entry across thousands of entities. +/// Real extracts hold about 3.5 to 7.5 times their size (Geofabrik's Luxembourg, 48 MB: 167 MiB, +/// 116 MiB of it on ways; Berlin, 100 MB: 721 MiB, 393 MiB on ways, per-entry overhead included), +/// so 24 times leaves the busiest kind, ways, about twice what Berlin needs of its third. +/// Split across nodes, ways and relations so heavy tags on one kind cannot starve the others. +const TEXT_BYTES_PER_FILE_BYTE: usize = 24; +/// The text budget's floor (a small file still reads whole) and ceiling, within the memory the +/// node and way caps already allow. +const MIN_TEXT_BYTES: usize = if cfg!(target_arch = "wasm32") { 64 << 20 } else { 256 << 20 }; +#[cfg(target_arch = "wasm32")] +const MAX_TEXT_BYTES: usize = 1 << 30; +#[cfg(not(target_arch = "wasm32"))] +const MAX_TEXT_BYTES: usize = 4 << 30; + +/// The tag and role text budget of a file of `len` bytes ([`TEXT_BYTES_PER_FILE_BYTE`]). +fn text_limit_for(len: usize) -> usize { + len.saturating_mul(TEXT_BYTES_PER_FILE_BYTE).clamp(MIN_TEXT_BYTES, MAX_TEXT_BYTES) +} /// Per-tag overhead (one `(String, String)` entry) charged beside key/value text bytes so /// zero-length `("", "")` tag pairs from string-table index 0 cannot allocate unbounded entries. const TAG_OVERHEAD: usize = 48; @@ -778,7 +793,7 @@ fn inside(p: Coord, ring: &[Coord]) -> bool { /// between blocks and between the ways and relations built from them; decoding one block is one /// step without a look. pub fn read(file_name: &str, bytes: &[u8]) -> Result> { - read_with_text_limit(file_name, bytes, MAX_TEXT_BYTES) + read_with_text_limit(file_name, bytes, text_limit_for(bytes.len())) } fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Result> { @@ -1902,4 +1917,19 @@ pub(crate) mod tests { assert!(note.contains("9 tagged nodes (left out of points)"), "{note:?}"); assert!(!note.contains("tagged way") && !note.contains("relation"), "{note:?}"); } + + /// The text budget follows the file's size between its floor and ceiling, so an ordinary + /// extract (Berlin's 100 MB holds 721 MiB of tag text) keeps its tags. + #[test] + fn text_budget_follows_the_file_size() { + assert_eq!(text_limit_for(0), MIN_TEXT_BYTES); + assert_eq!(text_limit_for(1 << 20), MIN_TEXT_BYTES); + assert_eq!(text_limit_for(usize::MAX), MAX_TEXT_BYTES); + if cfg!(not(target_arch = "wasm32")) { + let berlin = text_limit_for(100_000_000); + assert_eq!(berlin, 2_400_000_000); + // Each kind's third is above the 393 MiB Berlin's ways need. + assert!(berlin / 3 > 393 << 20); + } + } } From 395c988ec23081b1d67156d914f347072c4a0fb4 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 20:30:34 -0500 Subject: [PATCH 12/14] Cap the OSM text budget at the computer's planned share, by pointer width The ceiling now comes from memory::planned (at most 4 GiB on 64-bit, 1 GiB on 32-bit builds), so it follows the memory the machine has; the browser, which doesn't say its memory, keeps the fixed ceiling. --- crates/data/src/osm.rs | 41 ++++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 071b3640b3..169ef1b18f 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -31,17 +31,31 @@ const MAX_RELATIONS: usize = MAX_NODES / 40; /// so 24 times leaves the busiest kind, ways, about twice what Berlin needs of its third. /// Split across nodes, ways and relations so heavy tags on one kind cannot starve the others. const TEXT_BYTES_PER_FILE_BYTE: usize = 24; -/// The text budget's floor (a small file still reads whole) and ceiling, within the memory the -/// node and way caps already allow. +/// The text budget's floor (a small file still reads whole) and its most: 4 GiB on a 64-bit +/// build, 1 GiB where `usize` is 32 bits (the browser, a 32-bit phone). const MIN_TEXT_BYTES: usize = if cfg!(target_arch = "wasm32") { 64 << 20 } else { 256 << 20 }; -#[cfg(target_arch = "wasm32")] +#[cfg(not(target_pointer_width = "64"))] const MAX_TEXT_BYTES: usize = 1 << 30; -#[cfg(not(target_arch = "wasm32"))] +#[cfg(target_pointer_width = "64")] const MAX_TEXT_BYTES: usize = 4 << 30; -/// The tag and role text budget of a file of `len` bytes ([`TEXT_BYTES_PER_FILE_BYTE`]). +/// The tag and role text budget of a file of `len` bytes: [`TEXT_BYTES_PER_FILE_BYTE`] times its +/// size, from [`MIN_TEXT_BYTES`] up to what this computer plans for one job +/// ([`crate::memory::planned`], at most [`MAX_TEXT_BYTES`]). The browser doesn't say its memory, +/// so there the ceiling is [`MAX_TEXT_BYTES`] itself, with [`MAX_NODES`] already smaller there. +/// What is past the budget is left out and said, with a smaller extract as the way out. fn text_limit_for(len: usize) -> usize { - len.saturating_mul(TEXT_BYTES_PER_FILE_BYTE).clamp(MIN_TEXT_BYTES, MAX_TEXT_BYTES) + let ceiling = if cfg!(target_arch = "wasm32") { + MAX_TEXT_BYTES + } else { + crate::memory::planned(MIN_TEXT_BYTES, MAX_TEXT_BYTES, 1) + }; + text_limit_within(len, ceiling) +} + +/// [`text_limit_for`] with a given `ceiling`. +fn text_limit_within(len: usize, ceiling: usize) -> usize { + len.saturating_mul(TEXT_BYTES_PER_FILE_BYTE).clamp(MIN_TEXT_BYTES, ceiling.max(MIN_TEXT_BYTES)) } /// Per-tag overhead (one `(String, String)` entry) charged beside key/value text bytes so /// zero-length `("", "")` tag pairs from string-table index 0 cannot allocate unbounded entries. @@ -1922,11 +1936,16 @@ pub(crate) mod tests { /// extract (Berlin's 100 MB holds 721 MiB of tag text) keeps its tags. #[test] fn text_budget_follows_the_file_size() { - assert_eq!(text_limit_for(0), MIN_TEXT_BYTES); - assert_eq!(text_limit_for(1 << 20), MIN_TEXT_BYTES); - assert_eq!(text_limit_for(usize::MAX), MAX_TEXT_BYTES); - if cfg!(not(target_arch = "wasm32")) { - let berlin = text_limit_for(100_000_000); + assert_eq!(text_limit_within(0, MAX_TEXT_BYTES), MIN_TEXT_BYTES); + assert_eq!(text_limit_within(1 << 20, MAX_TEXT_BYTES), MIN_TEXT_BYTES); + assert_eq!(text_limit_within(usize::MAX, MAX_TEXT_BYTES), MAX_TEXT_BYTES); + // The computer's share caps it, never below the floor. + assert_eq!(text_limit_within(100_000_000, 1 << 30), 1 << 30); + assert_eq!(text_limit_within(100_000_000, 0), MIN_TEXT_BYTES); + let planned = text_limit_for(usize::MAX); + assert!((MIN_TEXT_BYTES..=MAX_TEXT_BYTES).contains(&planned), "{planned}"); + if cfg!(target_pointer_width = "64") { + let berlin = text_limit_within(100_000_000, MAX_TEXT_BYTES); assert_eq!(berlin, 2_400_000_000); // Each kind's third is above the 393 MiB Berlin's ways need. assert!(berlin / 3 > 393 << 20); From 1781201ced8720fee2a41da412fbc88630fb31cc Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 20:48:43 -0500 Subject: [PATCH 13/14] cargo fmt --- crates/data/src/osm.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 169ef1b18f..7a68ca1354 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -45,11 +45,7 @@ const MAX_TEXT_BYTES: usize = 4 << 30; /// so there the ceiling is [`MAX_TEXT_BYTES`] itself, with [`MAX_NODES`] already smaller there. /// What is past the budget is left out and said, with a smaller extract as the way out. fn text_limit_for(len: usize) -> usize { - let ceiling = if cfg!(target_arch = "wasm32") { - MAX_TEXT_BYTES - } else { - crate::memory::planned(MIN_TEXT_BYTES, MAX_TEXT_BYTES, 1) - }; + let ceiling = if cfg!(target_arch = "wasm32") { MAX_TEXT_BYTES } else { crate::memory::planned(MIN_TEXT_BYTES, MAX_TEXT_BYTES, 1) }; text_limit_within(len, ceiling) } From b392abccbd1a4152919b49f083cb4ecd3b3700cb Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 21:19:22 -0500 Subject: [PATCH 14/14] Say an inverted byte range as well as an overflowing one --- apps/rustgis-web/src/web.rs | 2 +- crates/tiles/src/cache.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 809950defe..29bf592147 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -770,7 +770,7 @@ async fn fetch_reached( if let Some((a, b)) = range && cache::range_len(a, b).is_none() { - return Err("byte range length overflows".into()); + return Err("byte range is inverted or its length overflows".into()); } // Share native GET routing: explicit service logins outrank implicit S3 endpoint signing. let bound = url; diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index 99d367b598..fc7d01e933 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -3730,7 +3730,7 @@ mod native { if let Some((a, b)) = range && super::range_len(a, b).is_none() { - return Err("byte range length overflows".into()); + return Err("byte range is inverted or its length overflows".into()); } // The last bytes asked for, while the file's length is asked for instead (see below). let mut measuring: Option = None; @@ -3935,7 +3935,7 @@ mod native { return Err(format!("larger than {max} bytes").into()); } if let Some((a, b)) = range.filter(|_| whole) { - let len = super::range_len(a, b).ok_or("byte range length overflows")?; + let len = super::range_len(a, b).ok_or("byte range is inverted or its length overflows")?; if buf.len() as u64 > len { return Err(rustgis_data::diagnostics::message_with_address(url, super::NO_RANGES).into()); }