Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 111 additions & 15 deletions crates/data/src/source/gpkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,7 @@ fn fill(
feed: &mut dyn FnMut(&mut dyn FnMut(&[crate::Feature]) -> Result<()>) -> Result<()>,
) -> Result<std::result::Result<(Layout, Extent), Redo>> {
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(_)))));
Expand All @@ -822,7 +823,7 @@ 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())),
Expand All @@ -837,6 +838,7 @@ fn fill(
Some(l) => l,
None => make(multi_points.unwrap_or(false), mixed)?,
};
fill_index(conn, &layout, &mut boxes)?;
Ok(Ok((layout, extent)))
}
}
Expand Down Expand Up @@ -913,9 +915,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)
}
Expand Down Expand Up @@ -1092,23 +1096,28 @@ 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<Option<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, 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`].
fn insert(
conn: &Connection,
layout: &Layout,
features: &[crate::Feature],
keep_ids: bool,
boxes: &mut Vec<IndexBox>,
) -> Result<Option<Redo>> {
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<String> =
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) {
Expand Down Expand Up @@ -1142,13 +1151,100 @@ 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] });
Comment on lines +1154 to +1155

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The streamed path can hold about twice the 96 MB this PR documents. fill checks boxes.len() >= INDEX_BATCH only after a whole feed chunk (up to 32 MB of feature storage, so possibly hundreds of thousands of boxes) has been pushed. A chunk that crosses 2^21 boxes makes Vec double its capacity to 2^22, which is 192 MiB held for the rest of the export, and the realloc briefly holds about 288 MiB (96 + 192). The 96 MB bound in INDEX_BATCH's doc and in the PR body therefore doesn't hold for any streamed export with more than about 2M placed features. I haven't measured it; the mechanics are standard Vec growth, so confidence is medium-high.

A fix that keeps the capacity at 2^21: flush from inside insert when the batch fills exactly, so the length never passes it. Then the None if boxes.len() >= INDEX_BATCH => fill_index(...) arm in fill (line 830) can be removed.

Suggested change
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] });
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] });
if boxes.len() == INDEX_BATCH {
fill_index(conn, layout, boxes)?;
}
}

Category: performance

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5ebbc33: insert loads the boxes the moment the batch fills, so the vector never passes INDEX_BATCH (capacity stays 2^21, 96 MB), and the check in fill is gone. A whole-layer export now batches the same way, so a streamed export again gives the file write_in would.

// 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
/// (`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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nits, grouped:

  • key is written as 0 in insert and only filled in by fill_index. Computing it in fill_index (or keeping keys in a parallel vector) would stop a half-built value from existing.
  • fill_index's doc says it looks at Cancel as it goes, but the Hilbert pass and the sort over up to 2^21 boxes have no check. They're short, but AGENTS.md asks for such steps to be named in the doc comment.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both in 5ebbc33: IndexBox's doc says key is 0 until fill_index works it out from the batch's extent (it needs the whole batch's extent, so it can't be set at insert), and fill_index's doc names the Hilbert pass and the sort as steps without a Cancel check, each over at most one batch.

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 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 };

/// 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing in this PR tests hilbert or the batch ordering. The tests check membership, the box of each entry, and that a second write matches, but a wrong curve (or a sort on the wrong key) would still pass them, since the file stays valid and only the R-tree build speed changes. A small unit test with fixed expected values would pin it down, for example on a 2x2 grid: hilbert(0,0)=0, hilbert(0,1)=1, hilbert(1,1)=2, hilbert(1,0)=3, plus one larger point checked by hand. That is a test for code that already works, so it is a quality point.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass.

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, 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<IndexBox>) -> 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<i64>) -> Result<()> {
register(conn, layout, extent, pinned, None)?;
Expand Down
138 changes: 138 additions & 0 deletions crates/data/src/source/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>)> = 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).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doc says the multipoint case restarts the export, but the test never reaches the restart. gpkg::write (build) and the add-table path (add::write_features, single feed call) both choose the table's multipoint type from all the features, so the multi case gets a MULTIPOINT table from the start and Redo::MultiPoints never fires. The restart path is only reached by a streamed feed whose first chunk has no multipoint, and no test in this PR covers that for the index. Suggest either feeding the layer in chunks through write_features_in in this test (so the restart happens and the index is checked after it), or dropping the restart clause from the doc.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass.

#[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<i64> {
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<Option<Geometry>>| {
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<u8>)>) {
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<i64> = (1..=2500).filter(|i| (i - 1) % 10 != 0).collect();
assert_eq!(rows.iter().map(|r| r.0).collect::<Vec<_>>(), placed, "one entry for each feature with a place");
assert_eq!(nodes, read(&files[1]).1, "the same layer builds the same index");
}
Loading