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
3 changes: 3 additions & 0 deletions changelog.d/snapshot-install-record-inserts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## Changed

- Speed up snapshot installation on SQLite replicas by writing records and their link and uniqueness indexes in batches.
24 changes: 23 additions & 1 deletion runtime/crates/bench/tests/catalog_reindex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ struct Profiled {
fn kind(sql: &str) -> String {
let table = sql
.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.find(|w| w.starts_with("st_"))
.find(|w| w.starts_with("st_") || w.starts_with("sg_"))
.unwrap_or("-");
if sql.contains("'delete-all'") {
return format!("fts-delete-all:{table}");
Expand Down Expand Up @@ -505,6 +505,28 @@ fn compact_then_tail(
snapshot
}

/// Install the same snapshot into seven empty SQLite databases. Fixture
/// construction, database open, tail replay and indexed reads are untimed.
#[test]
#[ignore = "manual release timing (#1648)"]
fn snapshot_install_at_10k() {
let svc = FakeLogService::new();
let (writer_store, _) = store("install_writer", false);
let mut writer = open(&svc, writer_store, 101);
let snapshot = snapshot_then_tail(&svc, &mut writer, 10_000, 1, "tasks/t01*.md");
for run in 1..=7 {
let (device_store, stats) = store("install_device", false);
let mut device = open(&svc, device_store, 102);
stats.borrow_mut().clear();
let started = Instant::now();
device.install_only();
let elapsed = started.elapsed();
assert_eq!(device.r.head().seq, snapshot);
assert_eq!(device.r.store().record_count().unwrap(), 10_050);
report(&format!("snapshot install {run}"), elapsed, &stats);
}
}

/// A device opening a 10k collection for the first time: it installs a
/// snapshot, then applies a tail holding two catalog changes (a new type over
/// a tenth of the tasks, then a schema-only change) among ordinary entries.
Expand Down
50 changes: 50 additions & 0 deletions runtime/crates/platform-native/tests/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1088,6 +1088,56 @@ fn sql_staging_survives_a_restart_through_the_file_store() {
);
}

#[test]
fn staged_record_batches_replace_old_lookup_keys() {
use mdbn_store_file::SqlStore;
use mdbn_store_file::testing::replica::conformance::record;
use mdbn_store_file::testing::replica::store::Stage;
let dir = scratch("bulk-stage");
let idx = SqliteIndex::open(dir.join("i.db"), IndexDurability::Durable).unwrap();
let mut store = SqlStore::open(Rc::new(RefCell::new(idx))).unwrap();
let row = |n, key: &str| {
let mut r = record(n, &format!("r{n}.md"), key);
r.meta.links = vec![key.into(), key.into()];
r.meta.unique = vec![("slug".into(), key.into())];
r
};
let mut put = |rows| {
store
.commit(Tx {
stage: Stage::Put,
records_put: rows,
..Tx::default()
})
.unwrap();
};
put(vec![row(1, "previous chunk")]);
let mut rows: Vec<_> = (1..=101).map(|n| row(n, "shared")).collect();
rows.push(row(1, "final"));
put(rows);
assert_eq!(store.record_count().unwrap(), 0);
store
.commit(Tx {
stage: Stage::Swap,
..Tx::default()
})
.unwrap();
assert_eq!(store.record_count().unwrap(), 101);
let final_row = row(1, "final");
assert_eq!(
store.record(&final_row.id).unwrap(),
Some(final_row.clone())
);
for (key, count) in [("previous chunk", 0), ("shared", 100), ("final", 1)] {
let links = store.referrers(&[key.into()]).unwrap();
let holders = store.unique_holders("slug", key).unwrap();
assert_eq!(links.len(), count);
assert_eq!(holders.len(), count);
assert_eq!(links.contains(&final_row.id), key == "final");
assert_eq!(holders.contains(&final_row.id), key == "final");
}
}

/// The app-local tentative store over a Disposable SQLite index (as OPFS
/// reports): the raw SqlStore refuses it, the typed composition opens it,
/// passes store conformance, keeps pending rows across a reopen, never holds
Expand Down
89 changes: 82 additions & 7 deletions runtime/crates/store-file/src/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,84 @@ fn link_stmts(id: &Uuid, links: &[String], out: &mut Vec<Stmt>) {
}
}

/// Bind complete rows within the hosted and app index codecs' parameter limit.
fn insert_rows<const N: usize>(
insert: &str,
rows: impl IntoIterator<Item = [SqlValue; N]>,
out: &mut Vec<Stmt>,
) {
let mut rows = rows.into_iter().peekable();
let tuple = format!("({})", ["?"; N].join(","));
let capacity = crate::index_codec::CodecLimits::HOSTED.max_parameters / N;
while rows.peek().is_some() {
let params: Vec<_> = rows.by_ref().take(capacity).flatten().collect();
let values = vec![tuple.as_str(); params.len() / N].join(",");
out.push(Stmt::new(format!("{insert} VALUES{values}"), params));
}
}

fn record_params(r: &RecordRow) -> StoreResult<[SqlValue; 4]> {
Ok([
b(&r.id),
t(&r.path_key),
int(u32::from(r.bucket)),
blob(record_c(r)?),
])
}

/// Replace a snapshot chunk's records and their lookup keys in staging. A
/// Stage::Put can replace a previously staged ID. For repeated puts within
/// the chunk, SQLite keeps the final record and only its keys should remain.
fn stage_records(records: &[RecordRow], out: &mut Vec<Stmt>) -> StoreResult<()> {
use crate::index_codec::CodecLimits;
let mut latest = std::collections::BTreeMap::new();
for chunk in records.chunks(CodecLimits::HOSTED.max_parameters / 4) {
let mut values = Vec::with_capacity(chunk.len());
for r in chunk {
values.push(record_params(r)?);
latest.insert(r.id, r);
}
insert_rows(
"INSERT OR REPLACE INTO sg_rec(id,path_key,bucket,row)",
values,
out,
);
}
let ids: Vec<_> = latest.keys().collect();
for chunk in ids.chunks(CodecLimits::HOSTED.max_parameters) {
let marks = vec!["?"; chunk.len()].join(",");
for table in ["sg_link", "sg_uniq"] {
out.push(st(
&format!("DELETE FROM {table} WHERE id IN ({marks})"),
chunk.iter().map(|id| b(id)).collect(),
));
}
}
insert_rows(
"INSERT OR IGNORE INTO sg_link(k,id)",
latest.values().flat_map(|r| {
r.meta
.links
.iter()
.collect::<BTreeSet<_>>()
.into_iter()
.map(|key| [t(key), b(&r.id)])
}),
out,
);
insert_rows(
"INSERT OR IGNORE INTO sg_uniq(f,v,id)",
latest.values().flat_map(|r| {
r.meta
.unique
.iter()
.map(|(field, value)| [t(field), t(value), b(&r.id)])
}),
out,
);
Ok(())
}

fn enc(c: Cbor) -> StoreResult<Vec<u8>> {
cbor::encode(&c).map_err(|_| corrupt("CBOR input"))
}
Expand Down Expand Up @@ -865,12 +943,7 @@ impl<I: IndexStorage> SqlStore<I> {
Self::del_record_stmts(&r.id, s, projections);
s.push(st(
"INSERT INTO st_rec(id, path_key, bucket, row) VALUES (?, ?, ?, ?)",
vec![
b(&r.id),
t(&r.path_key),
int(u32::from(r.bucket)),
blob(record_c(r)?),
],
record_params(r)?.into(),
));
link_stmts(&r.id, &r.meta.links, s);
for (f, v) in &r.meta.unique {
Expand Down Expand Up @@ -1663,10 +1736,12 @@ impl<I: IndexStorage> SqlStore<I> {
match tx.stage {
Stage::None => {}
Stage::Put => {
let rows = tx.take_confirmed_rows();
let mut rows = tx.take_confirmed_rows();
let records = std::mem::take(&mut rows.records_put);
let mut staged = Vec::new();
Self::confirmed_stmts(&rows, &mut staged, false)?;
s.extend(staged_stmts(staged)?);
stage_records(&records, &mut s)?;
}
Stage::Swap => {
// Confirmed state becomes the staging area, which ends empty.
Expand Down
2 changes: 1 addition & 1 deletion runtime/packages/sdk/scripts/runtime-methods.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"source": {
"commit": "173d092914ce109f11a8c53241e1959b35b8885d",
"commit": "80279ab7b08e946e1de7e20adfeb3bd5df574591",
"path": "runtime/crates/replica/src/frames.rs"
},
"methods": [
Expand Down
8 changes: 4 additions & 4 deletions runtime/packages/sdk/src/application/asset-pins.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{
"runtime": {
"sha256": "396a79e76e9ac841825b8d3cd1adf55b9f7d220dfa17a87a19d74b22dffcb912",
"bytes": 4095259,
"maxBytes": 4095259,
"sha256": "440557ae32a12e79ed753291b6e29be07e999779477477ec298a30bf9626ed12",
"bytes": 4105446,
"maxBytes": 4105446,
"source": {
"repository": "mdbase-dev/mdbase-connect",
"commit": "173d092914ce109f11a8c53241e1959b35b8885d"
"commit": "80279ab7b08e946e1de7e20adfeb3bd5df574591"
}
},
"sqlite": {
Expand Down
Loading