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 @@ -69,6 +69,7 @@ versions may change the store format and the API; the release notes say how to u

### Fixed

- The map's facet indexes of a dataset hold at most a quarter of its `maxMemory` or of `--memory-limit`, the lower (#809, #796). They keep each feature's IRI, values and geometry, and nothing bounded them: on OSM Europe (1B triples, `--memory-limit 32G`, 64 GB) the warm-up's indexes of the buildings, roads and land use held about 40 GB of heap (49 GB in all, against 14 GB before them), which left the store's files 11 GB of page cache instead of 41 GB, and short queries became 2 to 5 times slower (class counts 1.1 to 5.3 ms, label lookup 1.0 to 2.3 ms) and `osm_station_admin` 3.8 to 5.1 s. A build counts what it holds as it reads and stops past the budget, with a log line; that collection is counted and drawn with queries, and not tried again until the budget grows. Without either limit, nothing changes. On 11.7M triples of OSM Norway, the warm-up's peak heap with `--memory-limit 2G` is 1.5 GB instead of 5.5 GB, and 360 MB after it instead of 1.9 GB. See [the map's warm-up](docs/server.md#main-options).
- 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).
Expand Down
216 changes: 204 additions & 12 deletions crates/tripletrail-server/src/facet_index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -662,16 +662,20 @@ pub(crate) fn make(
query_memory: None,
..view.clone()
};
// Within what the dataset's facet indexes may hold (#809, #796), less what the others
// hold: not at all when it did not fit before.
let limit = budget_for(entry, view, &collection.id)?;
// The pattern of its features (#448).
let members = collection.members("?f");
let mut features = Features::default();
let mut features = Features::within(&collection.id, limit);
let mut pairs_of: Vec<(String, Read)> = Vec::new();
for facet in collection.facets.iter().filter(|f| !f.text) {
let Some(t) = timeout() else {
break;
};
match read(entry, &members, "", facet, t, view, &mut features) {
Ok(read) => pairs_of.push((facet.key.clone(), read)),
Err(e) if features.over => return Err(did_not_fit(entry, view, collection, e)),
Err(e) if e.1 == crate::TIMED_OUT || facet.select.is_some() => continue,
Err(e) => return Err(e),
}
Expand All @@ -685,7 +689,14 @@ pub(crate) fn make(
t,
view,
&mut features,
)?,
)
.map_err(|e| {
if features.over {
did_not_fit(entry, view, collection, e)
} else {
e
}
})?,
None => None,
};
let boxes_cut = read.is_none();
Expand All @@ -696,7 +707,7 @@ pub(crate) fn make(
.into_iter()
.map(|(key, (pairs, values, numeric))| (key, Column::of(pairs, values, numeric, n)))
.collect();
let Features { mut ids, names } = features;
let Features { mut ids, names, .. } = features;
ids.shrink_to_fit();
Ok(Index {
features: ids,
Expand Down Expand Up @@ -939,10 +950,14 @@ pub(crate) fn update(
let mut affected: Vec<String> = affected.into_iter().collect();
affected.sort_unstable();
// Their values and geometries, numbered as before; new features after the others.
// Within the budget as [`make`], with the features it had.
let limit = budget_for(entry, view, &collection.id)?;
let mut features = Features {
ids: before.features.clone(),
names: before.names.clone(),
..Features::within(&collection.id, limit)
};
features.take(before.bytes())?;
let mut read_of: Vec<Read> = vec![(Vec::new(), Vec::new(), true); partial.len()];
let mut new_boxes: Vec<(u32, Rect<f64>)> = Vec::new();
let mut new_shapes: HashMap<u32, Vec<Arc<Geom>>> = HashMap::new();
Expand Down Expand Up @@ -1002,6 +1017,7 @@ pub(crate) fn update(
};
match read(entry, &members, "", facet, t, view, &mut features) {
Ok(read) => whole_read.push((facet.key.clone(), read)),
Err(e) if features.over => return Err(e),
Err(e) if e.1 == crate::TIMED_OUT || facet.select.is_some() => continue,
Err(e) => return Err(e),
}
Expand Down Expand Up @@ -1101,7 +1117,7 @@ pub(crate) fn update(
ties.extend(new_ties);
(Some(boxes), shapes, drawn, ties)
};
let Features { ids, names } = features;
let Features { ids, names, .. } = features;
Ok(Some((
Index {
features: ids,
Expand Down Expand Up @@ -1260,14 +1276,33 @@ fn predicates_of(pattern: &str) -> Option<HashSet<String>> {
Some(out)
}

/// The features read so far, numbered in the order they come.
/// The features read so far, numbered in the order they come, and the bytes the build holds
/// against its budget (#809).
#[derive(Default)]
struct Features {
ids: HashMap<Arc<str>, u32>,
names: Vec<Arc<str>>,
/// Bytes the build holds so far, roughly: its features, values and geometries, with the
/// WKT it keeps while it reads them.
held: usize,
/// The most the build may hold ([`budget_for`]), `None` for no limit.
limit: Option<usize>,
/// The collection, for the error.
collection: String,
/// Whether the build went past `limit`: it stops, whatever the facet.
over: bool,
}

impl Features {
/// A build of `collection`'s index that may hold `limit` bytes.
fn within(collection: &str, limit: Option<usize>) -> Self {
Self {
limit,
collection: collection.to_owned(),
..Self::default()
}
}

fn position(&mut self, iri: &str) -> u32 {
if let Some(&i) = self.ids.get(iri) {
return i;
Expand All @@ -1276,8 +1311,41 @@ impl Features {
let name: Arc<str> = iri.into();
self.names.push(Arc::clone(&name));
self.ids.insert(name, i);
// Its IRI, and its entries in `ids` and `names`.
self.held += iri.len() + 64;
i
}

/// Counts `bytes` more against the budget: past it, the build stops with
/// [`too_large`]'s error.
fn take(&mut self, bytes: usize) -> Result<(), HttpError> {
self.held += bytes;
match self.limit {
Some(limit) if self.held > limit => {
self.over = true;
Err(too_large(&self.collection, limit))
}
_ => Ok(()),
}
}
}

/// The error of a build past its budget (#809): its facets and tiles are then read with a
/// query each, as for a collection the warm-up had no time for.
fn too_large(collection: &str, limit: usize) -> HttpError {
HttpError(
503,
format!(
"The facet index of {collection} needs more than the {} the map's facet indexes \
have left (a quarter of the dataset's maxMemory or of --memory-limit): its facets \
and tiles are read with queries",
if limit >= 10_000_000 {
format!("{} MB", limit / 1_000_000)
} else {
format!("{} KB", limit / 1_000)
}
),
)
}

/// The box of each feature's geometries, by position, or None when one is in a space other
Expand Down Expand Up @@ -1320,27 +1388,35 @@ fn read_boxes(
let mut shapes: HashMap<u32, Vec<Arc<Geom>>> = HashMap::new();
let mut parsed: HashMap<Term, Arc<Geom>> = HashMap::new();
let mut usable = true;
let read = crate::ogc::each_row(entry, &query, Some(timeout), view, |row| {
let read = crate::ogc::try_each_row(entry, &query, Some(timeout), view, |row| {
let (Some(Some(Term::NamedNode(f))), Some(Some(w))) = (row.first(), row.get(1)) else {
return;
return Ok(());
};
let i = features.position(f.as_str()) as usize;
// A row's box, its entries in `best` and `shapes`, and the WKT `best` keeps.
let mut bytes = 64 + term_bytes(Some(w));
let g = match parsed.get(w) {
Some(g) => Arc::clone(g),
None => {
let Some(g) = parse_wkt_literal_uncached(w) else {
return;
return Ok(());
};
parsed.insert(w.clone(), Arc::clone(&g));
// The geometry, and its WKT as the key of `parsed`.
{
use geo::CoordsIter;
bytes += 64 + 16 * g.geometry.coords_count() + term_bytes(Some(w));
}
g
}
};
features.take(bytes)?;
if !g.crs.is_geographic() {
usable = false;
return;
return Ok(());
}
let Some(r) = g.geometry.bounding_rect() else {
return;
return Ok(());
};
let rank = match row.get(2) {
Some(Some(Term::Literal(r))) => r.value().parse().unwrap_or(0),
Expand Down Expand Up @@ -1376,6 +1452,7 @@ fn read_boxes(
),
None => r,
});
Ok(())
});
// A feature of one point is in a window exactly when its box is.
shapes.retain(|_, g| {
Expand Down Expand Up @@ -1410,6 +1487,16 @@ fn read_boxes(
}
}

/// The bytes of a term's text, roughly.
fn term_bytes(t: Option<&Term>) -> usize {
match t {
Some(Term::NamedNode(n)) => n.as_str().len(),
Some(Term::Literal(l)) => l.value().len() + 16,
Some(_) => 32,
None => 0,
}
}

/// A literal's text, for ties between geometries of the same detail.
fn literal_text(t: &Term) -> &str {
match t {
Expand Down Expand Up @@ -1438,9 +1525,9 @@ fn read(
let mut values: Vec<Option<Term>> = Vec::new();
let mut ids: HashMap<Option<Term>, u32> = HashMap::new();
let mut numeric = true;
crate::ogc::each_row(entry, &query, Some(timeout), view, |row| {
crate::ogc::try_each_row(entry, &query, Some(timeout), view, |row| {
let Some(Some(Term::NamedNode(f))) = row.first() else {
return;
return Ok(());
};
let f = features.position(f.as_str());
let value = row.get(1).cloned().flatten();
Expand All @@ -1450,11 +1537,15 @@ fn read(
numeric = false;
}
let next = values.len() as u32;
let mut new = 0;
let v = *ids.entry(value.clone()).or_insert_with(|| {
// The value, here and in `values`.
new = 2 * (term_bytes(value.as_ref()) + 32);
values.push(value);
next
});
pairs.push((f, v));
features.take(new + 8)
})?;
Ok((pairs, values, numeric))
}
Expand Down Expand Up @@ -1563,6 +1654,13 @@ type Kept = (Arc<Index>, u64);
#[derive(Default)]
pub(crate) struct FacetIndexes {
kept: Mutex<HashMap<Key, Kept>>,
/// The most bytes the indexes and the build running may hold together (#809, #796): a
/// quarter of the dataset's `maxMemory` or of `--memory-limit`, the lower; 0 for no
/// limit. Set by [`set_budget`] from the requests and the warm-up, which know the limits.
budget: std::sync::atomic::AtomicUsize,
/// The collections (by view) whose index did not fit, with the budget it did not fit in:
/// not tried again until the budget grows, as each try reads up to the budget first.
too_large: Mutex<HashMap<(Option<u64>, String), usize>>,
/// Whether a build ([`make`], [`update`]) of the dataset runs, and the signal when it is
/// done (#771): one at a time.
building: (Mutex<bool>, std::sync::Condvar),
Expand Down Expand Up @@ -1667,6 +1765,16 @@ impl FacetIndexes {
})
}

/// Bytes the indexes hold but that of `collection` for the view `fingerprint`, which a
/// build of it replaces.
fn bytes_besides(&self, fingerprint: Option<u64>, collection: &str) -> usize {
self.lock()
.iter()
.filter(|(k, _)| k.0 != fingerprint || k.2 != collection)
.map(|(k, (i, _))| k.2.capacity() + i.bytes())
.sum()
}

/// Bytes the indexes hold.
pub(crate) fn bytes(&self) -> usize {
self.lock()
Expand All @@ -1676,6 +1784,90 @@ impl FacetIndexes {
}
}

/// The budget of the facet indexes of a dataset with the memory quota `max_memory` (#809,
/// #796): a quarter of it or of the server's `--memory-limit`, the lower, `None` with neither.
/// The tile builds take another quarter of the quota ([`crate::tiles::Budget`]).
pub(crate) fn budget(max_memory: Option<u64>) -> Option<usize> {
let quota = max_memory.map(|q| usize::try_from(q).unwrap_or(usize::MAX));
let process = tripletrail::store::Store::memory_limit();
match (quota, process) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
.map(|b| (b / 4).max(1))
}

/// Sets the budget of `entry`'s facet indexes ([`budget`]). When it shrinks below what they
/// hold, those of limited views go, then the others, as under the memory quota; when it
/// grows, the collections that did not fit are tried again.
pub(crate) fn set_budget(entry: &Entry, budget: Option<usize>) {
use std::sync::atomic::Ordering::Relaxed;
let indexes = &entry.map.facets;
let new = budget.unwrap_or(0);
if indexes.budget.swap(new, Relaxed) == new {
return;
}
indexes
.too_large
.lock()
.unwrap_or_else(|e| e.into_inner())
.retain(|_, at| new != 0 && new <= *at);
if let Some(budget) = budget {
for limited_only in [true, false] {
if indexes.bytes() > budget {
indexes.forget_views(limited_only);
}
}
}
}

/// What a build of `collection`'s index for `view` may hold: the budget less what the other
/// indexes hold, `None` for no limit. The error of [`too_large`] when the collection did not
/// fit this budget before.
fn budget_for(entry: &Entry, view: &View, collection: &str) -> Result<Option<usize>, HttpError> {
let indexes = &entry.map.facets;
let budget = indexes.budget.load(std::sync::atomic::Ordering::Relaxed);
if budget == 0 {
return Ok(None);
}
if too_large_for(entry, view, collection) {
return Err(too_large(collection, budget));
}
let others = indexes.bytes_besides(view.fingerprint(), collection);
Ok(Some(budget.saturating_sub(others)))
}

/// Whether `collection`'s index did not fit the budget for `view` as it is now: not made in
/// the background either (#809).
pub(crate) fn too_large_for(entry: &Entry, view: &View, collection: &str) -> bool {
let indexes = &entry.map.facets;
let budget = indexes.budget.load(std::sync::atomic::Ordering::Relaxed);
budget != 0
&& indexes
.too_large
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&(view.fingerprint(), collection.to_owned()))
.is_some_and(|&at| budget <= at)
}

/// Remembers that `collection`'s index did not fit the budget for `view`, and logs it once.
/// Answers `e`, the build's error.
fn did_not_fit(entry: &Entry, view: &View, collection: &Collection, e: HttpError) -> HttpError {
let indexes = &entry.map.facets;
let budget = indexes.budget.load(std::sync::atomic::Ordering::Relaxed);
let first = indexes
.too_large
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert((view.fingerprint(), collection.id.clone()), budget)
.is_none();
if first {
eprintln!("{}: {}", entry.name, e.1);
}
e
}

/// The stamp of the last use of an index.
static STAMP: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

Expand Down
Loading
Loading