diff --git a/CHANGELOG.md b/CHANGELOG.md index 407c2252..c819bea9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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). diff --git a/crates/tripletrail-server/src/facet_index.rs b/crates/tripletrail-server/src/facet_index.rs index 848427ba..76d44de1 100644 --- a/crates/tripletrail-server/src/facet_index.rs +++ b/crates/tripletrail-server/src/facet_index.rs @@ -662,9 +662,12 @@ 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 { @@ -672,6 +675,7 @@ pub(crate) fn make( }; 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), } @@ -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(); @@ -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, @@ -939,10 +950,14 @@ pub(crate) fn update( let mut affected: Vec = 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 = vec![(Vec::new(), Vec::new(), true); partial.len()]; let mut new_boxes: Vec<(u32, Rect)> = Vec::new(); let mut new_shapes: HashMap>> = HashMap::new(); @@ -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), } @@ -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, @@ -1260,14 +1276,33 @@ fn predicates_of(pattern: &str) -> Option> { 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, u32>, names: Vec>, + /// 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, + /// 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) -> 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; @@ -1276,8 +1311,41 @@ impl Features { let name: Arc = 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 @@ -1320,27 +1388,35 @@ fn read_boxes( let mut shapes: HashMap>> = HashMap::new(); let mut parsed: HashMap> = 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), @@ -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| { @@ -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 { @@ -1438,9 +1525,9 @@ fn read( let mut values: Vec> = Vec::new(); let mut ids: HashMap, 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(); @@ -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)) } @@ -1563,6 +1654,13 @@ type Kept = (Arc, u64); #[derive(Default)] pub(crate) struct FacetIndexes { kept: Mutex>, + /// 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, 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, std::sync::Condvar), @@ -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, 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() @@ -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) -> Option { + 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) { + 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, 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); diff --git a/crates/tripletrail-server/src/tiles.rs b/crates/tripletrail-server/src/tiles.rs index 12af2765..69a32ce2 100644 --- a/crates/tripletrail-server/src/tiles.rs +++ b/crates/tripletrail-server/src/tiles.rs @@ -500,6 +500,7 @@ pub(crate) fn warm(state: &State, entry: &Entry, within: Duration) -> Result Result { + facet_budget(state, entry); let deadline = std::time::Instant::now() + within; let limit = crate::limits::Limits::of(state, &entry.name).timeout(None); let mut out = Warmed { @@ -669,6 +670,7 @@ fn warm_caches(state: &State, entry: &Entry, within: Duration) -> Result HttpError { /// `--query-memory 1G`). Past it a query fails with 503 instead of taking the server's /// memory. pub(crate) fn map_view(state: &State, entry: &Entry, mut view: View) -> View { + facet_budget(state, entry); let process = || tripletrail::store::memory_limit().map(|b| b as u64); let whole = view .query_memory @@ -4737,6 +4743,13 @@ pub(crate) fn map_view(state: &State, entry: &Entry, mut view: View) -> View { view } +/// Sets the budget of `entry`'s facet indexes from its limits as they are now (#809, #796): +/// see [`crate::facet_index::budget`]. +pub(crate) fn facet_budget(state: &State, entry: &Entry) { + let quota = crate::limits::Limits::of(state, &entry.name).max_memory; + crate::facet_index::set_budget(entry, crate::facet_index::budget(quota)); +} + /// What the tile builds of a dataset may hold at once (#633): the geometries they read and /// the copies they draw, roughly. A build takes its part before it draws a layer and gives it /// back when it is done, so a tile with very large geometries, or many low-zoom tiles asked @@ -5889,6 +5902,12 @@ mod tests { .any(|k| k.2 == v && k.3 == "\u{0}answer:Station?" && (k.4, k.5, k.6) == (z, x, y)) }; assert!(answered(now, 4.4, 50.8) && !answered(now, 10.0, 45.0)); + // The planted answers are not gzip: taken out before a request could be answered with + // one. A tile request starts making the collections again on a thread, and once that + // is done before the request reads them, the answer kept for `now` is used. + lock(&entry.map.tiles.cache) + .tiles + .retain(|k, _| k.3 != "\u{0}answer:Station?"); // Meanwhile, the kept tile answers: marked here, to tell it from one made again. { let (x, y) = tile_of(z, 4.4, 50.8); diff --git a/crates/tripletrail-server/tests/facet_index_budget.rs b/crates/tripletrail-server/tests/facet_index_budget.rs new file mode 100644 index 00000000..e3e7258e --- /dev/null +++ b/crates/tripletrail-server/tests/facet_index_budget.rs @@ -0,0 +1,144 @@ +//! The map's facet indexes stay within a quarter of the dataset's `maxMemory` or of +//! `--memory-limit` (#809, #796): a collection whose index needs more is counted and drawn +//! with queries instead, and the log says why. Without either limit they are made as before. + +use std::time::Duration; +use tripletrail::Engine; +use tripletrail::oxigraph::io::RdfFormat; +use tripletrail_server::{Options, Server}; + +/// Two collections: a few stations, and lines long enough that their index is most of the +/// map's memory. +fn engine() -> Engine { + let mut ttl = String::from( + "@prefix ex: .\n\ + @prefix geo: .\n", + ); + for i in 0..5 { + ttl.push_str(&format!( + "ex:s{i} a ex:Station ; ex:kind \"k{}\" ; \ + geo:hasGeometry [ geo:asWKT \"POINT({i} 50)\"^^geo:wktLiteral ] .\n", + i % 2 + )); + } + for i in 0..200 { + let points: Vec = (0..200) + .map(|j| { + format!( + "{} {}", + 4.0 + f64::from(j) * 0.001, + 50.0 + f64::from(i) * 0.001 + ) + }) + .collect(); + ttl.push_str(&format!( + "ex:l{i} a ex:Line ; ex:speed {} ; \ + geo:hasGeometry [ geo:asWKT \"LINESTRING({})\"^^geo:wktLiteral ] .\n", + 100 + i % 3, + points.join(", ") + )); + } + let engine = Engine::new_tripletrail(); + engine.load(RdfFormat::Turtle, ttl.as_bytes()).unwrap(); + engine +} + +struct Running { + base: String, + handle: tripletrail_server::Handle, +} + +fn serve(limits: Option<&std::path::Path>) -> Running { + let server = Server::bind( + "127.0.0.1:0", + vec![("kg".to_owned(), engine())], + Options { + threads: 2, + limits: limits.map(std::path::Path::to_path_buf), + ..Options::default() + }, + ) + .unwrap(); + let base = format!("http://{}", server.address()); + let handle = server.handle(); + server.spawn(); + Running { base, handle } +} + +fn get(base: &str, path: &str) -> serde_json::Value { + serde_json::from_str( + &ureq::get(&format!("{base}{path}")) + .call() + .unwrap() + .into_string() + .unwrap(), + ) + .unwrap() +} + +fn map_bytes(base: &str) -> u64 { + get(base, "/$/stats/kg")["datasets"]["/kg"]["memory"]["mapCaches"] + .as_u64() + .unwrap() +} + +#[test] +fn a_facet_index_past_its_budget_is_not_made() { + // Without a limit: both indexes, as before. + let free = serve(None); + let done = free.handle.warm_map("kg").unwrap(); + assert!(!done.contains("failed"), "{done}"); + let whole = map_bytes(&free.base); + let lines = get(&free.base, "/kg/tiles/facets/Line"); + assert_eq!(lines["features"], 200, "{lines}"); + + // A quota whose quarter holds the stations' index but not the lines'. + let dir = tripletrail_testdir::tempdir("facet-index-budget"); + let limits = dir.join("limits.json"); + std::fs::write( + &limits, + format!(r#"{{"datasets": {{"kg": {{"maxMemory": {whole}}}}}}}"#), + ) + .unwrap(); + let held = serve(Some(&limits)); + let done = held.handle.warm_map("kg").unwrap(); + assert!( + done.contains("Line values: The facet index of Line needs more than"), + "{done}" + ); + assert!(!done.contains("Station values"), "{done}"); + // Not left for the background either: it would not fit there. + assert!(!done.contains("made in the background"), "{done}"); + let bytes = map_bytes(&held.base); + assert!(bytes <= whole / 4, "{bytes} of {whole}"); + // The same counts, read with queries, and a request does not make the index again. + let counted = get(&held.base, "/kg/tiles/facets/Line"); + assert_eq!(counted["features"], 200, "{counted}"); + assert_eq!(counted["facets"], lines["facets"], "{counted}"); + assert!(map_bytes(&held.base) <= whole / 4); + + // A larger quota: the lines' index is made again. + std::thread::sleep(Duration::from_millis(1100)); + std::fs::write( + &limits, + format!( + r#"{{"datasets": {{"kg": {{"maxMemory": {}}}}}}}"#, + whole * 40 + ), + ) + .unwrap(); + std::thread::sleep(Duration::from_millis(1100)); + let done = held.handle.warm_map("kg").unwrap(); + assert!(!done.contains("failed"), "{done}"); + assert!(map_bytes(&held.base) > whole / 4); + + // The server's --memory-limit bounds them the same way, without a quota. + tripletrail::store::Store::set_memory_limit(usize::try_from(whole).unwrap()); + let limited = serve(None); + let done = limited.handle.warm_map("kg").unwrap(); + assert!( + done.contains("Line values: The facet index of Line needs more than"), + "{done}" + ); + assert!(map_bytes(&limited.base) <= whole / 4); +} diff --git a/crates/tripletrail-store/src/lib.rs b/crates/tripletrail-store/src/lib.rs index dcdfdde8..09a0a0d9 100644 --- a/crates/tripletrail-store/src/lib.rs +++ b/crates/tripletrail-store/src/lib.rs @@ -1413,6 +1413,12 @@ impl Store { index::set_memory_limit(bytes); } + /// The limit [`Store::set_memory_limit`] set, if any (`--memory-limit`): the server also + /// sizes the map's facet indexes from it (#809). + pub fn memory_limit() -> Option { + index::memory_limit() + } + /// Sets, for the whole process, the number of quads from which a compaction writes runs /// rather than rewriting the permutations. For tests of runs on small stores. #[doc(hidden)] diff --git a/docs/guide/10-maps-and-apis.md b/docs/guide/10-maps-and-apis.md index c259e595..62bc4833 100644 --- a/docs/guide/10-maps-and-apis.md +++ b/docs/guide/10-maps-and-apis.md @@ -102,7 +102,10 @@ What it keeps in memory to draw each layer's tiles (its facet index) is the exce time for is made right after, in the background, one layer at a time, and the log line names those layers (`out of time for the facet index of tunnel, which is made in the background`). Until a layer's is made, its tiles are read with a query each, which can take seconds on a -large dataset. Before the map it sorts the +large dataset. These indexes hold each feature of a layer, with its geometry, so on a large +dataset they take memory: with `--memory-limit` or a dataset's `maxMemory`, they hold at most +a quarter of it, and a layer whose index would not fit is read with queries (the log says +`The facet index of building needs more than … MB`). Before the map it sorts the dataset's IRIs and strings once, for queries with `MIN`, `MAX` or `ORDER BY` on them (the log line `ds: string ranks of N terms`). A load, an update or new shapes make the counts out of date, so the server makes the map again once the dataset has kept still for half a diff --git a/docs/server.md b/docs/server.md index 069f4bcc..79ad78c9 100644 --- a/docs/server.md +++ b/docs/server.md @@ -222,6 +222,20 @@ tripletrail serve --store oxigraph --location /data/tripletrail --dataset kg once and grew by gigabytes; now the others wait, each until its own timeout (a request that runs out of time is counted without the index, a background build waits up to its ten minutes). The builds' queries are under `--query-memory`, as before. + The facet indexes of a dataset, with the build running, hold at most a quarter of its + `maxMemory` or of `--memory-limit`, the lower (#809, #796); with neither, as much as they + need. A build counts what it holds as it reads (each feature's IRI and values, each + geometry and its WKT, roughly) and stops once the indexes kept and it would pass that, + with the log line `{ds}: The facet index of C needs more than N MB the map's facet indexes + have left (…)`; the warm-up's line lists it under `facets that failed`. That collection is + then counted and drawn with queries, as one the warm-up had no time for, and its index is + not tried again until the budget grows. The estimate leaves out the queries' own working + memory, so the process's heap can pass it for the time of a build. On OSM Europe (1B + triples, `--memory-limit 32G`, a 64 GB machine) the indexes of the buildings, roads and + land use held about 40 GB of heap, which took the page cache the store's files need, and the + short queries became 2 to 5 times slower (#809); on 11.7M triples of OSM Norway (2.3M + features), the warm-up's peak heap is 5.5 GB without a limit and 1.5 GB with + `--memory-limit 2G`, where the land use's index (3.7 GB counted) is left out. A collection whose facets or boxes run out of time, or whose geometries are in another CRS, keeps being counted with queries. After a load, an update or a change of the shapes, it makes the map again once the dataset has kept still for 30 s (#258), and logs `{ds}: after a change, map ready: @@ -349,7 +363,9 @@ tripletrail serve --store oxigraph --location /data/tripletrail --dataset kg files, so a dataset larger than memory can be loaded. Without it everything is sorted in memory. A load needs about 650 MB on top of the limit (the blocks of text in flight, the allocator's caches): size a machine or a cgroup at the limit plus 1 GB (#241, see - [store.md](store.md#what---memory-limit-bounds-during-a-load-241)). + [store.md](store.md#what---memory-limit-bounds-during-a-load-241)). `serve` also keeps the + map's facet indexes of each dataset within a quarter of it (#809, see the map's warm-up + above). - `tripletrail load` writes a progress line to standard error every minute while a file loads (#232): the store's step (`reading`, `sorting`, `writing`, `entailing`), the triples read so far, and how much of the file has been read. `Store::load_progress()` gives the same step @@ -2751,7 +2767,9 @@ version. dataset over its memory quota first drops the map's caches of it (#583), which the map makes again on request, in this order until it is under: the kept tiles, facet counts and labels, the kept feature lists, the facet indexes of callers who see some graphs or - rows, then the facet index of the full view. Only then go the indexes and caches + rows, then the facet index of the full view. The facet indexes never hold more than a + quarter of `maxMemory` (#796): a collection whose index would pass it is counted and drawn + with queries. Only then go the indexes and caches queries built (#18), largest first: the full-text, spatial, vector and range indexes and the result cache, with their views for callers who see some graphs. The next query or map request that needs one builds it again, slower that once. The OGC API's