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/cold-open-index-records.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## Changed

- Speed up collection snapshot installation and index rebuilding by reusing parsed record metadata and batching SQLite inserts for paths, modification times, and type memberships.
86 changes: 66 additions & 20 deletions runtime/crates/bench/tests/catalog_reindex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,8 @@ fn kind(sql: &str) -> String {
format!("{verb}:{table}")
}

impl IndexStorage for Profiled {
fn info(&self) -> IndexInfo {
self.inner.info()
}
fn run(&mut self, batch: &Batch) -> Result<Vec<StmtResult>, IndexError> {
impl Profiled {
fn timed_run(&mut self, batch: &Batch) -> Result<Vec<StmtResult>, IndexError> {
if !self.split
|| !self.window
|| batch.mode != BatchMode::Transaction
Expand Down Expand Up @@ -102,6 +99,25 @@ impl IndexStorage for Profiled {
}
Ok(out)
}
}

impl IndexStorage for Profiled {
fn info(&self) -> IndexInfo {
self.inner.info()
}
fn run(&mut self, batch: &Batch) -> Result<Vec<StmtResult>, IndexError> {
let out = self.timed_run(batch)?;
for (stmt, result) in batch.stmts.iter().zip(&out) {
if stmt.sql.starts_with("INSERT INTO st_qrecord(") {
self.stats
.borrow_mut()
.entry("records projected".into())
.or_default()
.0 += u32::try_from(result.changes).unwrap();
}
}
Ok(out)
}
fn run_with_borrowed_blob(
&mut self,
batch: &Batch,
Expand Down Expand Up @@ -404,9 +420,12 @@ fn report(label: &str, elapsed: Duration, stats: &Stats) {
sql.as_secs_f64() * 1e3,
elapsed.saturating_sub(sql).as_secs_f64() * 1e3
);
let statements: u32 = stats.values().map(|(n, _)| *n).sum();
let mut rows: Vec<_> = stats
.iter()
.filter(|(key, _)| key.as_str() != "records projected")
.collect();
let statements: u32 = rows.iter().map(|(_, (n, _))| n).sum();
eprintln!(" {statements} statements");
let mut rows: Vec<_> = stats.iter().collect();
rows.sort_by_key(|(_, (_, d))| std::cmp::Reverse(*d));
for (k, (n, d)) in rows.into_iter().take(14) {
eprintln!(" {k:<26} {n:>7} stmts {:>9.1} ms", d.as_secs_f64() * 1e3);
Expand Down Expand Up @@ -554,7 +573,7 @@ fn device_cold_open_after_a_snapshot_at_10k() {
eprintln!(
" st_qstate inserts {}, records projected {}, fts delete-all {}",
count("insert:st_qstate"),
count("insert:st_qrecord"),
count("records projected"),
count("fts-delete-all:st_qbody")
);
if let Some((n, d)) = stats.get("fts-delete-all:st_qbody") {
Expand Down Expand Up @@ -597,6 +616,17 @@ fn device_cold_open_after_a_snapshot_at_10k() {
#[test]
#[ignore = "manual release timing (#1648)"]
fn seven_cold_opens_at_10k() {
seven_cold_opens(10_000, "cold-open")
}

/// Small control with the same note shape, snapshot and catalog-changing tail.
#[test]
#[ignore = "manual release timing (#1648)"]
fn seven_cold_opens_at_100() {
seven_cold_opens(100, "cold-open-small")
}

fn seven_cold_opens(tasks: u32, fixture: &str) {
let svc = FakeLogService::new();
let device_id = B16([101; 16]);
let state = mdbn_wire::policy::CState::E2e;
Expand All @@ -612,21 +642,31 @@ fn seven_cold_opens_at_10k() {
)),
)
};
let (writer_store, _) = store("seven_cold_writer", false);
let (writer_store, _) = store(&format!("{fixture}_writer"), false);
let mut writer = open_device(writer_store);
writer.sync(&svc);
seed_docs(&mut writer, &svc, 10_000, |n| {
seed_docs(&mut writer, &svc, tasks, |n| {
use std::fmt::Write;
let mut doc = task(n);
for line in 0..24 {
writeln!(doc, "Task {n} observation {line}: review the scheduled project work and record its outcome.").unwrap();
}
doc
});
let snapshot = compact_then_tail(&svc, &mut writer, 10_000, 10, "tasks/t01*.md");
write_browser_fixture(&svc, snapshot);
let snapshot = compact_then_tail(
&svc,
&mut writer,
tasks,
10,
if tasks < 1000 {
"tasks/t000*.md"
} else {
"tasks/t01*.md"
},
);
write_browser_fixture(&svc, snapshot, fixture);
for run in 1..=7 {
let (device_store, stats) = store("seven_cold_device", false);
let (device_store, stats) = store(&format!("{fixture}_device"), false);
let mut device = open_device(device_store);
stats.borrow_mut().clear();
let started = Instant::now();
Expand All @@ -640,7 +680,10 @@ fn seven_cold_opens_at_10k() {
report(&format!("run {run} replay"), started.elapsed(), &stats);
assert_eq!(device.r.stats.snapshots_installed, 1);
assert_index_ready(&device);
assert_eq!(device.r.store().record_count().unwrap(), 10_080);
assert_eq!(
device.r.store().record_count().unwrap(),
u64::from(tasks) + 80
);
assert_eq!(
type_page(&mut device, "batch", 50, None)
.unwrap()
Expand All @@ -653,7 +696,7 @@ fn seven_cold_opens_at_10k() {

/// Export only the synthetic service's public replies and sealed objects. The
/// browser opens with the same enrolled fixture device in a fresh database.
fn write_browser_fixture(svc: &FakeLogService, snapshot: u64) {
fn write_browser_fixture(svc: &FakeLogService, snapshot: u64, fixture_name: &str) {
use mdbn_replica::log::LogResponse;
use mdbn_wire::{
cbor::Cbor,
Expand Down Expand Up @@ -693,7 +736,8 @@ fn write_browser_fixture(svc: &FakeLogService, snapshot: u64) {
read(&mut client, snapshot, None),
Cbor::Array(objects),
]);
let path = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join("cold-open.cbor");
let path =
std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("{fixture_name}.cbor"));
std::fs::write(path, mdbn_wire::cbor::encode(&fixture).unwrap()).unwrap();
}

Expand Down Expand Up @@ -786,13 +830,15 @@ fn a_cold_open_builds_the_index_once_after_the_tail() {
let records = device.r.store().record_count().unwrap();
let projected = stats
.borrow()
.get("insert:st_qrecord")
.get("records projected")
.map_or(0, |(n, _)| *n);
assert_eq!(
u64::from(projected),
records,
"every record is projected once"
);
let inserts = stats.borrow()["insert:st_qrecord"].0;
assert!(inserts < projected, "projection inserts are batched");
assert_caught_up(&svc, &mut device);
}

Expand Down Expand Up @@ -950,7 +996,7 @@ fn device_behind_one_catalog_change_at_10k() {
);
let projected = stats
.borrow()
.get("insert:st_qrecord")
.get("records projected")
.map_or(0, |(n, _)| *n);
eprintln!(" records projected {projected}");
assert_index_ready(&device);
Expand Down Expand Up @@ -1113,7 +1159,7 @@ fn ordinary_entries_are_projected_as_they_apply() {
device.sync(&svc);
let projected = stats
.borrow()
.get("insert:st_qrecord")
.get("records projected")
.map_or(0, |(n, _)| *n);
assert_eq!(projected, 2, "one projection per created record");
assert_index_ready(&device);
Expand Down Expand Up @@ -1154,7 +1200,7 @@ fn a_device_not_deferred_applies_a_catalog_change_in_one_combined_pass() {
// The combined pass projects the 450 records it rederives; the 3 creates
// are projected in their own commits.
assert_eq!(
ran(&stats, "insert:st_qrecord"),
ran(&stats, "records projected"),
TASKS + 50 + 3,
"{stats:?}"
);
Expand Down
65 changes: 47 additions & 18 deletions runtime/crates/core/src/links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,8 +397,12 @@ pub fn record_links(catalog: &Catalog, path: &str, source: &str) -> Vec<Link> {
let doc = Document::parse_at(path, source);
let types = catalog.membership(path, doc.frontmatter()).types;
let values = catalog.record_values(path, &types, doc.frontmatter());
let mut out = frontmatter_links(catalog, &types, &values);
out.extend(parse_body(doc.body()));
parsed_links(catalog, &types, &values, doc.body())
}

fn parsed_links(catalog: &Catalog, types: &[String], values: &Map, body: &str) -> Vec<Link> {
let mut out = frontmatter_links(catalog, types, values);
out.extend(parse_body(body));
out
}

Expand Down Expand Up @@ -597,8 +601,27 @@ fn id_key(id: &str) -> LinkKey {
/// Index keys of the outgoing links of a record (for the link index): the
/// path key of each target's final segment without a record extension.
pub fn index_keys(catalog: &Catalog, path: &str, source: &str) -> Vec<LinkKey> {
outgoing_keys(catalog, path, record_links(catalog, path, source))
}

/// Both sides of the link index for a record whose membership and path-derived
/// values have already been computed under this catalog.
pub fn record_index_keys(
catalog: &Catalog,
path: &str,
types: &[String],
values: &Map,
body: &str,
) -> (Vec<LinkKey>, Vec<LinkKey>) {
(
outgoing_keys(catalog, path, parsed_links(catalog, types, values, body)),
target_keys_with_values(catalog, path, Some(values)),
)
}

fn outgoing_keys(catalog: &Catalog, path: &str, links: Vec<Link>) -> Vec<LinkKey> {
let mut keys: BTreeSet<LinkKey> = BTreeSet::new();
for l in record_links(catalog, path, source) {
for l in links {
// Keep the raw key for compatibility with previously materialized
// indexes, but also index the resolver's normalized path basename.
keys.insert(name_index_key(catalog, &l.target));
Expand All @@ -622,21 +645,27 @@ pub fn name_index_key(catalog: &Catalog, target: &str) -> LinkKey {
/// Keys under which a record or file at `path` is found: its name key, and,
/// when an ID field is configured, its ID key.
pub fn target_keys(catalog: &Catalog, path: &str, source: Option<&str>) -> Vec<LinkKey> {
let mut keys = vec![name_key(&path_key(strip_record_ext(
catalog,
basename(path),
)))];
if let (Some(field), Some(src)) = (&catalog.settings().id_field, source) {
let doc = Document::parse_at(path, src);
let types = catalog.membership(path, doc.frontmatter()).types;
let values = catalog.record_values(path, &types, doc.frontmatter());
if let Some(id) = values
.get(field)
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
{
keys.push(id_key(id));
}
let values = source
.filter(|_| catalog.settings().id_field.is_some())
.map(|src| {
let doc = Document::parse_at(path, src);
let types = catalog.membership(path, doc.frontmatter()).types;
catalog.record_values(path, &types, doc.frontmatter())
});
target_keys_with_values(catalog, path, values.as_ref())
}

fn target_keys_with_values(catalog: &Catalog, path: &str, values: Option<&Map>) -> Vec<LinkKey> {
let mut keys = vec![name_index_key(catalog, path)];
if let Some(id) = catalog
.settings()
.id_field
.as_ref()
.and_then(|field| values?.get(field))
.and_then(Value::as_str)
.filter(|id| !id.is_empty())
{
keys.push(id_key(id));
}
keys.sort();
keys
Expand Down
8 changes: 5 additions & 3 deletions runtime/crates/replica/src/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,12 +186,14 @@ pub fn record_meta(catalog: &Catalog, path: &str, doc: &str) -> RecordMeta {
let membership = catalog.membership(path, fm);
let values = catalog.record_values(path, &membership.types, fm);
let fm = &values;
let mut links: Vec<String> = mdbn_core::links::index_keys(catalog, path, doc)
let (outgoing, targets) =
mdbn_core::links::record_index_keys(catalog, path, &membership.types, fm, parsed.body());
let mut links: Vec<String> = outgoing
.into_iter()
.map(|k| format!("{LINK_PREFIX}{}", k.0))
.collect();
links.extend(
mdbn_core::links::target_keys(catalog, path, Some(doc))
targets
.into_iter()
.map(|k| format!("{TARGET_PREFIX}{}", k.0)),
);
Expand All @@ -210,7 +212,7 @@ pub fn record_meta(catalog: &Catalog, path: &str, doc: &str) -> RecordMeta {
unique.sort();
unique.dedup();
RecordMeta {
types: membership.types.clone(),
types: membership.types,
effective: convert::wmap(fm),
links,
tags: Vec::new(),
Expand Down
47 changes: 28 additions & 19 deletions runtime/crates/store-file/src/sql_fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,29 +416,38 @@ pub(crate) fn maintenance<I: IndexStorage>(
if update.replace_specs.is_none() {
delete_fields(&row_ids, &mut out);
}
for r in &update.rows {
out.push(Stmt::new(
"INSERT INTO st_qrecord(id,path) VALUES(?,?)",
vec![blob(&r.id.0), blob(r.path.as_bytes())],
));
out.push(Stmt::new(
"INSERT INTO st_qmtime(id,kind,sort,path) VALUES(?,?,?,?)",
vec![
insert_rows(
"INSERT INTO st_qrecord(id,path)",
update
.rows
.iter()
.map(|r| [blob(&r.id.0), blob(r.path.as_bytes())]),
&mut out,
);
insert_rows(
"INSERT INTO st_qmtime(id,kind,sort,path)",
update.rows.iter().map(|r| {
[
blob(&r.id.0),
SqlValue::Integer(i64::from(r.mtime.kind)),
blob(&r.mtime.key),
blob(r.path.as_bytes()),
],
));
// Core's closed profile resolves query spelling to these exact canonical
// catalogue membership names; the backend invents no folding semantics.
for name in r.types.iter().cloned().collect::<BTreeSet<_>>() {
out.push(Stmt::new(
"INSERT INTO st_qtype(name,id) VALUES(?,?)",
vec![SqlValue::Text(name), blob(&r.id.0)],
));
}
}
]
}),
&mut out,
);
// Membership names retain Core's exact spelling and are unique per record.
insert_rows(
"INSERT INTO st_qtype(name,id)",
update.rows.iter().flat_map(|r| {
r.types
.iter()
.collect::<BTreeSet<_>>()
.into_iter()
.map(move |name| [SqlValue::Text(name.clone()), blob(&r.id.0)])
}),
&mut out,
);
insert_rows(
"INSERT INTO st_field(id,source,field,kind,sort,hint,path)",
update.rows.iter().flat_map(|r| {
Expand Down
Loading
Loading