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 @@ -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).
Expand Down
4 changes: 4 additions & 0 deletions crates/tripletrail-server/api/surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,10 @@ cli shapes import-atlas --out
cli shapes import-atlas --prefix [default: ]
cli shapes import-atlas <folder>
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
Expand Down
31 changes: 31 additions & 0 deletions crates/tripletrail-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize>,
},
/// 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
Expand Down Expand Up @@ -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 {
Expand Down
22 changes: 22 additions & 0 deletions crates/tripletrail-server/src/offline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
33 changes: 33 additions & 0 deletions crates/tripletrail-server/tests/offline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <http://ex/name> \"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());
}
98 changes: 98 additions & 0 deletions crates/tripletrail-server/tests/upgrade_in_place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
let mut queries: Vec<PathBuf> = std::fs::read_dir(upgrade_dir().join("queries"))
.unwrap()
.map(|e| e.unwrap().path())
.collect();
queries.sort();
let mut out: Vec<String> = 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 { <http://example.org/up/s0_0> ?p ?o } ; \
DELETE WHERE { GRAPH ?g { <http://example.org/up/s0_0> ?p ?o } } ; \
DELETE WHERE { ?s <http://www.w3.org/2000/01/rdf-schema#label> ?l } ; \
DELETE WHERE { GRAPH ?g { ?s <http://www.w3.org/2000/01/rdf-schema#label> ?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 { <http://example.org/up/new> <http://www.w3.org/2000/01/rdf-schema#label> \"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");
}
41 changes: 40 additions & 1 deletion crates/tripletrail-store/examples/dict_churn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
//! `<dir>-fresh`, each with a row of its own.
//!
//! `cargo run --release -p tripletrail-store --example dict_churn <new dir> [n] [rounds]`
use oxigraph::model::{GraphName, Literal, NamedNode, Quad};
Expand Down Expand Up @@ -113,4 +115,41 @@ fn main() {
store.checkpoint().unwrap();
store = report(round, store);
}
let quads: Vec<Quad> = 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);
}
Loading
Loading