diff --git a/CHANGELOG.md b/CHANGELOG.md index 407c2252..d5d02f45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ versions may change the store format and the API; the release notes say how to u ### Added +- `tripletrail store compact --location DIR [--dataset ds]` rewrites a dataset no server has open with only the terms its quads still use (#759), as `tdb2.tdbcompact` does for TDB2. The dictionary only grows, so terms that deletes left behind stayed on disk. The command writes the next checkpoint with the live terms and every index sorted again (`--memory-limit` as for `load`). The answers are the same, and a crash leaves the dataset as it was. After 1M triples and 10 rounds each replacing a tenth of them, `dict*.bin` goes from 124.5 MB to 71.2 MB and `geoms*.bin` from 20.0 MB to 10.0 MB, the sizes of a fresh load of the same quads, in 0.7 s. Term ids change, and the saved spatial index is built again. The kept keys are streamed to disk, so the heap holds a bit per term besides the sort. A dataset whose files an older release wrote is refused (run `tripletrail store upgrade` first, which keeps a restore point). Running inside the server comes with #760. See [the store](docs/store.md) and [Fuseki's compaction](docs/guide/11-fuseki.md#compaction-and-syntax-checks). - Automatic failover with a lease in etcd (#779, decision record 0012). `--failover http://etcd:2379`, `--failover-name` and `--node-url` make the servers of a cluster elect the leader of each `--follow` dataset themselves: when the leader goes away, a replica takes over within a few seconds. The members' lists (`--node-url` and the `--follow` URLs) must match, or a member refuses to start. A replica runs for leader only while the lease is free, when it reaches at least `members - --sync-replicas` members and none of them is further along (holds data of a newer leader, `appliedEpoch`, or of the same leader further on its timeline). It then takes the lease (an etcd key bound to an etcd lease, through etcd's JSON gateway, with the epoch kept beside it) and is promoted at that epoch. The leader gives the lease up when it stops. Under `--failover`, `--sync-replicas` must be 1 or more and writes never stop waiting for replicas: a write that too few hold within `--sync-timeout` answers `503`. A leader takes no writes, and serves no log or base, until it holds the lease; a promotion by hand answers `409`. `/$/replication/{name}` shows the member's view under `failover`, and a follower's position under `following`. The first leader of a new cluster is the member started with `--dataset NAME` beside its `--follow NAME=…`. An old leader that comes back does not follow the new one yet (#781). See [automatic failover](docs/server.md#automatic-failover). - A promoted replica fences the old leader (#778, the first part of automatic failover #14, decision record 0012). Every leader has an epoch, which a promotion raises above every epoch the copy has seen and keeps in an `EPOCH` file in its directory and in its `HISTORY` entry. `/$/replication/{name}`, `/log` and `/base` give it in `X-TripleTrail-Epoch` (and `epoch` in the status). A replica keeps the highest epoch it has seen in its `NAME.replica` and its status, and refuses to read from a leader with a lower one, so an old leader that comes back cannot get a write held by a replica that has read from the new one. For the failover to come: a leader that holds a lease (`Handle::fence`, with a `LeaseBackend`; a test backend only for now) takes writes only before its deadline (its last renew sent, plus the time to live, minus a margin); past it, writes and `/$/role/{name}` answer `503` (`lease-expired`), the wait for `--sync-replicas` ends at the deadline, and a write answered after it is not acknowledged (`503`). Without a lease and without a promotion, nothing changes. **Format:** a new file, `EPOCH`, which older releases ignore. See [read replicas](docs/server.md#read-replicas) and [docs/store-formats.md](docs/store-formats.md). diff --git a/crates/tripletrail-server/api/surface.txt b/crates/tripletrail-server/api/surface.txt index 85b4a663..2c472d6e 100644 --- a/crates/tripletrail-server/api/surface.txt +++ b/crates/tripletrail-server/api/surface.txt @@ -365,6 +365,10 @@ cli shapes import-atlas --out cli shapes import-atlas --prefix [default: ] cli shapes import-atlas cli store +cli store compact +cli store compact --dataset [default: ds] +cli store compact --location +cli store compact --memory-limit [env: TRIPLETRAIL_MEMORY_LIMIT] cli store info cli store info --dataset [default: ds] cli store info --json diff --git a/crates/tripletrail-server/src/main.rs b/crates/tripletrail-server/src/main.rs index e8895658..9282cd52 100644 --- a/crates/tripletrail-server/src/main.rs +++ b/crates/tripletrail-server/src/main.rs @@ -853,6 +853,24 @@ enum StoreCommand { #[arg(long, conflicts_with = "dry_run")] finish: bool, }, + /// Rewrites a dataset on disk with only the terms its quads still use (#759), offline, + /// giving back the space of the terms deletes left behind. The next checkpoint holds the + /// live terms and every index sorted again; the answers are the same. A crash leaves the + /// dataset as it was. Needs room for one more checkpoint of the live data and, besides + /// the sort, a bit per term of memory (the kept keys are streamed to disk). A dataset a + /// server has open is refused, and so is one whose files an older release wrote (run + /// `store upgrade` first, which keeps a restore point). + Compact { + /// Directory of the on-disk datasets. + #[arg(long)] + location: PathBuf, + #[arg(long, default_value = "ds")] + dataset: String, + /// Memory the sort of the quads may use (e.g. 32G; suffixes K, M, G, T), as for + /// `load`: past it, they are sorted on disk. No limit by default. + #[arg(long, env = "TRIPLETRAIL_MEMORY_LIMIT", value_parser = parse_size)] + memory_limit: Option, + }, /// Makes the restore point of the last upgrade current again (#517): the checkpoint and log /// of before the upgrade, so that the release that wrote them opens the dataset. Says what /// it drops: the transactions and checkpoints written since the upgrade. Refuses, changing @@ -4571,6 +4589,19 @@ fn run() -> Result<()> { finish, }, } => offline::store_upgrade(&location, &dataset, dry_run, finish), + Command::Store { + command: + StoreCommand::Compact { + location, + dataset, + memory_limit, + }, + } => { + if let Some(bytes) = memory_limit { + tripletrail::store::Store::set_memory_limit(bytes); + } + offline::store_compact(&location, &dataset) + } Command::Store { command: StoreCommand::Rollback { diff --git a/crates/tripletrail-server/src/offline.rs b/crates/tripletrail-server/src/offline.rs index 9de9d5b8..22df7dd5 100644 --- a/crates/tripletrail-server/src/offline.rs +++ b/crates/tripletrail-server/src/offline.rs @@ -559,6 +559,28 @@ pub(crate) fn store_info(location: &Path, dataset: &str, json: bool) -> Result<( Ok(()) } +/// `tripletrail store compact` (#759): the dataset rewritten without its dead terms. +pub(crate) fn store_compact(location: &Path, dataset: &str) -> Result<()> { + let dir = store_dir(location, dataset)?; + let started = std::time::Instant::now(); + let done = tripletrail::store::Store::compact(&dir, &mut |line| eprintln!("compact: {line}")) + .map_err(|e| store_error(dataset, e))?; + if done.dropped() == 0 { + println!("dataset {dataset} has no dead terms: nothing to do"); + return Ok(()); + } + let text = tripletrail::store::bytes_text; + println!( + "dataset {dataset} compacted in {:.1} s: {} of {} terms dropped, checkpoint {} instead of {}", + started.elapsed().as_secs_f64(), + done.dropped(), + done.terms_before, + text(done.bytes_after), + text(done.bytes_before), + ); + Ok(()) +} + /// `tripletrail store upgrade` (#516). pub(crate) fn store_upgrade( location: &Path, diff --git a/crates/tripletrail-server/tests/offline.rs b/crates/tripletrail-server/tests/offline.rs index 5c5cd7a7..9fb2398e 100644 --- a/crates/tripletrail-server/tests/offline.rs +++ b/crates/tripletrail-server/tests/offline.rs @@ -594,3 +594,36 @@ fn a_command_that_exits_during_an_index_save_leaves_it_whole() { ); assert!(!names.iter().any(|n| n.ends_with(".tmp")), "{names:?}"); } + +/// `tripletrail store compact` (#759): the dataset without the terms a delete left behind, +/// with the same answers. +#[test] +fn store_compact_drops_dead_terms() { + let dir = scratch("compact"); + ok(tripletrail( + &dir, + &["load", "--location", "db", "a.ttl", "g.nq"], + )); + ok(tripletrail( + &dir, + &[ + "update", + "--location", + "db", + "--update", + "DELETE WHERE { ?s \"B\" }", + ], + )); + let before = ok(tripletrail(&dir, &["dump", "--location", "db"])); + let out = ok(tripletrail(&dir, &["store", "compact", "--location", "db"])); + assert!(out.contains("dataset ds compacted in"), "{out}"); + assert!(out.contains("1 of "), "{out}"); + assert_eq!(ok(tripletrail(&dir, &["dump", "--location", "db"])), before); + let again = ok(tripletrail(&dir, &["store", "compact", "--location", "db"])); + assert_eq!(again, "dataset ds has no dead terms: nothing to do\n"); + let refused = tripletrail( + &dir, + &["store", "compact", "--location", "db", "--dataset", "x"], + ); + assert!(!refused.status.success()); +} diff --git a/crates/tripletrail-server/tests/upgrade_in_place.rs b/crates/tripletrail-server/tests/upgrade_in_place.rs index e0c39858..6a216f35 100644 --- a/crates/tripletrail-server/tests/upgrade_in_place.rs +++ b/crates/tripletrail-server/tests/upgrade_in_place.rs @@ -787,3 +787,101 @@ fn a_kill_during_the_automatic_upgrade_is_finished_by_the_next_start() { before ); } + +/// A full ordered dump of the dataset `kg` on `served`: every quad, graph by graph. +const DUMP: &str = "SELECT ?g ?s ?p ?o WHERE { { ?s ?p ?o } UNION { GRAPH ?g { ?s ?p ?o } } } ORDER BY ?g ?s ?p ?o"; + +/// The answers to compare before and after a compaction: the four fixture queries and the +/// full dump. +fn answers(served: &Served) -> Vec { + let mut queries: Vec = std::fs::read_dir(upgrade_dir().join("queries")) + .unwrap() + .map(|e| e.unwrap().path()) + .collect(); + queries.sort(); + let mut out: Vec = queries + .iter() + .map(|q| served.csv(&std::fs::read_to_string(q).unwrap())) + .collect(); + out.push(served.csv(DUMP)); + out +} + +/// `tripletrail store compact` (#759) on each release's dataset, served first (so its +/// routing network and spatial index are saved, and its files upgraded with a restore point) +/// and then left with about 400 early terms dead (`up/s0_0` and every label): the same +/// answers to the fixture queries and the same full dump, caches built again for the new +/// checkpoint, and a dataset that takes writes. +#[test] +fn every_release_is_compacted_with_the_same_answers() { + for (version, fixture) in fixtures() { + let dir = tripletrail_testdir::tempdir("store-compact"); + copy(&fixture.join("data"), &dir); + let served = Served::start(&dir, &version); + served.update( + "DELETE WHERE { ?p ?o } ; \ + DELETE WHERE { GRAPH ?g { ?p ?o } } ; \ + DELETE WHERE { ?s ?l } ; \ + DELETE WHERE { GRAPH ?g { ?s ?l } }", + ); + assert_eq!(served.csv(COUNT_S0), "n\n0\n", "{version}"); + let before = answers(&served); + served.stop(); + let (ok, out, err) = store_command(&["compact"], &dir); + assert!(ok, "{version}: {err}"); + let dropped: u64 = out + .split("compacted in ") + .nth(1) + .and_then(|rest| rest.split(": ").nth(1)) + .and_then(|rest| rest.split(' ').next()) + .and_then(|n| n.parse().ok()) + .unwrap_or_else(|| panic!("{version}: {out}")); + assert!(dropped > 100, "{version}: {out}"); + let info = store_info(&dir); + assert_eq!(info["upToDate"], true, "{version}: {info}"); + let served = Served::start(&dir, &version); + let after = answers(&served); + for (b, a) in before.iter().zip(&after) { + assert_eq!(a, b, "{version}: answers otherwise after the compaction"); + } + served.update( + "INSERT DATA { \"Added after the compaction\" }", + ); + assert_eq!(served.csv(COUNT_NEW), "n\n1\n"); + served.stop(); + } +} + +/// `store compact` refuses a dataset whose files are of an older version, rather than +/// upgrading it with no restore point: `store upgrade` first, which keeps one. +#[test] +fn store_compact_refuses_a_dataset_not_up_to_date() { + let mut refused = 0; + for (version, fixture) in fixtures() { + let dir = tripletrail_testdir::tempdir("compact-refuse"); + copy(&fixture.join("data"), &dir); + if store_info(&dir)["upToDate"] == true { + continue; + } + let before = files(&dir.join("kg")); + let (ok, _, err) = store_command(&["compact"], &dir); + assert!(!ok, "{version}: compacted a dataset not up to date"); + assert!( + err.contains("is not up to date") && err.contains("store upgrade first"), + "{version}: {err}" + ); + assert_eq!(files(&dir.join("kg")), before, "{version}: changed"); + refused += 1; + // After `store upgrade`, with its restore point kept, it is compacted. + let (ok, _, err) = store_command(&["upgrade"], &dir); + assert!(ok, "{version}: {err}"); + let (ok, out, err) = store_command(&["compact"], &dir); + assert!(ok, "{version}: {err}"); + assert!(out.contains("dataset kg "), "{version}: {out}"); + assert!( + !store_info(&dir)["restorePoint"].is_null(), + "{version}: the restore point of the upgrade" + ); + } + assert!(refused > 0, "no release fixture is of an older version"); +} diff --git a/crates/tripletrail-store/examples/dict_churn.rs b/crates/tripletrail-store/examples/dict_churn.rs index 6aff6be8..b5d851c6 100644 --- a/crates/tripletrail-store/examples/dict_churn.rs +++ b/crates/tripletrail-store/examples/dict_churn.rs @@ -2,7 +2,9 @@ //! objects are literals (strings, and WKT points every third), then runs `rounds` rounds that //! each delete 10 % of them and insert as many with new literals, with a checkpoint after //! each. Prints the sizes of `dict*.bin`, `dict*.idx`, `geoms*.bin` and the whole directory, -//! and the dead terms (`Store::dead_terms`), after the load and after every round. +//! and the dead terms (`Store::dead_terms`), after the load and after every round. Then the +//! store is compacted (`Store::compact`, #759), and the same quads are loaded fresh into +//! `-fresh`, each with a row of its own. //! //! `cargo run --release -p tripletrail-store --example dict_churn [n] [rounds]` use oxigraph::model::{GraphName, Literal, NamedNode, Quad}; @@ -113,4 +115,41 @@ fn main() { store.checkpoint().unwrap(); store = report(round, store); } + let quads: Vec = store.iter().collect(); + drop(store); + let started = std::time::Instant::now(); + let done = Store::compact(dir, &mut |_| {}).unwrap(); + eprintln!( + "compacted in {:.1} s: {} of {} terms dropped", + started.elapsed().as_secs_f64(), + done.dropped(), + done.terms_before + ); + let mb_row = |label: &str, dir: &Path| { + let store = Store::open(dir).unwrap(); + let dead = store.dead_terms(&|| false).unwrap(); + println!( + "| {label} | {:.1} | {:.1} | {:.1} | {:.1} | {} | {} | {:.1} | {:.1} | {:.1} |", + mb(bytes(dir, "dict", ".bin")), + mb(bytes(dir, "dict", ".idx")), + mb(bytes(dir, "geoms", ".bin")), + mb(bytes(dir, "", "")), + dead.terms, + dead.dead, + 100.0 * dead.dead as f64 / dead.terms.max(1) as f64, + mb(dead.key_bytes), + mb(dead.geometry_bytes), + ); + }; + mb_row("compacted", dir); + let fresh_dir = dir.with_file_name(format!( + "{}-fresh", + dir.file_name().unwrap().to_string_lossy() + )); + { + let fresh = Store::open(&fresh_dir).unwrap(); + fresh.bulk_load_quads(quads).unwrap(); + fresh.checkpoint().unwrap(); + } + mb_row("fresh load", &fresh_dir); } diff --git a/crates/tripletrail-store/src/compact.rs b/crates/tripletrail-store/src/compact.rs new file mode 100644 index 00000000..40888932 --- /dev/null +++ b/crates/tripletrail-store/src/compact.rs @@ -0,0 +1,289 @@ +//! `tripletrail store compact` (#759, decision record 0013 §1 and §4): a closed store +//! rewritten with only the terms its quads still use. +//! +//! The dictionary only grows: a term a delete leaves unused keeps its key, and a WKT literal +//! its saved geometry. Compaction writes the next checkpoint from the live terms alone, +//! numbered by **rank**: a live term's new ordinal is the number of live terms up to and +//! including it, so the order of the keys is kept and the dictionary is copied in one pass, +//! key by key, skipping the dead ones. The quads are renumbered and sorted again into every +//! permutation by the bulk load's sorter (an id's kind is in its low bits, so a smaller +//! payload can change the order of two ids), under the memory limit. +//! +//! The result is a checkpoint of the current format, written next to the current one as any +//! checkpoint: until `CURRENT` names it, the store is as it was, and a crash leaves the old +//! checkpoint whole (the unfinished one is removed at the next open, as any stale one). +//! The log is folded in, as by any checkpoint. Term ids are not stable across a compaction +//! (DR 0013, I4): nothing outside a checkpoint holds them, and caches keyed to a checkpoint, +//! such as the saved spatial index, are built again for the new one. + +use crate::dict::Dictionary; +use crate::index::{QuadIndex, Sorter}; +use crate::persist; +use crate::restore; +use crate::segment::Key; +use crate::{Store, StoreError, TermId}; +use std::path::Path; +use std::sync::Arc; +use tripletrail_geo::sync::{LockUnpoisoned, RwLockUnpoisoned}; + +/// What [`Store::compact`] did. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Compacted { + /// Terms in the dictionary before. + pub terms_before: u64, + /// Terms kept: those some quad uses. + pub terms_after: u64, + /// The quads, the same before and after. + pub quads: u64, + /// Bytes of the current checkpoint before (its files, the log not included). + pub bytes_before: u64, + /// Bytes of the new checkpoint. + pub bytes_after: u64, +} + +impl Compacted { + /// Terms dropped. + pub fn dropped(&self) -> u64 { + self.terms_before - self.terms_after + } +} + +/// The new ordinal of each live old one: a bit per old ordinal and, every 512 ordinals, the +/// live ones before (a `u32` per 64 bytes of bits, rather than a map of every term). +struct Ranks { + bits: Vec, + /// `before[b]`: live ordinals below `b * 512`. + before: Vec, +} + +const BLOCK_WORDS: usize = 8; + +impl Ranks { + fn new(bits: Vec) -> Self { + let mut before = Vec::with_capacity(bits.len() / BLOCK_WORDS + 1); + let mut count = 0u32; + for block in bits.chunks(BLOCK_WORDS) { + before.push(count); + count += block.iter().map(|w| w.count_ones()).sum::(); + } + Self { bits, before } + } + + fn is_live(&self, o: usize) -> bool { + self.bits[o / 64] & 1 << (o % 64) != 0 + } + + /// The new ordinal of the live ordinal `o`: the live ordinals up to and including it + /// (ordinal 0 is never live, so the first live one becomes 1). + fn rank(&self, o: usize) -> u64 { + let word = o / 64; + let block = word / BLOCK_WORDS; + let mut n = u64::from(self.before[block]); + for w in &self.bits[block * BLOCK_WORDS..word] { + n += u64::from(w.count_ones()); + } + let mask = if o % 64 == 63 { + u64::MAX + } else { + (1u64 << (o % 64 + 1)) - 1 + }; + n + u64::from((self.bits[word] & mask).count_ones()) + } + + /// The live ordinal whose new ordinal is `n` (1 for the first live one): the inverse of + /// [`Ranks::rank`], found by a binary search over the blocks and a scan of one. + fn select(&self, n: u64) -> usize { + let n = n as u32; + // The last block with fewer live ordinals before it than `n`. + let block = self.before.partition_point(|&b| b < n) - 1; + let mut left = n - self.before[block]; + let mut word = block * BLOCK_WORDS; + loop { + let ones = self.bits[word].count_ones(); + if left <= ones { + break; + } + left -= ones; + word += 1; + } + let mut w = self.bits[word]; + for _ in 1..left { + w &= w - 1; + } + word * 64 + w.trailing_zeros() as usize + } + + /// `id` renumbered: a dictionary id by the rank of its ordinal, any other as it is. + fn id(&self, id: u64) -> u64 { + let t = TermId(id); + if !t.is_dictionary() { + return id; + } + TermId::new(t.kind(), self.rank(t.payload() as usize)).0 + } +} + +/// Bytes of the files in `dir`. +fn dir_bytes(dir: &Path) -> u64 { + std::fs::read_dir(dir) + .map(|entries| { + entries + .flatten() + .filter_map(|e| e.metadata().ok()) + .filter(|m| m.is_file()) + .map(|m| m.len()) + .sum() + }) + .unwrap_or(0) +} + +impl Store { + /// Rewrites the closed store in `dir` with only the terms its quads still use (#759): the + /// next checkpoint holds the live terms, renumbered, and the space of the dead ones is + /// given back. The store's answers are the same. Refused while another process has the + /// store open, while an upgrade waits for `store rollback` or `store upgrade --finish`, + /// and for a store whose files are of an older version (`store upgrade` first). The keys + /// kept are written to a file as they are read, not held on the heap. A store without dead terms is left as it is. + pub fn compact( + dir: impl AsRef, + progress: &mut dyn FnMut(&str), + ) -> Result { + let dir = dir.as_ref(); + if !dir.join("CURRENT").is_file() && !dir.join("FORMAT").is_file() { + return Err(StoreError::Unsupported(format!( + "{} is not a TripleTrail store (no FORMAT or CURRENT file)", + dir.display() + ))); + } + restore::check_no_rollback(dir)?; + // Its checkpoint is written in the formats of this build: an older store would be + // upgraded with no restore point, which `store upgrade` keeps. + if !Store::store_info(dir)?.up_to_date() { + return Err(StoreError::Unsupported(format!( + "{} is not up to date with this TripleTrail: run tripletrail store upgrade first (it keeps a restore point), then store compact", + dir.display() + ))); + } + let store = Store::open(dir)?; + store.compact_closed(progress) + } + + /// [`Store::compact`] of this store, opened for it alone: it cannot be used afterwards + /// (its writer is closed), as its data in memory is that of the old checkpoint. + fn compact_closed(self, progress: &mut dyn FnMut(&str)) -> Result { + let inner = &self.inner; + // Nothing but this may write any more: background merges stop first. + inner + .closed + .store(true, std::sync::atomic::Ordering::SeqCst); + loop { + let threads = std::mem::take(&mut *inner.merge_threads.lock_unpoisoned()); + if threads.is_empty() { + break; + } + for thread in threads { + let _ = thread.join(); + } + } + let mut writer = self.lock_writer()?; + let Some(disk) = writer.as_mut() else { + return Err(StoreError::Unsupported( + "only a store on disk can be compacted".into(), + )); + }; + self.wait_verified()?; + let (old_dir, _) = persist::generation_paths(disk.dir(), disk.generation()); + let bytes_before = dir_bytes(&old_dir); + let mut quads = inner.quads.read_unpoisoned().clone(); + quads.spill = Some(Arc::clone(&disk.spill)); + quads.compact(); + let dict = inner.dict.read_unpoisoned(); + let terms = dict.len(); + progress(&format!("reading the quads of {terms} terms")); + let mut bits = vec![0u64; terms / 64 + 1]; + let mut count = 0u64; + for q in quads.iter() { + count += 1; + for id in q { + let t = TermId(id); + if t.is_dictionary() { + let o = t.payload() as usize; + if o <= terms { + bits[o / 64] |= 1 << (o % 64); + } + } + } + } + let ranks = Ranks::new(bits); + let live = if terms == 0 { 0 } else { ranks.rank(terms) }; + let mut report = Compacted { + terms_before: terms as u64, + terms_after: live, + quads: count, + bytes_before, + bytes_after: bytes_before, + }; + if live == terms as u64 { + progress("no dead terms: the store is left as it is"); + drop(dict); + writer.take(); + return Ok(report); + } + progress(&format!( + "keeping {live} of {terms} terms, renumbering {count} quads" + )); + let kept: Dictionary = dict.keep( + (1..=terms).filter(|&o| ranks.is_live(o)).map(|o| o as u32), + &disk.spill, + )?; + let mut sorter = Sorter::new(Some(Arc::clone(&disk.spill))); + for q in quads.iter() { + let k: Key = q.map(|id| ranks.id(id)); + sorter.push(k); + } + drop(quads); + let mut index = QuadIndex::from_sorter(sorter, None, None); + index.spill = Some(Arc::clone(&disk.spill)); + index.compact(); + progress("writing the new checkpoint"); + { + // The geometries of the kept terms, read by their old ordinals. + let encode = |o: u32, out: &mut Vec| { + inner.encode_geometry(&dict, ranks.select(u64::from(o)) as u32, out) + }; + disk.checkpoint(&kept, &index, &encode, self.render_wkt(), true)?; + } + let (new_dir, _) = persist::generation_paths(disk.dir(), disk.generation()); + report.bytes_after = dir_bytes(&new_dir); + let (store_dir, generation) = (disk.dir().to_owned(), disk.generation()); + drop(dict); + // The data in memory is the old checkpoint's: the writer goes, so nothing more is + // written from it. + writer.take(); + drop(writer); + drop(self); + persist::remove_stale_now(&store_dir, generation); + Ok(report) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ranks_count_the_live_ordinals_up_to_each() { + let live = [1usize, 2, 63, 64, 65, 511, 512, 513, 1000, 4095]; + let mut bits = vec![0u64; 4096 / 64 + 1]; + for &o in &live { + bits[o / 64] |= 1 << (o % 64); + } + let ranks = Ranks::new(bits); + for (i, &o) in live.iter().enumerate() { + assert!(ranks.is_live(o)); + assert_eq!(ranks.rank(o), i as u64 + 1, "{o}"); + assert_eq!(ranks.select(i as u64 + 1), o, "{o}"); + } + assert!(!ranks.is_live(3)); + } +} diff --git a/crates/tripletrail-store/src/dict.rs b/crates/tripletrail-store/src/dict.rs index adc6a737..b2824964 100644 --- a/crates/tripletrail-store/src/dict.rs +++ b/crates/tripletrail-store/src/dict.rs @@ -1258,6 +1258,32 @@ impl Dictionary { }) } + /// A dictionary of the keys at `ordinals` (ascending), numbered 1, 2, ... in that order + /// (#759): each key as stored, with the same namespaces, written by `spill` to a file as + /// it is read and mapped from there, so the keys are never all on the heap. Its table is + /// left empty: it is only for writing a checkpoint, not for lookups. + pub(crate) fn keep( + &self, + ordinals: impl Iterator, + spill: &crate::persist::Spill, + ) -> std::io::Result { + let (bytes, ends) = + self.reading_in_order(|| spill.map_keys_from(ordinals.map(|o| self.raw_key(o))))?; + Ok(Self { + pieces: vec![Piece { + first: 1, + bytes, + ends, + index: None, + spilled: true, + }], + table: HashTable::new(), + hasher: Hasher::default(), + compact: self.compact, + ns: self.ns.clone(), + }) + } + /// Rebuilds a dictionary from saved pieces of consecutive keys, each /// [`Dictionary::valid_parts`]. pub(crate) fn from_pieces(saved: Vec) -> Self { diff --git a/crates/tripletrail-store/src/lib.rs b/crates/tripletrail-store/src/lib.rs index dcdfdde8..aacb2c33 100644 --- a/crates/tripletrail-store/src/lib.rs +++ b/crates/tripletrail-store/src/lib.rs @@ -16,6 +16,7 @@ mod bgp; mod buf; +mod compact; mod dataset; mod dict; pub mod entail; @@ -42,6 +43,7 @@ pub use bgp::{ BgpCount, CompiledBgp, DEFAULT_JOIN_MEMORY, IdRows, IdSlot, IdTriple, join_memory, memory_limit, set_join_memory, with_join_memory, }; +pub use compact::Compacted; pub use dataset::{Dataset, DatasetError, QuadIter, RowView}; pub use dict::KindUsage; pub use labels::BlankNodes; diff --git a/crates/tripletrail-store/src/persist.rs b/crates/tripletrail-store/src/persist.rs index e788f5a9..52faad3c 100644 --- a/crates/tripletrail-store/src/persist.rs +++ b/crates/tripletrail-store/src/persist.rs @@ -3241,6 +3241,50 @@ impl Spill { )) } + /// [`Spill::map_keys`] of keys given one at a time (#759): the keys and their ends go to + /// two files as they come, so neither is held on the heap. + pub(crate) fn map_keys_from<'k>( + &self, + keys: impl Iterator, + ) -> io::Result<(Buf, Buf)> { + let (n, keys_path, keys_file) = loop { + let n = self.next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = self.dir.join(format!("{n}.keys")); + match File::options().write(true).create_new(true).open(&path) { + Ok(f) => break (n, path, f), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(e), + } + }; + let ends_path = self.dir.join(format!("{n}.ends")); + let ends_file = File::options() + .write(true) + .create_new(true) + .open(&ends_path)?; + let (mut kw, mut ew) = (BufWriter::new(keys_file), BufWriter::new(ends_file)); + let (mut at, mut count) = (0u64, 1usize); + ew.write_all(&0u64.to_le_bytes())?; + for key in keys { + kw.write_all(key)?; + at += key.len() as u64; + ew.write_all(&at.to_le_bytes())?; + count += 1; + } + // An empty file cannot be mapped everywhere: a byte past the keys. + kw.write_all(&[0])?; + kw.into_inner().map_err(io::IntoInnerError::into_error)?; + ew.into_inner().map_err(io::IntoInnerError::into_error)?; + let keys_map = Mapped::open(keys_path.clone()).map_err(io::Error::other)?; + let ends_map = Mapped::open(ends_path.clone()).map_err(io::Error::other)?; + let _ = fs::remove_file(&keys_path); + let _ = fs::remove_file(&ends_path); + let bad = || io::Error::other("dictionary keys written short"); + Ok(( + Buf::mapped(&keys_map.map, 0, at as usize).ok_or_else(bad)?, + Buf::mapped(&ends_map.map, 0, count).ok_or_else(bad)?, + )) + } + /// A new segment file. pub(crate) fn writer(&self) -> io::Result { // A new name: a merge still running for an earlier opening of the store may hold diff --git a/crates/tripletrail-store/tests/compact.rs b/crates/tripletrail-store/tests/compact.rs new file mode 100644 index 00000000..71d81a44 --- /dev/null +++ b/crates/tripletrail-store/tests/compact.rs @@ -0,0 +1,390 @@ +//! `Store::compact` (#759, DR 0013 §1 and §4): a closed store rewritten with only the terms +//! its quads use. After churn it is about the size of a fresh load of the same quads, its +//! answers are the same, and a kill in the middle leaves the store as it was. + +use oxigraph::model::{ + BlankNode, GraphName, Literal, NamedNode, NamedOrBlankNode, Quad, Term, Triple, +}; +use std::collections::BTreeSet; +use std::path::Path; +use tripletrail_store::{Store, StoreError}; + +const WKT: &str = "http://www.opengis.net/ont/geosparql#wktLiteral"; + +/// The quad of subject `i` in generation `g`: its object changes with the generation. Every +/// third object is a WKT point; the others are strings, language strings, typed literals, +/// blank nodes and triple terms, in named graphs too. +fn quad(i: usize, g: usize) -> Quad { + let s = NamedNode::new_unchecked(format!("http://example.org/s{i}")); + let (p, o): (&str, Term) = match i % 6 { + 0 | 3 => ( + "geometry", + Literal::new_typed_literal( + format!( + "POINT({:.6} {:.6})", + 4.0 + (i % 1000) as f64 / 1000.0 + g as f64 * 1e-5, + 50.0 + (i / 1000 % 1000) as f64 / 1000.0 + ), + NamedNode::new_unchecked(WKT), + ) + .into(), + ), + 1 => ( + "label", + Literal::new_language_tagged_literal_unchecked(format!("station {i} v{g}"), "nl") + .into(), + ), + 2 => ( + "note", + Literal::new_typed_literal( + format!("code-{i}-{g}"), + NamedNode::new_unchecked("http://example.org/Code"), + ) + .into(), + ), + 4 => ("node", BlankNode::new_unchecked(format!("b{i}g{g}")).into()), + _ => ( + "said", + Triple::new( + NamedNode::new_unchecked(format!("http://example.org/a{i}")), + NamedNode::new_unchecked("http://example.org/p"), + Literal::new_simple_literal(format!("value {g}")), + ) + .into(), + ), + }; + let graph = if i.is_multiple_of(5) { + GraphName::NamedNode(NamedNode::new_unchecked(format!( + "http://example.org/g{}", + g % 3 + ))) + } else { + GraphName::DefaultGraph + }; + Quad::new( + NamedOrBlankNode::NamedNode(s), + NamedNode::new_unchecked(format!("http://example.org/{p}")), + o, + graph, + ) +} + +/// Bytes of the current checkpoint's files whose names start with `prefix` and end with +/// `suffix`. +fn bytes(dir: &Path, prefix: &str, suffix: &str) -> u64 { + let n = std::fs::read_to_string(dir.join("CURRENT")).unwrap(); + let checkpoint = dir.join(format!("checkpoint-{}", n.trim())); + std::fs::read_dir(checkpoint) + .unwrap() + .flatten() + .filter(|e| { + let name = e.file_name().to_string_lossy().into_owned(); + name.starts_with(prefix) && name.ends_with(suffix) + }) + .map(|e| e.metadata().unwrap().len()) + .sum() +} + +fn terms_bytes(dir: &Path) -> u64 { + bytes(dir, "dict", ".bin") + bytes(dir, "geoms", ".bin") +} + +fn answers(store: &Store) -> BTreeSet { + store.iter().map(|q| q.to_string()).collect() +} + +/// A store of `n` subjects after `rounds` rounds that each replace a tenth of them, with a +/// checkpoint after each; the subjects' current generations. +fn churned(dir: &Path, n: usize, rounds: usize) -> Vec { + let store = Store::open(dir).unwrap(); + store.bulk_load_quads((0..n).map(|i| quad(i, 0))).unwrap(); + store.checkpoint().unwrap(); + let mut generation = vec![0usize; n]; + for round in 1..=rounds { + let chosen: Vec = (0..n).filter(|i| i % 10 == (round - 1) % 10).collect(); + store + .transaction(|txn| { + for &i in &chosen { + txn.remove(quad(i, generation[i]).as_ref()); + txn.insert(quad(i, round).as_ref()); + } + Ok::<_, StoreError>(()) + }) + .unwrap(); + for &i in &chosen { + generation[i] = round; + } + store.checkpoint().unwrap(); + } + generation +} + +#[test] +fn compaction_gives_back_the_space_of_dead_terms() { + let n = 20_000; + let dir = tripletrail_testdir::tempdir("compact-churn"); + let generation = churned(&dir, n, 10); + // A last transaction stays in the log: compaction folds it in. + { + let store = Store::open(&dir).unwrap(); + store + .transaction(|txn| { + txn.insert(quad(n, 99).as_ref()); + Ok::<_, StoreError>(()) + }) + .unwrap(); + } + let (before, grown, dead) = { + let store = Store::open(&dir).unwrap(); + let dead = store.dead_terms(&|| false).unwrap(); + (answers(&store), terms_bytes(&dir), dead) + }; + assert!(dead.dead > 0, "{dead:?}"); + + let mut lines = Vec::new(); + let report = Store::compact(&dir, &mut |l| lines.push(l.to_owned())).unwrap(); + assert_eq!(report.terms_before, dead.terms, "{report:?}"); + assert_eq!(report.dropped(), dead.dead, "{report:?}"); + assert_eq!(report.quads as usize, before.len(), "{report:?}"); + assert!(report.bytes_after < report.bytes_before, "{report:?}"); + assert!(!lines.is_empty()); + + // The same answers, from the new checkpoint, with no dead terms left. + let store = Store::open(&dir).unwrap(); + assert_eq!(answers(&store), before); + assert_eq!(store.dead_terms(&|| false).unwrap().dead, 0); + // Geometries are read from the saved ones of the new checkpoint. + for i in (0..n) + .step_by(3) + .filter(|i| i % 6 == 0 || i % 6 == 3) + .take(50) + { + let q = quad(i, generation[i]); + let g = store.geometry(q.object.as_ref()).unwrap(); + assert!( + format!("{:?}", g.geometry).starts_with("POINT(4."), + "{q} {:?}", + g.geometry + ); + } + // The store takes writes, and a term dropped can come back. + store + .transaction(|txn| { + txn.insert(quad(1, 0).as_ref()); + txn.remove(quad(n, 99).as_ref()); + Ok::<_, StoreError>(()) + }) + .unwrap(); + store.checkpoint().unwrap(); + drop(store); + let store = Store::open(&dir).unwrap(); + let mut expected = before.clone(); + expected.insert(quad(1, 0).to_string()); + expected.remove(&quad(n, 99).to_string()); + assert_eq!(answers(&store), expected); + drop(store); + + // About the size of a fresh load of the same quads. + let fresh_dir = tripletrail_testdir::tempdir("compact-fresh"); + let compacted = terms_bytes(&dir); + { + let fresh = Store::open(&fresh_dir).unwrap(); + let quads: Vec = Store::open(&dir).unwrap().iter().collect(); + fresh.bulk_load_quads(quads).unwrap(); + fresh.checkpoint().unwrap(); + } + let fresh = terms_bytes(&fresh_dir); + assert!( + compacted as f64 <= fresh as f64 * 1.03, + "compacted {compacted} bytes, fresh load {fresh}, before {grown}" + ); + assert!(compacted < grown, "compacted {compacted}, before {grown}"); +} + +#[test] +fn a_store_without_dead_terms_is_left_as_it_is() { + let dir = tripletrail_testdir::tempdir("compact-nothing"); + { + let store = Store::open(&dir).unwrap(); + store + .bulk_load_quads((0..1000).map(|i| quad(i, 0))) + .unwrap(); + store.checkpoint().unwrap(); + } + let current = std::fs::read_to_string(dir.join("CURRENT")).unwrap(); + let report = Store::compact(&dir, &mut |_| {}).unwrap(); + assert_eq!(report.dropped(), 0); + assert_eq!(report.bytes_after, report.bytes_before); + assert_eq!( + std::fs::read_to_string(dir.join("CURRENT")).unwrap(), + current + ); +} + +#[test] +fn compaction_refuses_what_is_not_a_store() { + let dir = tripletrail_testdir::tempdir("compact-none"); + let e = Store::compact(&dir, &mut |_| {}).unwrap_err(); + assert!(e.to_string().contains("not a TripleTrail store"), "{e}"); +} + +#[test] +fn compaction_refuses_a_store_open_elsewhere() { + let dir = tripletrail_testdir::tempdir("compact-locked"); + churned(&dir, 1000, 1); + let _open = Store::open(&dir).unwrap(); + assert!(Store::compact(&dir, &mut |_| {}).is_err()); +} + +/// The fixture of an older release (CRS tags, #456): refused while its files are of an older +/// version (compaction would upgrade it with no restore point), compacted after +/// `Store::upgrade`, with the same answers and the upgrade's restore point kept. +#[test] +fn an_older_store_is_compacted_after_its_upgrade() { + let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/crs-tags-0.3.0"); + let dir = tripletrail_testdir::tempdir("compact-fixture"); + copy_dir(&fixture, &dir); + let before = { + let store = Store::open(&dir).unwrap(); + let before = answers(&store); + // A term to drop. + let q = store.iter().next().unwrap(); + store + .transaction(|txn| { + txn.remove(q.as_ref()); + Ok::<_, StoreError>(()) + }) + .unwrap(); + let mut after = before; + after.remove(&q.to_string()); + after + }; + let info = Store::store_info(&dir).unwrap(); + assert!(!info.up_to_date(), "{info:?}"); + let before_files = files(&dir); + let refused = Store::compact(&dir, &mut |_| {}).unwrap_err().to_string(); + assert!( + refused.contains("not up to date") && refused.contains("store upgrade first"), + "{refused}" + ); + assert_eq!(files(&dir), before_files, "a refusal changes nothing"); + Store::upgrade(&dir, &mut |_| {}).unwrap(); + let report = Store::compact(&dir, &mut |_| {}).unwrap(); + assert!(report.dropped() > 0, "{report:?}"); + let store = Store::open(&dir).unwrap(); + assert_eq!(answers(&store), before); + drop(store); + let info = Store::store_info(&dir).unwrap(); + assert!(info.up_to_date(), "{info:?}"); + assert!(info.restore_point.is_some(), "{info:?}"); +} + +/// Every file under `dir` with its bytes, the lock file aside. +fn files(dir: &Path) -> Vec<(std::path::PathBuf, Vec)> { + let mut out = Vec::new(); + let mut stack = vec![dir.to_owned()]; + while let Some(d) = stack.pop() { + for e in std::fs::read_dir(&d).unwrap().flatten() { + if e.file_type().unwrap().is_dir() { + stack.push(e.path()); + } else if e.file_name() != "LOCK" { + out.push((e.path(), std::fs::read(e.path()).unwrap())); + } + } + } + out.sort(); + out +} + +fn copy_dir(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for e in std::fs::read_dir(from).unwrap().flatten() { + let target = to.join(e.file_name()); + if e.file_type().unwrap().is_dir() { + copy_dir(&e.path(), &target); + } else { + std::fs::copy(e.path(), target).unwrap(); + } + } +} + +#[test] +#[ignore = "run by a_kill_during_compaction_leaves_the_store_whole as a child process"] +fn compact_child() { + use std::io::Write; + let Ok(dir) = std::env::var("TRIPLETRAIL_COMPACT_DIR") else { + return; + }; + let mut out = std::io::stdout().lock(); + Store::compact(&dir, &mut |line| { + let _ = writeln!(out, "{line}"); + let _ = out.flush(); + }) + .unwrap(); + let _ = writeln!(out, "done"); +} + +/// A compaction killed (SIGKILL) in each of its steps (reading the quads, sorting them, +/// writing the checkpoint) leaves a store that opens with the same quads and nothing of the +/// unfinished checkpoint, and a later compaction finishes. +#[cfg(unix)] +#[test] +fn a_kill_during_compaction_leaves_the_store_whole() { + use std::io::{BufRead, BufReader}; + use std::process::{Command, Stdio}; + let template = tripletrail_testdir::tempdir("compact-kill-template"); + churned(&template, 60_000, 10); + let expected = answers(&Store::open(&template).unwrap()); + let steps = ["reading", "keeping", "writing"]; + let mut rng = 0x2545_f491_4f6c_dd1d_u64; + let mut killed = 0; + for round in 0..6 { + let dir = tripletrail_testdir::tempdir(&format!("compact-kill-{round}")); + copy_dir(&template, &dir); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "compact_child", + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .env("TRIPLETRAIL_COMPACT_DIR", &dir) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + // Killed a moment after the step of this round starts. + let step = steps[round % steps.len()]; + let mut lines = BufReader::new(child.stdout.take().unwrap()).lines(); + let started = lines + .by_ref() + .map_while(Result::ok) + .any(|l| l.contains(step)); + assert!(started, "round {round}: the child did not reach {step}"); + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + std::thread::sleep(std::time::Duration::from_millis(rng % 40)); + let _ = child.kill(); + child.wait().unwrap(); + if !lines.map_while(Result::ok).any(|l| l.ends_with("done")) { + killed += 1; + } + let store = Store::open(&dir).unwrap(); + assert_eq!(answers(&store), expected, "round {round}"); + drop(store); + // Nothing of an unfinished checkpoint is left once the store opened. + let n = std::fs::read_to_string(dir.join("CURRENT")).unwrap(); + let n: u64 = n.trim().parse().unwrap(); + assert!( + !dir.join(format!("checkpoint-{}", n + 1)).exists(), + "round {round}" + ); + let report = Store::compact(&dir, &mut |_| {}).unwrap(); + let store = Store::open(&dir).unwrap(); + assert_eq!(answers(&store), expected, "round {round}"); + assert_eq!(store.dead_terms(&|| false).unwrap().dead, 0, "{report:?}"); + } + assert!(killed > 0, "every compaction finished before its kill"); +} diff --git a/docs/guide/11-fuseki.md b/docs/guide/11-fuseki.md index 3e4aaf6a..587dad4a 100644 --- a/docs/guide/11-fuseki.md +++ b/docs/guide/11-fuseki.md @@ -82,6 +82,7 @@ print(sparql.queryAndConvert()) |---|---| | `fuseki-server --loc=DB /kg` | `tripletrail serve --location DIR --dataset kg` | | `tdb2.tdbloader` | `tripletrail load --location DIR --dataset kg files…` | +| `tdb2.tdbcompact --loc=DB` | `tripletrail store compact --location DIR --dataset kg` (below) | | `/kg/query`, `/kg/sparql`, `/kg/update`, `/kg/data`, `/kg/get` | the same | | `/$/ping`, `/$/datasets`, `/$/backup`, `/$/backups-list`, `/$/tasks`, `/$/stats`, `/$/server` | the same paths and keys | | `/$/compact/kg`, `/$/sleep`, `/$/logs`, `/$/validate/…` | the same (below) | @@ -653,6 +654,29 @@ curl -s 'http://localhost:7878/$/validate/langtag?langtag=nl-BE' | grep -o '"val "valid":true ``` +Like TDB2, TripleTrail keeps the terms a delete leaves behind: a label replaced by another +stays in the dictionary. `tdb2.tdbcompact` drops them from a database no server has open, and +so does `tripletrail store compact`. It writes the dataset again with only the terms its data +still uses; the answers are the same, and a crash leaves the dataset as it was. Here on a copy +of the network loaded offline, whose station labels are deleted: + + +```sh +tripletrail load --location offline --dataset kg network.ttl +tripletrail update --location offline --dataset kg \ + --update 'DELETE WHERE { ?s ?label }' +tripletrail store compact --location offline --dataset kg | grep -o '[0-9]* of [0-9]* terms dropped' +``` + + +```text +11 of 108 terms dropped +``` + +`tripletrail disk-usage` shows how many terms are dead before you run it. A dataset whose files +an older release wrote is refused: run `tripletrail store upgrade` first, which keeps a restore +point for `store rollback`, then compact it. + ### RDF Patch Fuseki's patch service is at `/kg/patch`. It takes an RDF Patch, the format `tripletrail diff diff --git a/docs/server.md b/docs/server.md index 069f4bcc..13134e41 100644 --- a/docs/server.md +++ b/docs/server.md @@ -4715,6 +4715,19 @@ node already stored, give it an IRI, or load its triples in one file. - `tripletrail store info` and `tripletrail store upgrade` show the versions of a dataset folder's files and bring them to this build's (#516): see [upgrading TripleTrail](#upgrading-tripletrail). +- `tripletrail store compact --location DIR [--dataset ds] [--memory-limit SIZE]` rewrites a + dataset folder with only the terms its quads still use (#759), giving back the space of the + dead terms `disk-usage` counts. It writes the next checkpoint with the live terms, renumbered, + and every index sorted again (past `--memory-limit`, on disk, as for `load`); the answers are + the same. A crash leaves the dataset as it was, and running the command again starts over. + It needs room for one more checkpoint of the live data, prints `compact:` lines on standard + error as it goes and a line with the terms dropped and the checkpoint's size before and after, + and leaves a dataset without dead terms as it is. Besides the sort, it holds a bit per term + on the heap: the kept keys are written to a file as they are read, not held in memory. A + dataset a server has open is refused (stop the server, or run it on a copy of the folder), and + so is one whose files an older release wrote, which compaction would upgrade with no way + back: run `tripletrail store upgrade` first, which keeps a restore point (`store info` says + whether a dataset is up to date). See [compaction](store.md). - `tripletrail disk-usage --location DIR [--dataset ds] [--json]` shows what a dataset folder takes (#152): its files by kind, numbered pieces and runs counted under their kind (`dict.bin`, `geoms.bin`, `spog.seg`, …), and, read from every key, the dictionary's keys by diff --git a/docs/store.md b/docs/store.md index 020df8d1..567c34cc 100644 --- a/docs/store.md +++ b/docs/store.md @@ -536,6 +536,30 @@ there: `Engine::new_oxigraph()` or `TRIPLETRAIL_STORE=oxigraph`, `tripletrail se key: the terms no quad uses any more, their key bytes and their saved geometries' bytes (`tripletrail disk-usage`'s last line, `deadTerms` in its JSON, #758). The dictionary only grows: a delete leaves the terms of the quads it removes. +- **Compaction.** `Store::compact(dir)` (`tripletrail store compact`, #759, decision record 0013) + rewrites a closed store with only the terms its quads still use. Each live term gets as its new + ordinal its **rank**: the number of live terms up to and including it. The rank is read from a + bit per term and a count every 512 terms, so no map of every term is built, and the old + ordinal of a new one is found from them again by a search. The keys keep their order and are + streamed, skipping the dead ones, to a file in `runs/` that is mapped, not to the heap; the + checkpoint writes them from there as one dictionary piece with its index. So besides the sort + of the quads (bounded by the memory limit) the heap holds a bit per term. The saved + geometries are read by their old ordinals and copied. A store whose files are of an older + version is refused: the new checkpoint is in this build's formats, so compacting it would + upgrade it with no restore point; `Store::upgrade` (`store upgrade`) first keeps one. The quads are renumbered and every + permutation is sorted again by the bulk load's sorter, under the memory limit, because an + id's kind is in its low bits and a smaller payload can change the order of two ids. The result + is the next checkpoint, in the current format, written next to the current one; `CURRENT` + names it only once it is complete, so a crash leaves the store as it was, and the unfinished + checkpoint is removed at the next open. The log is folded in, as by any checkpoint. + **Term ids change** across a compaction: nothing outside a checkpoint holds them, and the + saved spatial index, keyed to its checkpoint, is built again for the new one. The namespaces + of compact IRI keys are kept as they are. A store without dead terms is left as it is. After + the churn of `examples/dict_churn.rs` (1M triples, 10 rounds each replacing a tenth, a third of + the terms dead), `dict*.bin` falls from 124.5 MB to 71.2 MB and `geoms*.bin` from 20.0 MB to + 10.0 MB, as in a fresh load of the same quads (71.2 MB and 10.0 MB); the segments are 18 % + larger than a fresh load's (22.0 MB against 18.7 MB), as the order of the ordinals differs. + The compaction took 0.7 s (release build). - **Upgrades in place.** A dataset written by a release opens with every later release as it is. Its checkpoints carry its files over: a checkpoint links the dictionary pieces and segments it did not change, and adds the new terms of a write as a new dictionary piece