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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions crates/tripletrail-spatial/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
229 changes: 180 additions & 49 deletions crates/tripletrail-spatial/src/rewrite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool> {
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<usize> {
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<GraphPattern> {
Expand Down Expand Up @@ -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<usize>,
}

/// How far to grow a geometry's bounding box before probing the index.
Expand Down Expand Up @@ -987,6 +1011,16 @@ fn below_optional(p: &GraphPattern, used: &HashSet<Variable>) -> 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::<TermId>() + 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::<SideGeometry>() + size_of::<Lazy<'static>>();

/// `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.
Expand Down Expand Up @@ -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<IdSide> = 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<TermId> = Vec::new();
let mut variables: Option<Vec<Variable>> = 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<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::<TermId>();
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<usize>,
start: Instant,
) -> Option<Option<(GraphPattern, Vec<GraphPattern>)>> {
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<TermId>,
) -> Option<Option<(usize, usize)>> {
// Rows and geometries are numbered in 32 bits below.
if [&side_a, &side_b]
.iter()
Expand All @@ -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`.
Expand Down Expand Up @@ -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!(
Expand Down Expand Up @@ -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;
Expand All @@ -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);
Expand All @@ -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(
Expand Down
Loading
Loading