diff --git a/CHANGELOG.md b/CHANGELOG.md index d03c2c03..1c04ad73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,7 @@ versions may change the store format and the API; the release notes say how to u - The Python package's README installs the `rdflib` extra from PyPI in its rdflib section too, `pip install "tripletrail[rdflib]"`, instead of from a checkout (#807). - A failing command prints its error as a sentence that names the file or address, such as `Error: missing.ttl does not exist` or `Error: cannot listen on 127.0.0.1:7878: address already in use` (#804). Before, `load`, `validate` and `serve` printed Rust's debug form, `Error: Os { code: 2, kind: NotFound, … }`, which did not say which file of several was missing, and other errors came out quoted (`Error: "1 of 1 queries failed"`). See [the server options](docs/server.md#main-options). - `geof:length(?g, uom:metre)` answers on a projected CRS (#786): GeoSPARQL 1.1's form with a unit was unbound for `geof:length`, `geof:perimeter`, `geof:area` and `geof:size` on every CRS, while `geof:metricLength` and `st:ST_Length` gave the length. They now give the `metric*` value in metres or kilometres (square metres or kilometres for an area); another unit is still unbound. `geof:distance` and `geof:buffer` took a unit already. See [docs/spatial.md](docs/spatial.md). +- A spatial join on term ids stays within the query memory (#811): it held both sides' rows and boxes and its table whole, whatever `--query-memory` said, so a join of two large sides could take many times the limit. Now the side estimated smaller is held in at most half of the limit and the other is read in parts of a quarter of it, each swept against the first and its pairs added to the table; when the three would pass the limit, the query fails with the memory error (503 on the server), as a hash join of the evaluator does. Without a limit nothing changes. See [docs/server.md](docs/server.md) (**Query memory**) and [docs/spatial-index.md](docs/spatial-index.md). - `st:ST_LineSubstring`, `st:ST_LineInterpolatePoint` and `st:ST_LineLocatePoint` measure a `MULTILINESTRING` as one line, as the `rail:` functions do (#787): the parts in order, with a gap adding no length. Before, they answered unbound without a message, so a rule silently dropped net elements whose geometry came as touching parts. A substring across a gap is a `MULTILINESTRING`. An empty or non-line input still gives no value. See [the spatial functions](docs/spatial.md). - `st:ST_SnapToGrid` and `st:ST_ReducePrecision` keep Z and M (#783). They dropped Z from a line as soon as a coordinate moved, so rounding a transformed 3D track lost its heights. In a `GEOMETRYCOLLECTION`, `ST_SnapToGrid` left a point unsnapped and `ST_ReducePrecision` gave it a wrong Z taken from the line next to it. Now every member of a collection is snapped alike and each moved coordinate keeps its own Z and M, as in PostGIS. Where snapping merges points, the first one's are kept. When `ST_ReducePrecision` has to add a vertex to keep the result valid, the result has no Z or M rather than an invented one. - A spatial join of two query sides runs on term ids under the union default graph too, each triple read once (#784): it went the `VALUES` way, which copied each polygon's literal into every pair and, with 90 large multipolygons and 11,000 lines in 30 named graphs, ran out of 16 GB of memory. The FILTER's tests of one side's variables alone, such as `STRSTARTS(STR(?w), "<…/EPSG/0/25832>")` to keep one CRS of a feature's geometries, now drop that side's rows before the pairs are swept and tested, so only the literals they keep are paired: on that graph the `sfContains` join takes 0.45 s, 5 s before in the default graph, and 26 s written as a box filter plus `BIND`. The example `contains_join` generates the data. diff --git a/crates/tripletrail-spatial/src/lib.rs b/crates/tripletrail-spatial/src/lib.rs index cef94cca..51f35e18 100644 --- a/crates/tripletrail-spatial/src/lib.rs +++ b/crates/tripletrail-spatial/src/lib.rs @@ -17,6 +17,6 @@ pub use index::{ IndexStats, IndexedPredicates, SAVED_KEY_FILE, SavedIndex, SpatialIndex, saved_file_of, }; pub use rewrite::{ - BUILT_IN_SERVICES, Bounded, Decision, IdSide, Knn, RewriteStats, SideGeometry, SpatialContext, - binds_through, knn, rewrite_query, rewrite_update, + BUILT_IN_SERVICES, Bounded, Decision, GEOMETRY_BYTES, IdSide, Knn, RewriteStats, SideGeometry, + SpatialContext, binds_through, knn, rewrite_query, rewrite_update, }; diff --git a/crates/tripletrail-spatial/src/rewrite.rs b/crates/tripletrail-spatial/src/rewrite.rs index 31d7f951..f0df47fb 100644 --- a/crates/tripletrail-spatial/src/rewrite.rs +++ b/crates/tripletrail-spatial/src/rewrite.rs @@ -176,6 +176,27 @@ pub trait SpatialContext: Sync { let _ = (pattern, var); None } + /// [`Self::side_ids`] handed to `each` in parts of about `bytes` each (rows and boxes), + /// so that a join holds one part of a large side at a time (#811); `bytes` is + /// `usize::MAX` for the whole side at once. `each` returns false to stop: `Some(false)` + /// then, `Some(true)` once every part was handed over, `None` as [`Self::side_ids`] + /// gives none. The default reads the side whole. + fn side_ids_each( + &self, + pattern: &GraphPattern, + var: &Variable, + bytes: usize, + each: &mut dyn FnMut(IdSide) -> bool, + ) -> Option { + let _ = bytes; + Some(each(self.side_ids(pattern, var)?)) + } + /// The memory in bytes one query may hold (the server's `--query-memory`), which a join + /// on term ids keeps its sides, boxes and result table within (#811): past it the query + /// fails with the memory error. `None` (the default): no limit. + fn query_memory(&self) -> Option { + None + } /// A pattern that reads `rows` (one column per variable) in the evaluation of the query /// being rewritten, or `None` (the default) if the context does not offer it. fn table(&self, variables: &[Variable], rows: IdRows) -> Option { @@ -393,6 +414,9 @@ pub struct RewriteStats { /// Indexed geometries an `st:` nearest-neighbour query left out because they are in /// another CRS than its constant, which `st:` distances refuse (#520). pub other_crs: usize, + /// The query memory (bytes) a join on term ids would have passed with its sides, boxes + /// and table (#811): the query then fails with the memory error. + pub over_memory: Option, } /// How far to grow a geometry's bounding box before probing the index. @@ -987,6 +1011,16 @@ fn below_optional(p: &GraphPattern, used: &HashSet) -> bool { } } +/// The bytes a join on ids holds for `side` (#811): its rows, its geometries' boxes and the +/// sweep's entry for each. +fn side_bytes(side: &IdSide) -> usize { + side.rows.ids.len() * size_of::() + side.geometries.len() * GEOMETRY_BYTES +} + +/// The memory a join on term ids counts for each geometry of a side: its box, and its place +/// in the sweep (#811). A context reading a side in parts sizes them with it. +pub const GEOMETRY_BYTES: usize = size_of::() + size_of::>(); + /// `side` under a `FILTER` of the `conjuncts` (but `join`) that read only variables `side` /// binds, or `side` itself when none does (#784). Every row of the group passes them, so a /// side read with them loses no row the group keeps; the group's FILTER still tests them. @@ -2330,30 +2364,150 @@ impl<'a> Rewriter<'a> { // literals, say), which the context may apply as it reads the side (#784): the pairs // of literals they leave out are then neither swept nor tested. let join = &plan.conjunct; - let Some(side_a) = self.ctx.side_ids(&narrowed(pa, conjuncts, join), a) else { - note_slow(start, || side_not_read(a, self.ctx.cancelled())); - return self.ctx.cancelled().then_some(None); + let (qa, qb) = (narrowed(pa, conjuncts, join), narrowed(pb, conjuncts, join)); + // Within the query memory (#811): the side estimated smaller is held, read in parts + // of a quarter of it, and the other is swept against it one part at a time, each + // part's pairs added to the table; the sides' rows, boxes and the table all count. + let budget = self.ctx.query_memory(); + let part = budget.map_or(usize::MAX, |b| (b / 4).max(1)); + let hold_a = match (self.rows(pa), self.rows(pb)) { + (Some(x), Some(y)) => x <= y, + _ => true, }; - note_slow(start, || { - format!( - "side read: {a} {} rows ({} geometries)", - side_a.rows.len(), - side_a.geometries.len() - ) + let (held_var, held_q, streamed_var, streamed_q) = if hold_a { + (a, &qa, b, &qb) + } else { + (b, &qb, a, &qa) + }; + let mut held: Vec = Vec::new(); + let mut held_bytes = 0usize; + let mut over = false; + let read = self.ctx.side_ids_each(held_q, held_var, part, &mut |side| { + held_bytes += side_bytes(&side); + held.push(side); + over = budget.is_some_and(|b| held_bytes > b / 2); + !over }); - let Some(side_b) = self.ctx.side_ids(&narrowed(pb, conjuncts, join), b) else { - note_slow(start, || side_not_read(b, self.ctx.cancelled())); + if over { + return self.over_memory(budget, start); + } + if read.is_none() { + note_slow(start, || side_not_read(held_var, self.ctx.cancelled())); return self.ctx.cancelled().then_some(None); - }; + } + let held_rows: usize = held.iter().map(|s| s.rows.len()).sum(); + let held_geometries: usize = held.iter().map(|s| s.geometries.len()).sum(); note_slow(start, || { - format!( - "sides read: {a} {} rows ({} geometries), {b} {} rows ({} geometries)", - side_a.rows.len(), - side_a.geometries.len(), - side_b.rows.len(), - side_b.geometries.len() - ) + format!("side read: {held_var} {held_rows} rows ({held_geometries} geometries)") }); + self.stats.sides_evaluated += 2; + let mut ids: Vec = Vec::new(); + let mut variables: Option> = None; + let (mut streamed_rows, mut pairs, mut total) = (0usize, 0usize, 0usize); + // `Some(None)`: cancelled; `None`: given up (the table too large, say). + let mut outcome: Option> = Some(Some(())); + let streamed = self + .ctx + .side_ids_each(streamed_q, streamed_var, part, &mut |part| { + streamed_rows += part.rows.len(); + for h in &held { + let (side_a, side_b) = if hold_a { (h, &part) } else { (&part, h) }; + if variables.is_none() { + let mut v = side_a.variables.clone(); + v.extend(side_b.variables.iter().cloned()); + variables = Some(v); + } + match self.pairs_on_ids(plan, (a, b), (side_a, side_b), left, start, &mut ids) { + Some(Some((p, r))) => { + pairs += p; + total += r; + } + other => { + outcome = other.map(|_| None); + return false; + } + } + let bytes = held_bytes + side_bytes(&part) + ids.len() * size_of::(); + if budget.is_some_and(|b| bytes > b) { + over = true; + return false; + } + } + true + }); + if over { + return self.over_memory(budget, start); + } + match outcome { + None => { + self.stats.lookup += start.elapsed(); + return None; + } + Some(None) => { + self.stats.lookup += start.elapsed(); + return Some(None); + } + Some(Some(())) => {} + } + if streamed.is_none() { + note_slow(start, || side_not_read(streamed_var, self.ctx.cancelled())); + return self.ctx.cancelled().then_some(None); + } + let (rows_a, rows_b) = if hold_a { + (held_rows, streamed_rows) + } else { + (streamed_rows, held_rows) + }; + let probe_var = if hold_a { a } else { b }; + let width = variables.as_ref().map_or(0, Vec::len); + let variables = variables.unwrap_or_default(); + self.stats.joins += 1; + let table = self.ctx.table(&variables, IdRows { width, ids }); + note_slow(start, || format!("a table of {total} rows")); + self.stats.lookup += start.elapsed(); + let table = table?; + if self.costed() { + self.stats.decisions.push(Decision::IdJoin { + a: a.clone(), + b: b.clone(), + rows_a, + rows_b, + probe: probe_var.clone(), + pairs, + rows: total, + }); + } + self.stats.materialized += 1; + Some(Some((table, vec![pa.clone(), pb.clone()]))) + } + + /// Ends a join on ids past the query memory `budget` (#811): the query fails with the + /// memory error. + fn over_memory( + &mut self, + budget: Option, + start: Instant, + ) -> Option)>> { + note_slow(start, || "past the query memory".to_owned()); + self.stats.lookup += start.elapsed(); + self.stats.over_memory = budget; + Some(None) + } + + /// The pairs of two sides (or parts of sides) on term ids passing `plan`, a row per pair + /// of their rows appended to `ids` (`side_a`'s columns, then `side_b`'s): the number of + /// pairs of geometries and of rows. `None` when the join is given up (its table would + /// pass [`MAX_TABLE_IDS`]), `Some(None)` once the query is cancelled. + #[allow(clippy::too_many_arguments)] + fn pairs_on_ids( + &mut self, + plan: &Plan, + (a, b): (&Variable, &Variable), + (side_a, side_b): (&IdSide, &IdSide), + left: &[(&Plan, Variable)], + start: Instant, + ids: &mut Vec, + ) -> Option> { // Rows and geometries are numbered in 32 bits below. if [&side_a, &side_b] .iter() @@ -2366,7 +2520,6 @@ impl<'a> Rewriter<'a> { .iter() .all(|s| s.geometries.is_sorted_by_key(|g| g.id)) ); - self.stats.sides_evaluated += 2; let threads = tripletrail_store::par::query_threads(); // The constant tests left to the FILTER hold in every row too. // Geometries are keyed by their place in the side's `geometries`. @@ -2402,8 +2555,8 @@ impl<'a> Rewriter<'a> { .collect() }; let (geoms_a, geoms_b) = ( - keep(&side_a, &tests(a), threads), - keep(&side_b, &tests(b), threads), + keep(side_a, &tests(a), threads), + keep(side_b, &tests(b), threads), ); note_slow(start, || { format!( @@ -2472,20 +2625,17 @@ impl<'a> Rewriter<'a> { ); self.stats.pairing += pairing.elapsed(); let Some(found) = found else { - self.stats.lookup += start.elapsed(); return Some(None); }; if ctx.cancelled() { - self.stats.lookup += start.elapsed(); return Some(None); } self.stats.sweeps += 1; - self.stats.joins += 1; self.stats.candidates += found.len(); // The rows of each side by geometry, then a row per pair of rows. let (rows_a, rows_b) = ( - RowsByGeometry::new(&side_a, threads), - RowsByGeometry::new(&side_b, threads), + RowsByGeometry::new(side_a, threads), + RowsByGeometry::new(side_b, threads), ); let (wa, wb) = (side_a.rows.width, side_b.rows.width); let width = wa + wb; @@ -2495,11 +2645,10 @@ impl<'a> Rewriter<'a> { let (ga, gb) = pair(f); total += rows_a.of(ga).len() * rows_b.of(gb).len(); } - if total.saturating_mul(width) > MAX_TABLE_IDS { - self.stats.lookup += start.elapsed(); + if total.saturating_mul(width).saturating_add(ids.len()) > MAX_TABLE_IDS { return None; } - let mut ids = Vec::with_capacity(total * width); + ids.reserve(total * width); for f in &found { let (ga, gb) = pair(f); let rb = rows_b.of(gb); @@ -2512,25 +2661,7 @@ impl<'a> Rewriter<'a> { } } } - let mut variables = side_a.variables.clone(); - variables.extend(side_b.variables.iter().cloned()); - let table = self.ctx.table(&variables, IdRows { width, ids }); - note_slow(start, || format!("a table of {total} rows")); - self.stats.lookup += start.elapsed(); - let table = table?; - if self.costed() { - self.stats.decisions.push(Decision::IdJoin { - a: a.clone(), - b: b.clone(), - rows_a: side_a.rows.len(), - rows_b: side_b.rows.len(), - probe: probe_var.clone(), - pairs: found.len(), - rows: total, - }); - } - self.stats.materialized += 1; - Some(Some((table, vec![pa.clone(), pb.clone()]))) + Some(Some((found.len(), total))) } fn join_values( diff --git a/crates/tripletrail-store/src/bgp.rs b/crates/tripletrail-store/src/bgp.rs index 20b4f81e..1908ab0a 100644 --- a/crates/tripletrail-store/src/bgp.rs +++ b/crates/tripletrail-store/src/bgp.rs @@ -411,6 +411,36 @@ impl Snapshot { graph: GraphSelector, cancelled: &(dyn Fn() -> bool + Sync), ) -> Option { + let mut ids = Vec::new(); + self.join_ids_each_part(triples, width, graph, cancelled, usize::MAX, &mut |rows| { + ids.extend_from_slice(&rows.ids); + true + })?; + Some(IdRows { width, ids }) + } + + /// The rows of [`Snapshot::join_ids_in_parts`] handed to `each` one part at a time, each + /// part the solutions of up to `values` values of the key variable (`usize::MAX`: parts + /// whose rows take about a quarter of what one join may hold), so that a caller + /// keeping only what it makes of each part (a spatial join's pairs, #811) holds one part + /// of the rows at a time, and the key's values (8 bytes each). `each` returns false to + /// stop: `Some(false)` then, `Some(true)` once every part was handed over; `None` as + /// [`Snapshot::join_ids_in_parts`] gives none. A row's copies (the same row from several + /// graphs) are in one part: their key's value is the same. + pub fn join_ids_each_part( + &self, + triples: &[IdTriple], + width: usize, + graph: GraphSelector, + cancelled: &(dyn Fn() -> bool + Sync), + values: usize, + each: &mut dyn FnMut(IdRows) -> bool, + ) -> Option { + let part = if values == usize::MAX { + (max_ids() / (4 * width.max(1))).max(64) + } else { + values.max(1) + }; let var = |s: IdSlot| match s { IdSlot::Var(v) => Some(v), IdSlot::Const(_) => None, @@ -456,18 +486,12 @@ impl Snapshot { values.sort_unstable_by_key(|id| id.0); values.dedup(); if values.is_empty() { - return Some(IdRows { - width, - ids: Vec::new(), - }); + return Some(true); } // About one row per value (a feature and its geometry), not a cross product. if self.estimate_rows(&triples, graph) > 4.0 * values.len() as f64 + 1024.0 { return None; } - // Parts whose rows take about a quarter of what one join may hold. - let part = (max_ids() / (4 * width.max(1))).max(64); - let mut ids = Vec::new(); for chunk in values.chunks(part) { if cancelled() { return None; @@ -481,11 +505,16 @@ impl Snapshot { Joined::Rows(rows) => rows, Joined::Count(_) => unreachable!("rows asked for"), }; + let mut ids = Vec::with_capacity(rows.ids.len()); for row in rows.rows() { ids.extend((0..width).map(|c| row[swap(c)])); } + drop(rows); + if !each(IdRows { width, ids }) { + return Some(false); + } } - Some(IdRows { width, ids }) + Some(true) } /// The number of solutions of `triples` in `graph` ([`BgpCount::Rows`]), or of distinct diff --git a/crates/tripletrail-store/tests/join_in_parts.rs b/crates/tripletrail-store/tests/join_in_parts.rs index a4a30da9..353898df 100644 --- a/crates/tripletrail-store/tests/join_in_parts.rs +++ b/crates/tripletrail-store/tests/join_in_parts.rs @@ -67,6 +67,31 @@ fn a_join_in_parts_has_the_rows_of_one_join() { .join_ids_in_parts(&triples, 3, GraphSelector::Default, &none) .unwrap(); assert_eq!(sorted(parts), whole); + // Handed over part by part: `usize::MAX` values take parts within the join memory + // (#811), each a quarter of it at most; a number of values takes parts of as many. + for (values, most) in [(usize::MAX, 512), (100, 300)] { + let (mut rows, mut parts) = (Vec::new(), 0); + let done = snap.join_ids_each_part( + &triples, + 3, + GraphSelector::Default, + &none, + values, + &mut |part| { + assert!(part.ids.len() <= most, "{values}: {}", part.ids.len()); + rows.extend_from_slice(&part.ids); + parts += 1; + true + }, + ); + assert_eq!(done, Some(true)); + assert!(parts > 1, "{values}: {parts} parts"); + let rows = tripletrail_store::IdRows { + width: 3, + ids: rows, + }; + assert_eq!(sorted(rows), whole); + } // Cancelled: none. assert!( snap.join_ids_in_parts(&triples, 3, GraphSelector::Default, &|| true) diff --git a/crates/tripletrail/src/lib.rs b/crates/tripletrail/src/lib.rs index 6a6a5a10..94a7b5bf 100644 --- a/crates/tripletrail/src/lib.rs +++ b/crates/tripletrail/src/lib.rs @@ -2391,8 +2391,10 @@ impl Engine { | spargebra::Query::Describe { dataset, .. } | spargebra::Query::Ask { dataset, .. } => *dataset = marker, } + let over_memory = stats.over_memory; *self.spatial.last.lock_unpoisoned() = stats; self.check_cancelled()?; + check_spatial_memory(over_memory)?; Ok(rewritten) } @@ -2984,8 +2986,10 @@ impl Engine { rows: Some((&rows, &base)), }; let (rewritten, stats) = rewrite_query(query, &ctx); + let over_memory = stats.over_memory; *self.spatial.last.lock_unpoisoned() = stats; self.check_cancelled()?; + check_spatial_memory(over_memory)?; rewritten } else { query @@ -3071,8 +3075,10 @@ impl Engine { if dataset.is_none() && shortcuts { query = range::rewrite(query, self, at.as_ref()).0; } + let over_memory = stats.over_memory; *self.spatial.last.lock_unpoisoned() = stats; self.check_cancelled()?; + check_spatial_memory(over_memory)?; } // With the result tables the spatial rewrite registered after the view was taken (the // pairs of a spatial join): the count pass reads them as tables, not through the @@ -3814,9 +3820,11 @@ impl Engine { update = self.search_rewrite_update(update, false, true)?; if rewrite && self.spatial_rewrite_on() { let (rewritten, stats) = tripletrail_spatial::rewrite_update(update, self); + let over_memory = stats.over_memory; *self.spatial.last.lock_unpoisoned() = stats; update = rewritten; self.check_cancelled()?; + check_spatial_memory(over_memory)?; } // Joins written as filters (#185), from what the store held before the update and // only for predicates no operation of it may write. @@ -4933,6 +4941,135 @@ fn touches_index(predicate: NamedNodeRef<'_>, object: &Term) -> bool { || matches!(object, Term::Literal(l) if tripletrail_geo::is_geometry_datatype(l.datatype().as_str())) } +impl Engine { + /// The side of the rows `all` of a side's compiled pattern ([`Self::side_ids_each`]): + /// made distinct under the union, its named variables, the tests of its own variables + /// applied, and its geometries' boxes. `None` once the query is cancelled. + fn side_of( + &self, + store: &tripletrail_store::Store, + snapshot: &tripletrail_store::Snapshot, + mut all: tripletrail_store::IdRows, + variables: &[Variable], + graph: tripletrail_store::GraphSelector, + tests: Option<&spargebra::algebra::Expression>, + ) -> Option { + let cancelled = || self.is_cancelled(); + let width = variables.len(); + // Every graph's copy of a triple gave a row of its own: one each, as the union has. + if graph == tripletrail_store::GraphSelector::All { + let mut rows: Vec<&[tripletrail_store::TermId]> = all.rows().collect(); + rows.sort_unstable_by(|a, b| a.iter().map(|t| t.0).cmp(b.iter().map(|t| t.0))); + rows.dedup(); + all = tripletrail_store::IdRows { + width: all.width, + ids: rows.concat(), + }; + } + // The named variables only. + let mut ids = Vec::with_capacity(all.len() * width); + for row in all.rows() { + ids.extend_from_slice(&row[..width]); + } + let mut rows = tripletrail_store::IdRows { width, ids }; + if let Some(expr) = tests { + let mut kept = Vec::new(); + split_conjuncts(expr, &mut kept); + kept.retain(|c| idtree::filter_covered(c)); + if let Some(expr) = kept + .into_iter() + .cloned() + .reduce(|a, b| spargebra::algebra::Expression::And(Box::new(a), Box::new(b))) + { + let table = idtree::Table { + vars: variables.to_vec(), + maybe: vec![false; width], + ones: rows.len(), + ids: rows.ids.clone(), + }; + let eval = idtree::Eval { + snapshot, + cancelled: &cancelled, + graph, + columns: None, + named: None, + }; + // Not evaluated on ids after all: every row, for the query's FILTER. + match eval.filtered(&expr, table) { + Some(t) => { + rows = tripletrail_store::IdRows { width, ids: t.ids }; + } + None if cancelled() => return None, + None => {} + } + } + } + let mut distinct: Vec = rows + .rows() + .map(|r| r[0]) + .filter(|id| id.kind() == tripletrail_store::Kind::Geometry) + .collect(); + distinct.sort_unstable_by_key(|id| id.0); + distinct.dedup(); + // Bounding boxes only, read from the saved records on the query pool (#728) in parts + // of at least 4096; the join parses the geometries it tests (#754). Empty and invalid + // geometries meet nothing. + let strict = tripletrail_geo::strict_crs(); + let geometries: Vec<_> = + tripletrail_store::par::chunks_sized(distinct.len(), 8192, 4096, |range| { + let part = &distinct[range]; + let mut out = Vec::with_capacity(part.len()); + for (i, &id) in part.iter().enumerate() { + // Each box is a read of the geometry's record, which on a large + // side that is not in memory takes minutes in all (#338). + if i % 4096 == 0 && self.is_cancelled() { + return None; + } + if let Some((crs, Some(bbox))) = store.geometry_bbox(id) { + // A projected one's box in the lon/lat frame, as saved, + // for a join across CRSs (#669). + let frame = (!strict && !crs.is_geographic()) + .then(|| store.geometry_saved_frame_box(id)) + .flatten() + .map(|b| b.map(f64::from)); + out.push(tripletrail_spatial::SideGeometry { + id, + crs, + bbox, + frame, + }); + } + } + Some(out) + }) + .into_iter() + .collect::>>()? + .into_iter() + .flatten() + .collect(); + let parse = snapshot.clone(); + let read = snapshot.clone(); + Some(tripletrail_spatial::IdSide { + variables: variables.to_vec(), + rows, + geometry: 0, + geometries, + load: Arc::new(move |id| parse.geometry(id)), + read: Arc::new(move |id| read.geometry_transient(id)), + }) + } +} + +/// The memory error of a query whose spatial join on term ids would have passed the query +/// memory (#811), as a hash join of the evaluator past it fails. From the query's own +/// rewrite statistics, not the engine's last ones, which another query may have replaced. +fn check_spatial_memory(over_memory: Option) -> Result<(), Error> { + match over_memory { + Some(limit) => Err(oxigraph::sparql::QueryEvaluationError::MemoryLimit(limit).into()), + None => Ok(()), + } +} + /// The conjuncts of `e` (`a && b && c` as `[a, b, c]`). fn split_conjuncts<'e>( e: &'e spargebra::algebra::Expression, @@ -4960,6 +5097,10 @@ impl SpatialContext for Engine { self.is_cancelled() } + fn query_memory(&self) -> Option { + tripletrail_store::memory_limit() + } + fn non_geometry_objects(&self, predicate: &str) -> Option { if let Some(&n) = self.spatial.non_geometry.lock_unpoisoned().get(predicate) { return Some(n); @@ -5061,6 +5202,21 @@ impl SpatialContext for Engine { pattern: &spargebra::algebra::GraphPattern, var: &Variable, ) -> Option { + let mut side = None; + self.side_ids_each(pattern, var, usize::MAX, &mut |s| { + side = Some(s); + true + })?; + side + } + + fn side_ids_each( + &self, + pattern: &spargebra::algebra::GraphPattern, + var: &Variable, + bytes: usize, + each: &mut dyn FnMut(tripletrail_spatial::IdSide) -> bool, + ) -> Option { let Dataset::TripleTrail(store) = &self.store else { return None; }; @@ -5116,7 +5272,7 @@ impl SpatialContext for Engine { let compiled = snapshot.compile_bgp(&triples, &variables)?; let width = variables.len(); let Some(graph) = graph.filter(|_| !compiled.empty) else { - return Some(tripletrail_spatial::IdSide { + return Some(each(tripletrail_spatial::IdSide { variables, rows: tripletrail_store::IdRows { width, @@ -5126,119 +5282,49 @@ impl SpatialContext for Engine { geometries: Vec::new(), load: Arc::new(|_| None), read: Arc::new(|_| None), - }); + })); }; let cancelled = || self.is_cancelled(); let columns = compiled.columns.len(); // A side whose rows take more than one id join may (33 million land-use features at // 1B triples) is joined in parts rather than given up on: the other ways of joining // evaluate it row by row, far past any timeout (#340). - let mut all = match snapshot.join_ids(&compiled.triples, columns, graph, &cancelled) { - Some(all) => all, - None if cancelled() => return None, - None => snapshot.join_ids_in_parts(&compiled.triples, columns, graph, &cancelled)?, - }; - // Every graph's copy of a triple gave a row of its own: one each, as the union has. - if graph == tripletrail_store::GraphSelector::All { - let mut rows: Vec<&[tripletrail_store::TermId]> = all.rows().collect(); - rows.sort_unstable_by(|a, b| a.iter().map(|t| t.0).cmp(b.iter().map(|t| t.0))); - rows.dedup(); - all = tripletrail_store::IdRows { - width: all.width, - ids: rows.concat(), - }; - } - // The named variables only. - let mut ids = Vec::with_capacity(all.len() * width); - for row in all.rows() { - ids.extend_from_slice(&row[..width]); + // A row and its geometry's box, about: what a part of `bytes` holds (#811). + let per_row = + columns * size_of::() + tripletrail_spatial::GEOMETRY_BYTES; + let whole = bytes == usize::MAX + || snapshot.estimate_rows(&compiled.triples, graph) * per_row as f64 <= bytes as f64; + let finish = |all| self.side_of(store, &snapshot, all, &variables, graph, tests); + if whole && let Some(all) = snapshot.join_ids(&compiled.triples, columns, graph, &cancelled) + { + return Some(each(finish(all)?)); } - let mut rows = tripletrail_store::IdRows { width, ids }; - if let Some(expr) = tests { - let mut kept = Vec::new(); - split_conjuncts(expr, &mut kept); - kept.retain(|c| idtree::filter_covered(c)); - if let Some(expr) = kept - .into_iter() - .cloned() - .reduce(|a, b| spargebra::algebra::Expression::And(Box::new(a), Box::new(b))) - { - let table = idtree::Table { - vars: variables.clone(), - maybe: vec![false; width], - ones: rows.len(), - ids: rows.ids.clone(), - }; - let eval = idtree::Eval { - snapshot: &snapshot, - cancelled: &cancelled, - graph, - columns: None, - named: None, - }; - // Not evaluated on ids after all: every row, for the query's FILTER. - match eval.filtered(&expr, table) { - Some(t) => { - rows = tripletrail_store::IdRows { width, ids: t.ids }; - } - None if cancelled() => return None, - None => {} - } - } + if cancelled() { + return None; } - let mut distinct: Vec = rows - .rows() - .map(|r| r[0]) - .filter(|id| id.kind() == tripletrail_store::Kind::Geometry) - .collect(); - distinct.sort_unstable_by_key(|id| id.0); - distinct.dedup(); - // Bounding boxes only, read from the saved records on the query pool (#728) in parts - // of at least 4096; the join parses the geometries it tests (#754). Empty and invalid - // geometries meet nothing. - let strict = tripletrail_geo::strict_crs(); - let geometries: Vec<_> = - tripletrail_store::par::chunks_sized(distinct.len(), 8192, 4096, |range| { - let part = &distinct[range]; - let mut out = Vec::with_capacity(part.len()); - for (i, &id) in part.iter().enumerate() { - // Each box is a read of the geometry's record, which on a large - // side that is not in memory takes minutes in all (#338). - if i % 4096 == 0 && self.is_cancelled() { - return None; - } - if let Some((crs, Some(bbox))) = store.geometry_bbox(id) { - // A projected one's box in the lon/lat frame, as saved, - // for a join across CRSs (#669). - let frame = (!strict && !crs.is_geographic()) - .then(|| store.geometry_saved_frame_box(id)) - .flatten() - .map(|b| b.map(f64::from)); - out.push(tripletrail_spatial::SideGeometry { - id, - crs, - bbox, - frame, - }); - } + // In parts: each a part of the values of the key of the side's smallest triple; with + // no query memory, parts of the store's own size, within the id join memory (#340). + let values = if bytes == usize::MAX { + usize::MAX + } else { + (bytes / per_row).max(1) + }; + let mut failed = false; + let done = snapshot.join_ids_each_part( + &compiled.triples, + columns, + graph, + &cancelled, + values, + &mut |all| match finish(all) { + Some(side) => each(side), + None => { + failed = true; + false } - Some(out) - }) - .into_iter() - .collect::>>()? - .into_iter() - .flatten() - .collect(); - let parse = snapshot.clone(); - let read = snapshot.clone(); - Some(tripletrail_spatial::IdSide { - variables, - rows, - geometry: 0, - geometries, - load: Arc::new(move |id| parse.geometry(id)), - read: Arc::new(move |id| read.geometry_transient(id)), - }) + }, + )?; + (!failed).then_some(done) } fn table( diff --git a/crates/tripletrail/tests/cost_model.rs b/crates/tripletrail/tests/cost_model.rs index 76608cdb..b4c7f011 100644 --- a/crates/tripletrail/tests/cost_model.rs +++ b/crates/tripletrail/tests/cost_model.rs @@ -877,6 +877,8 @@ fn a_join_side_larger_than_the_query_memory_is_read_in_parts() { let decisions = small.last_spatial_stats().decisions; assert_eq!(on_ids(&decisions), Some(n), "{decisions:?}"); assert_eq!(small.last_spatial_stats().sides_evaluated, 2); + // The spots are swept against the zones in parts of 2 KiB each (#811). + assert!(small.last_spatial_stats().sweeps > 1); } #[test] @@ -979,3 +981,47 @@ fn a_join_pairs_only_the_literals_its_filter_keeps() { // The table of the join on ids: the answer's rows, no pair of a CRS84 literal. assert_eq!(on_ids(&decisions), Some(n), "{decisions:?}"); } + +#[test] +fn joins_on_ids_stay_within_the_query_memory() { + // #811: a join on term ids reads its sides in parts within the query memory, with the + // same answer; one whose held part alone would pass the memory answers the memory error. + let e = Engine::new_tripletrail(); + let mut quads = grid("p", "Spot", 2500, 50, 10.0, 60.0, 0.001); + for i in 0..2500 { + let (x, y) = ( + 10.0 + (i % 50) as f64 * 0.001 - 0.0002, + 60.0 + (i / 50) as f64 * 0.001 - 0.0002, + ); + quads.extend(zone(&format!("z{i}"), x, y, 0.0006)); + } + e.load_quads(quads).unwrap(); + let within = "SELECT ?p ?z WHERE { ?p a ex:Spot ; geo:hasGeometry/geo:asWKT ?pw . \ + ?z a ex:Zone ; geo:hasGeometry/geo:asWKT ?zw FILTER(geof:sfWithin(?pw, ?zw)) }"; + let whole = sorted(&e, within); + assert_eq!(whole.len(), 2500); + // Within 64 MiB each side is read whole and swept once; within 1 MiB the side held + // still fits in half of it, and the other is swept against it in parts. + for (bytes, parts) in [(64 << 20, 1), (1 << 20, 4)] { + let limited = e.with_query_memory(bytes); + assert_eq!(sorted(&limited, within), whole, "{bytes} bytes"); + let stats = limited.last_spatial_stats(); + assert_eq!( + on_ids(&stats.decisions), + Some(2500), + "{bytes} bytes: {stats:?}" + ); + assert_eq!(stats.sweeps, parts, "{bytes} bytes: {stats:?}"); + assert_eq!(stats.over_memory, None); + } + // Within 256 KiB the side held no longer fits in half of it. + let error = e + .with_query_memory(256 << 10) + .query(&format!("{PREFIXES}{within}")) + .err() + .expect("a join past the query memory fails"); + assert!( + error.to_string().contains("more memory than its limit"), + "{error}" + ); +} diff --git a/docs/guide/13-production.md b/docs/guide/13-production.md index 4de0c7e7..2100bef0 100644 --- a/docs/guide/13-production.md +++ b/docs/guide/13-production.md @@ -258,7 +258,8 @@ See [read replicas](../server.md#read-replicas). a lower limit for one dataset, and a request may ask for less with `query-memory`. A map tile, facet count or OGC API page holds that limit for all of its queries together (1 GiB without either). A query whose joins, sorts and groups together would hold more fails - with 503 instead of taking the server's memory: + with 503 instead of taking the server's memory, and so does a spatial join of two large + sides that would not fit even read in parts: ```sh diff --git a/docs/server.md b/docs/server.md index 72f430a6..069f4bcc 100644 --- a/docs/server.md +++ b/docs/server.md @@ -2642,8 +2642,13 @@ version. memory of one query's intermediate rows. Joins on term ids that would pass it are evaluated row by row instead: slower, but in little memory and cancelled at the timeout. A side of a spatial join on term ids is the exception: it is joined in parts of its - features instead (#340), as the join keeps its rows and boxes anyway and row by row it - would run far past the timeout. + features instead (#340), as row by row it would run far past the timeout. Such a join + holds the rows and boxes of the side estimated smaller, which must fit in half of the + limit, reads the other side in parts of a quarter of it, sweeps each part against the + first, and keeps the pairs' rows: when the three would pass the limit, the query fails + with 503 like a hash join (#811). Beyond the limit it holds, while it reads a part, the + values of the part's key (8 bytes each), and the geometries of the candidates it tests, + parsed (#811). A hash join of the evaluator whose held rows would pass it fails the query with 503 ("needs more memory than its limit"), and so do the rows `ORDER BY` sorts, the rows `DISTINCT` has seen, the groups of `GROUP BY` in the evaluator and the nodes a property diff --git a/docs/spatial-index.md b/docs/spatial-index.md index 47811d14..b013c475 100644 --- a/docs/spatial-index.md +++ b/docs/spatial-index.md @@ -365,7 +365,11 @@ A join cut off while it reads a side says which one (`cut off while reading side the store did not offer on term ids says so (`side ?w2 not read on term ids; joined another way`). A side whose intermediate rows would take more than `--query-memory` (33.4M land-use features at 1B triples) is joined in parts of the values of its smallest triple's subject, -each part within that memory, rather than given up on (#340). The +each part within that memory, rather than given up on (#340). Within `--query-memory` the join +holds the side estimated smaller whole, in at most half of it, and sweeps the other against it +in parts of a quarter of it, the pairs' rows added to one table; when the held side, a part and +the table would pass the memory, the join stops (`past the query memory`) and the query fails +with the memory error (#811). The steps are reading each side, the constant tests, each sweep (with its candidates, or "more than" the cap when the probes are split), the tests of the candidates and the table of rows.