From a1f922d81102343276e64c7c08a9fa4a07f067f2 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 15:13:11 -0600 Subject: [PATCH 1/2] perf(data): GeoPackage export fills the spatial index after the rows, in Hilbert order The export put each feature's box into the table's R-tree as it wrote the row. SQLite's R-tree walks down from the root to pick a leaf for every entry, which costs more when consecutive entries lie all over the map than when neighbours arrive together. The boxes are now kept as the rows go in and loaded once at the end, ordered by the Hilbert index of their centres, ties by row id, so the same layer still gives the same file. They cost 48 bytes for each feature that has a place; a streamed export that has kept 2,097,152 of them (96 MB) loads them and starts over, so memory doesn't grow with the layer. The load looks at Cancel every 8192 entries. The table, its rows and the triggers (added after, as before) are unchanged. --- crates/data/src/source/gpkg.rs | 119 +++++++++++++++++++++++---- crates/data/src/source/tests.rs | 138 ++++++++++++++++++++++++++++++++ 2 files changed, 242 insertions(+), 15 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index ee2f8c2272..774d8e3c3f 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -813,6 +813,7 @@ fn fill( feed: &mut dyn FnMut(&mut dyn FnMut(&[crate::Feature]) -> Result<()>) -> Result<()>, ) -> Result> { let (mut layout, mut extent, mut redo) = (None, Extent::EMPTY, None); + let mut boxes = Vec::new(); let fed = feed(&mut |features| { if layout.is_none() { let multi = multi_points.unwrap_or_else(|| features.iter().any(|f| matches!(f.geometry, Some(crate::Geometry::MultiPoint(_))))); @@ -822,10 +823,11 @@ fn fill( for g in features.iter().filter_map(|f| f.geometry.as_ref()) { extent = extent.union(&g.extent()); } - redo = insert(conn, l, features, keep_ids)?; + redo = insert(conn, l, features, keep_ids, &mut boxes)?; match redo { // Stops the traversal; the export starts again. Some(_) => Err(DataError::Format("GeoPackage: starting again".into())), + None if boxes.len() >= INDEX_BATCH => fill_index(conn, l, &mut boxes), None => Ok(()), } }); @@ -837,6 +839,7 @@ fn fill( Some(l) => l, None => make(multi_points.unwrap_or(false), mixed)?, }; + fill_index(conn, &layout, &mut boxes)?; Ok(Ok((layout, extent))) } } @@ -913,9 +916,11 @@ fn build(conn: &Connection, ds: &crate::Dataset, name: &str, crs: Crs, pinned: O let keep_ids = ds.features.iter().all(|f| i64::try_from(f.id).is_ok() && seen.insert(f.id)); // The table is made for the whole layer, so nothing should need doing again; should a // feature not fit after all, the export fails rather than leave it out. - if insert(conn, &layout, &ds.features, keep_ids)?.is_some() { + let mut boxes = Vec::new(); + if insert(conn, &layout, &ds.features, keep_ids, &mut boxes)?.is_some() { return Err(DataError::Format("GeoPackage: a feature doesn't fit the table chosen for the layer".into())); } + fill_index(conn, &layout, &mut boxes)?; finish(conn, &layout, ds.extent(), pinned)?; Ok(layout.table) } @@ -1092,23 +1097,27 @@ enum Redo { Renumber, } -/// Inserts features into the table [`create`] made, and their boxes into its spatial index. -/// With `keep_ids` each keeps its id; otherwise SQLite numbers it. Stops at the first feature -/// the table as made can't hold as the whole layer would have it (a multipoint in a POINT -/// table, geometry of another kind, an id that doesn't fit or is taken), saying what to -/// [`Redo`]. -fn insert(conn: &Connection, layout: &Layout, features: &[crate::Feature], keep_ids: bool) -> Result> { +/// Inserts features into the table [`create`] made, and puts the box of each one with a place in +/// `boxes` for [`fill_index`] to load. With `keep_ids` each keeps its id; +/// otherwise SQLite numbers it. Stops at the first feature the table as made can't hold as the +/// whole layer would have it (a multipoint in a POINT table, geometry of another kind, an id +/// that doesn't fit or is taken), saying what to [`Redo`]. +fn insert( + conn: &Connection, + layout: &Layout, + features: &[crate::Feature], + keep_ids: bool, + boxes: &mut Vec, +) -> Result> { use rusqlite::types::Value as Sql; - let Layout { columns, fields, has_geom, multi_points, srs_id, table_q: t, geom_q: g, fid_q: i, rtree_q: rt, .. } = layout; + let Layout { columns, fields, has_geom, multi_points, srs_id, table_q: t, geom_q: g, fid_q: i, .. } = layout; let (has_geom, multi_points, srs_id) = (*has_geom, *multi_points, *srs_id); let names: Vec = std::iter::once(i.clone()).chain(has_geom.then(|| g.clone())).chain(columns.iter().map(|c| quote(c))).collect(); let marks = vec!["?"; names.len()].join(", "); let mut st = conn.prepare_cached(&format!("INSERT INTO {t} ({}) VALUES ({marks})", names.join(", "))).map_err(err)?; - // The spatial index is filled here; its triggers (which call functions only GeoPackage - // software defines) are created after. - let mut index = - if has_geom { Some(conn.prepare_cached(&format!("INSERT INTO {rt} VALUES (?1, ?2, ?3, ?4, ?5)")).map_err(err)?) } else { None }; + // The spatial index is filled after the rows ([`fill_index`]); its triggers (which call + // functions only GeoPackage software defines) are created after that. for f in features { crate::progress::step(1)?; if has_geom && !layout.mixed && other_kind(f, layout.kind) { @@ -1142,13 +1151,93 @@ fn insert(conn: &Connection, layout: &Layout, features: &[crate::Feature], keep_ Err(e) => return Err(err(e)), } let e = f.geometry.as_ref().map(|x| x.extent()).unwrap_or(Extent::EMPTY); - if let (Some(ix), false) = (index.as_mut(), e.is_empty()) { - ix.execute(rusqlite::params![conn.last_insert_rowid(), e.min_x, e.max_x, e.min_y, e.max_y]).map_err(err)?; + if has_geom && !e.is_empty() { + boxes.push(IndexBox { key: 0, id: conn.last_insert_rowid(), bounds: [e.min_x, e.max_x, e.min_y, e.max_y] }); } } Ok(None) } +/// A feature's box waiting to go into the spatial index, with its place along the Hilbert curve. +/// It holds 48 bytes per feature that has a place, until [`fill_index`] loads it. +struct IndexBox { + key: u64, + id: i64, + /// `[min_x, max_x, min_y, max_y]`, the order of the index's columns. + bounds: [f64; 4], +} + +/// How many boxes [`fill_index`] loads between looks at Cancel. +const INDEX_CHECK_EVERY: usize = 8192; + +/// How many boxes a streamed export keeps before it loads them (96 MB at 48 bytes each), so a +/// layer of any size needs no more; a layer of fewer features is loaded in one go at the end. +/// Each load is in Hilbert order within itself. +/// (1,000 in this crate's tests, so they reach a second load.) +const INDEX_BATCH: usize = if cfg!(test) { 1000 } else { 1 << 21 }; + +/// The distance along a Hilbert curve of 2^16 by 2^16 cells at which the cell `(x, y)` lies. +fn hilbert(mut x: u32, mut y: u32) -> u64 { + const SIDE: u32 = 1 << 16; + let mut d = 0u64; + let mut s = SIDE >> 1; + while s > 0 { + let (rx, ry) = (u32::from(x & s != 0), u32::from(y & s != 0)); + d += u64::from(s) * u64::from(s) * u64::from((3 * rx) ^ ry); + if ry == 0 { + if rx == 1 { + x = SIDE - 1 - x; + y = SIDE - 1 - y; + } + std::mem::swap(&mut x, &mut y); + } + s >>= 1; + } + d +} + +/// Fills the table's spatial index with `boxes`, one entry for each, in Hilbert order of their +/// centres. SQLite's R-tree picks a leaf for each entry by walking down from the root, which costs +/// far more when consecutive entries lie all over the map than when neighbours arrive together. +/// Ties fall back to the row id, so the same layer gives the same file each time. Empties `boxes`. +/// Looks at Cancel as it goes, but not within one SQLite insert. +fn fill_index(conn: &Connection, layout: &Layout, boxes: &mut Vec) -> Result<()> { + if !layout.has_geom || boxes.is_empty() { + return Ok(()); + } + let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for b in boxes.iter() { + for (axis, (a, z)) in [(0, 1), (2, 3)].into_iter().enumerate() { + let centre = (b.bounds[a] + b.bounds[z]) / 2.0; + if centre.is_finite() { + lo[axis] = lo[axis].min(centre); + hi[axis] = hi[axis].max(centre); + } + } + } + let cell = |v: f64, axis: usize| { + let span = hi[axis] - lo[axis]; + // A NaN or an empty span lands in the first cell. + if span > 0.0 { (((v - lo[axis]) / span) * 65535.0).clamp(0.0, 65535.0) as u32 } else { 0 } + }; + for b in boxes.iter_mut() { + let [x0, x1, y0, y1] = b.bounds; + b.key = hilbert(cell((x0 + x1) / 2.0, 0), cell((y0 + y1) / 2.0, 1)); + } + crate::progress::check()?; + boxes.sort_unstable_by_key(|b| (b.key, b.id)); + let mut index = conn.prepare_cached(&format!("INSERT INTO {} VALUES (?1, ?2, ?3, ?4, ?5)", layout.rtree_q)).map_err(err)?; + for (n, b) in boxes.iter().enumerate() { + if n % INDEX_CHECK_EVERY == 0 { + crate::progress::check()?; + } + let [min_x, max_x, min_y, max_y] = b.bounds; + index.execute(rusqlite::params![b.id, min_x, max_x, min_y, max_y]).map_err(err)?; + } + boxes.clear(); + Ok(()) +} + /// [`register`]s the table, in a new file, and commits. fn finish(conn: &Connection, layout: &Layout, extent: Extent, pinned: Option) -> Result<()> { register(conn, layout, extent, pinned, None)?; diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 4967df9cd2..47de6aee0e 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5038,3 +5038,141 @@ fn write_projected_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, dicti writer.write(&batch).unwrap(); writer.close().unwrap(); } + +/// The spatial index, loaded after the rows in Hilbert order, holds one entry with the box of +/// each feature that has a place (none for one without), and the same layer gives the same index +/// nodes each time. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn geopackage_index_holds_each_placed_feature_and_repeats() { + let folder = tempfile::tempdir().unwrap(); + let mut ds = Dataset::new("scatter", GeometryType::Point, vec![]); + let mut seed = 12345u64; + let mut next = move || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as f64 / f64::from(1u32 << 31) + }; + let mut places = Vec::new(); + for _ in 0..3000 { + let c = Coord::new(next() * 360.0 - 180.0, next() * 170.0 - 85.0); + places.push(c); + ds.push(Some(Geometry::Point(c)), vec![]); + } + ds.push(None, vec![]); + let mut nodes = Vec::new(); + for name in ["a.gpkg", "b.gpkg"] { + let path = folder.path().join(name); + gpkg::write(&ds, &path).unwrap(); + let c = rusqlite::Connection::open(&path).unwrap(); + let mut st = c.prepare("SELECT id, minx, maxx, miny, maxy FROM rtree_scatter_geom ORDER BY id").unwrap(); + let rows: Vec<(i64, [f64; 4])> = + st.query_map([], |r| Ok((r.get(0)?, [r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?]))).unwrap().map(|r| r.unwrap()).collect(); + assert_eq!(rows.len(), places.len(), "one entry for each feature with a place"); + for ((id, [x0, x1, y0, y1]), p) in rows.iter().zip(&places) { + let sane = (*x0 as f32 as f64 - p.x).abs() < 1e-4 && (*x1 as f32 as f64 - p.x).abs() < 1e-4; + assert!(sane && (*y0 as f32 as f64 - p.y).abs() < 1e-4 && (*y1 as f32 as f64 - p.y).abs() < 1e-4, "box of {id}"); + } + let nodes_of: Vec<(i64, Vec)> = c + .prepare("SELECT nodeno, data FROM rtree_scatter_geom_node ORDER BY nodeno") + .unwrap() + .query_map([], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + nodes.push(nodes_of); + let triggers: i64 = c + .query_row("SELECT count(*) FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'rtree_scatter_geom_%'", [], |r| r.get(0)) + .unwrap(); + assert_eq!(triggers, 7, "the index's triggers exist when the write ends"); + } + assert_eq!(nodes[0], nodes[1], "the same layer builds the same index"); +} + +/// The spatial index of a GeoPackage lists exactly the features with a place, for a layer with +/// none, one of only null and empty geometries, a table added to a file that has another, and one +/// replaced there (and a point layer that turns out to hold multipoints, which restarts the export). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn geopackage_index_lists_only_features_with_a_place() { + use crate::io::{GpkgMode, GpkgTable}; + let folder = tempfile::tempdir().unwrap(); + let indexed = |path: &Path, table: &str| -> Vec { + let c = rusqlite::Connection::open(path).unwrap(); + let mut st = c.prepare(&format!("SELECT id FROM rtree_{table}_geom ORDER BY id")).unwrap(); + st.query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect() + }; + let layer = |name: &str, geoms: Vec>| { + let mut ds = Dataset::new(name, GeometryType::Point, vec![]); + for g in geoms { + ds.push(g, vec![]); + } + ds + }; + let at = |x: f64| Some(Geometry::Point(Coord::new(x, -x))); + for (name, geoms, want) in [ + ("empty", vec![], vec![]), + ("none", vec![None, None], vec![]), + ("empty_multi", vec![None, Some(Geometry::MultiPoint(vec![]))], vec![]), + ("some", vec![at(3.0), None, at(1.0), Some(Geometry::MultiPoint(vec![])), at(2.0)], vec![1, 3, 5]), + ( + "multi", + vec![at(3.0), None, Some(Geometry::MultiPoint(vec![Coord::new(1.0, 1.0), Coord::new(2.0, 2.0)])), at(2.0)], + vec![1, 3, 4], + ), + ] { + let path = folder.path().join(format!("{name}.gpkg")); + gpkg::write(&layer(name, geoms), &path).unwrap(); + assert_eq!(indexed(&path, name), want, "{name}"); + } + // A table added to a file that has another, then replaced by one with fewer features. + let path = folder.path().join("two.gpkg"); + let to = |mode, name: &str| GpkgTable { mode, name: Some(name.into()) }; + gpkg::write(&layer("first", vec![at(5.0), at(4.0)]), &path).unwrap(); + gpkg::write_table_in(&layer("x", vec![at(9.0), None, at(8.0), at(7.0)]), &path, Crs::LonLat, &to(GpkgMode::AddTable, "second")) + .unwrap(); + assert_eq!((indexed(&path, "first"), indexed(&path, "second")), (vec![1, 2], vec![1, 3, 4])); + gpkg::write_table_in(&layer("x", vec![None, at(6.0)]), &path, Crs::LonLat, &to(GpkgMode::ReplaceTable, "second")).unwrap(); + assert_eq!((indexed(&path, "first"), indexed(&path, "second")), (vec![1, 2], vec![2])); +} + +/// A streamed export loads the spatial index in several runs once it holds enough boxes: every +/// feature with a place is still indexed with its box, and the same layer builds the same index. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_streamed_geopackage_loads_its_index_in_runs() { + let folder = tempfile::tempdir().unwrap(); + let mut ds = Dataset::new("runs", GeometryType::Point, vec![]); + for i in 0..2500 { + let (x, y) = (f64::from((i * 7919) % 360) - 180.0, f64::from((i * 104_729) % 170) - 85.0); + ds.push((i % 10 != 0).then(|| Geometry::Point(Coord::new(x, y))), vec![]); + } + let mut files = Vec::new(); + for name in ["a.gpkg", "b.gpkg"] { + let path = folder.path().join(name); + let mut feed = |put: &mut dyn FnMut(&[crate::Feature]) -> crate::Result<()>| ds.features.chunks(400).try_for_each(&mut *put); + gpkg::write_features_in("runs", GeometryType::Point, &[], &path, Crs::LonLat, &crate::io::GpkgTable::default(), &mut feed).unwrap(); + files.push(path); + } + let read = |path: &Path| -> (Vec<(i64, [f64; 4])>, Vec<(i64, Vec)>) { + let c = rusqlite::Connection::open(path).unwrap(); + let rows = c + .prepare("SELECT id, minx, maxx, miny, maxy FROM rtree_runs_geom ORDER BY id") + .unwrap() + .query_map([], |r| Ok((r.get(0)?, [r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?]))) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + let nodes = c + .prepare("SELECT nodeno, data FROM rtree_runs_geom_node ORDER BY nodeno") + .unwrap() + .query_map([], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + (rows, nodes) + }; + let (rows, nodes) = read(&files[0]); + let placed: Vec = (1..=2500).filter(|i| (i - 1) % 10 != 0).collect(); + assert_eq!(rows.iter().map(|r| r.0).collect::>(), placed, "one entry for each feature with a place"); + assert_eq!(nodes, read(&files[1]).1, "the same layer builds the same index"); +} From 5ebbc33234a7ee6ecc83c71615f6fd17d73dd2e2 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 15:43:43 -0600 Subject: [PATCH 2/2] perf(data): the spatial index loads each batch as it fills, so it never grows past one Review: a streamed chunk crossing the batch made the box vector double to twice its documented size. Loading from insert keeps it at one batch and batches a whole-layer export the same way. Docs name the unchecked Hilbert pass and sort. --- crates/data/src/source/gpkg.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 774d8e3c3f..a82077fe3c 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -827,7 +827,6 @@ fn fill( match redo { // Stops the traversal; the export starts again. Some(_) => Err(DataError::Format("GeoPackage: starting again".into())), - None if boxes.len() >= INDEX_BATCH => fill_index(conn, l, &mut boxes), None => Ok(()), } }); @@ -1098,7 +1097,8 @@ enum Redo { } /// Inserts features into the table [`create`] made, and puts the box of each one with a place in -/// `boxes` for [`fill_index`] to load. With `keep_ids` each keeps its id; +/// `boxes` for [`fill_index`] to load, loading them whenever [`INDEX_BATCH`] are waiting; the +/// caller loads the rest at the end. With `keep_ids` each keeps its id; /// otherwise SQLite numbers it. Stops at the first feature the table as made can't hold as the /// whole layer would have it (a multipoint in a POINT table, geometry of another kind, an id /// that doesn't fit or is taken), saying what to [`Redo`]. @@ -1153,12 +1153,18 @@ fn insert( let e = f.geometry.as_ref().map(|x| x.extent()).unwrap_or(Extent::EMPTY); if has_geom && !e.is_empty() { boxes.push(IndexBox { key: 0, id: conn.last_insert_rowid(), bounds: [e.min_x, e.max_x, e.min_y, e.max_y] }); + // Loaded the moment a batch fills, so `boxes` never grows past one batch and a + // streamed export batches exactly as a whole-layer one does. + if boxes.len() == INDEX_BATCH { + fill_index(conn, layout, boxes)?; + } } } Ok(None) } -/// A feature's box waiting to go into the spatial index, with its place along the Hilbert curve. +/// A feature's box waiting to go into the spatial index, with its place along the Hilbert curve +/// (`key`, 0 until [`fill_index`] works it out from the whole batch's extent). /// It holds 48 bytes per feature that has a place, until [`fill_index`] loads it. struct IndexBox { key: u64, @@ -1170,8 +1176,8 @@ struct IndexBox { /// How many boxes [`fill_index`] loads between looks at Cancel. const INDEX_CHECK_EVERY: usize = 8192; -/// How many boxes a streamed export keeps before it loads them (96 MB at 48 bytes each), so a -/// layer of any size needs no more; a layer of fewer features is loaded in one go at the end. +/// How many boxes an export keeps before it loads them (96 MB at 48 bytes each), so a layer of +/// any size needs no more; a layer of fewer features is loaded in one go at the end. /// Each load is in Hilbert order within itself. /// (1,000 in this crate's tests, so they reach a second load.) const INDEX_BATCH: usize = if cfg!(test) { 1000 } else { 1 << 21 }; @@ -1200,7 +1206,8 @@ fn hilbert(mut x: u32, mut y: u32) -> u64 { /// centres. SQLite's R-tree picks a leaf for each entry by walking down from the root, which costs /// far more when consecutive entries lie all over the map than when neighbours arrive together. /// Ties fall back to the row id, so the same layer gives the same file each time. Empties `boxes`. -/// Looks at Cancel as it goes, but not within one SQLite insert. +/// Looks at Cancel as it goes, but not within one SQLite insert, nor while it works out the +/// Hilbert places and sorts them (one pass and one sort over at most [`INDEX_BATCH`] boxes). fn fill_index(conn: &Connection, layout: &Layout, boxes: &mut Vec) -> Result<()> { if !layout.has_geom || boxes.is_empty() { return Ok(());