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-raw-projection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## Changed

- Snapshot installs promote the staged SQLite record table without copying note bodies a second time. Query-index rebuilds fetch raw sources in ordered batches.
80 changes: 40 additions & 40 deletions runtime/crates/core/src/doc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ pub struct Document {
block: Option<FrontmatterBlock>,
parsed: Option<Parsed>,
problem: Option<FrontmatterProblem>,
frontmatter: Map,
body: Range<usize>,
eol: LineEnding,
}
Expand Down Expand Up @@ -141,28 +140,15 @@ impl Document {
}
_ => first_line_ending(&source[start..]),
};
let (parsed, problem, frontmatter) = match &block {
None => (None, None, Map::new()),
Some(b) => match Parsed::new(&source[b.yaml.clone()]) {
Err(e) => (None, Some(FrontmatterProblem::Syntax(e)), Map::new()),
Ok(p) => match &p.value {
None => (Some(p), None, Map::new()),
Some(Value::Map(m)) => {
let m = m.clone();
(Some(p), None, m)
}
Some(_) => (Some(p), Some(FrontmatterProblem::NotMapping), Map::new()),
},
},
};
let (parsed, problem) =
parse_frontmatter(block.as_ref(), |b| Parsed::new(&source[b.yaml.clone()]));
Document {
source,
format,
bom,
block,
parsed,
problem,
frontmatter,
body,
eol,
}
Expand Down Expand Up @@ -209,7 +195,6 @@ impl Document {
block: parts.block,
parsed: parts.parsed,
problem: parts.problem,
frontmatter: parts.frontmatter,
body,
eol,
},
Expand Down Expand Up @@ -246,7 +231,12 @@ impl Document {

/// The persisted frontmatter mapping (`{}` when absent or invalid).
pub fn frontmatter(&self) -> &Map {
&self.frontmatter
static EMPTY: Map = Map::new();
self.parsed
.as_ref()
.and_then(|p| p.value.as_ref())
.and_then(Value::as_map)
.unwrap_or(&EMPTY)
}

/// Why the frontmatter block could not be read as a mapping, if it could not.
Expand Down Expand Up @@ -303,7 +293,7 @@ impl Document {
}

/// Preflight a borrowed source before caller cloning/planning/index hydration.
/// Includes the document's final frontmatter clone in the conservative estimate.
/// Includes a frontmatter copy in the conservative admission estimate.
pub fn check_frontmatter_at(
path: &str,
source: &str,
Expand All @@ -315,7 +305,6 @@ struct BoundedFrontmatter {
block: Option<FrontmatterBlock>,
parsed: Option<Parsed>,
problem: Option<FrontmatterProblem>,
frontmatter: Map,
footprint: crate::yaml::budget::Footprint,
}
fn bounded_frontmatter(
Expand All @@ -336,34 +325,45 @@ fn bounded_frontmatter(
RecordFormat::Markdown => find_frontmatter(source, start),
};
let mut budget = crate::yaml::budget::Budget::new();
let (parsed, problem, frontmatter) = match &block {
None => (None, None, Map::new()),
Some(b) => match Parsed::with_budget(&source[b.yaml.clone()], &mut budget) {
Err(YamlError {
kind: crate::yaml::ErrorKind::ResourceLimit(e),
..
}) => return Err(e),
Err(e) => (None, Some(FrontmatterProblem::Syntax(e)), Map::new()),
Ok(p) => match &p.value {
None => (Some(p), None, Map::new()),
Some(value @ Value::Map(m)) => {
budget.copy_value(value, 1, false)?;
let frontmatter = m.clone();
(Some(p), None, frontmatter)
}
Some(_) => (Some(p), Some(FrontmatterProblem::NotMapping), Map::new()),
},
},
};
let (parsed, problem) = parse_frontmatter(block.as_ref(), |b| {
Parsed::with_budget(&source[b.yaml.clone()], &mut budget)
});
if let Some(FrontmatterProblem::Syntax(YamlError {
kind: crate::yaml::ErrorKind::ResourceLimit(e),
..
})) = problem
{
return Err(e);
}
if let Some(value @ Value::Map(_)) = parsed.as_ref().and_then(|p| p.value.as_ref()) {
// Keep the established admission footprint for consumers that copy the mapping.
budget.copy_value(value, 1, false)?;
}
Ok(BoundedFrontmatter {
block,
parsed,
problem,
frontmatter,
footprint: budget.footprint,
})
}

fn parse_frontmatter(
block: Option<&FrontmatterBlock>,
parse: impl FnOnce(&FrontmatterBlock) -> Result<Parsed, YamlError>,
) -> (Option<Parsed>, Option<FrontmatterProblem>) {
let Some(block) = block else {
return (None, None);
};
match parse(block) {
Err(e) => (None, Some(FrontmatterProblem::Syntax(e))),
Ok(parsed) => {
let problem = matches!(parsed.value, Some(ref v) if v.as_map().is_none())
.then_some(FrontmatterProblem::NotMapping);
(Some(parsed), problem)
}
}
}

/// The line ending of the first line break in `s` (`\n` when there is none).
fn first_line_ending(s: &str) -> LineEnding {
match s.find('\n') {
Expand Down
7 changes: 5 additions & 2 deletions runtime/crates/core/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -429,8 +429,11 @@ pub struct Map {

impl Map {
/// An empty map.
pub fn new() -> Map {
Map::default()
pub const fn new() -> Map {
Map {
entries: Vec::new(),
index: BTreeMap::new(),
}
}

/// Number of entries.
Expand Down
10 changes: 10 additions & 0 deletions runtime/crates/core/src/views/bases/source_tags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,16 @@ pub fn capture_source_tags(
Unsure::Rest => body.len(),
});
}
// Ordinary text cannot open or close any of the spans below. Stop at
// line boundaries so block classification and code-work charges stay exact.
let plain = tail
.bytes()
.take_while(|b| !matches!(b, b'\n' | b'`' | b'[' | b']' | b'<' | b'$' | b'#'))
.count();
if plain != 0 {
cursor += plain;
continue;
}
let settled = cursor >= unsure_until;
if tail.starts_with('`') {
if settled
Expand Down
41 changes: 40 additions & 1 deletion runtime/crates/platform-native/tests/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1102,6 +1102,13 @@ fn staged_record_batches_replace_old_lookup_keys() {
r.meta.unique = vec![("slug".into(), key.into())];
r
};
let old = row(200, "old");
store
.commit(Tx {
records_put: vec![old.clone()],
..Tx::default()
})
.unwrap();
let mut put = |rows| {
store
.commit(Tx {
Expand All @@ -1115,7 +1122,39 @@ fn staged_record_batches_replace_old_lookup_keys() {
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);
let ddl = |sql| {
store
.index()
.borrow_mut()
.run(&Batch {
mode: BatchMode::Transaction,
stmts: vec![Stmt::new(sql, vec![])],
})
.unwrap()
};
// Refuse a later table in the same swap, after the staged record table
// and its indexes have been renamed/recreated.
ddl(
"CREATE TRIGGER refuse_links BEFORE INSERT ON st_link BEGIN SELECT RAISE(ABORT,'swap fault'); END",
);
assert!(
store
.commit(Tx {
stage: Stage::Swap,
..Tx::default()
})
.is_err()
);
assert_eq!(store.record_count().unwrap(), 1);
assert_eq!(store.record(&old.id).unwrap(), Some(old));
store
.index()
.borrow_mut()
.run(&Batch {
mode: BatchMode::Transaction,
stmts: vec![Stmt::new("DROP TRIGGER refuse_links", vec![])],
})
.unwrap();
store
.commit(Tx {
stage: Stage::Swap,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ fn index_only_backfill_reads_small_and_large_sources_in_order() {
.unwrap();
let projected = rows
.iter()
.rev()
.map(|r| {
let mut entry = project_record_query_index_row(&catalog(), r, &refs, 8192).unwrap();
entry.body = None;
Expand Down
39 changes: 19 additions & 20 deletions runtime/crates/store-file/src/index_codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,26 +279,25 @@ impl<'a> Reader<'a> {

/// Encode a complete bounded request, preserving each SQLite value type.
pub fn encode_request(request: &IndexRequest, limits: CodecLimits) -> Result<Vec<u8>> {
let mut w = Writer::new(
limits,
if matches!(request, IndexRequest::Reset) {
1
} else {
0
},
)?;
if let IndexRequest::Run(batch) = request {
w.byte(match batch.mode {
BatchMode::Transaction => 0,
BatchMode::Autocommit => 1,
})?;
w.count(batch.stmts.len(), limits.max_statements, "statements")?;
for st in &batch.stmts {
w.data(st.sql.as_bytes(), limits.max_sql_bytes, "SQL bytes")?;
w.count(st.params.len(), limits.max_parameters, "parameters")?;
for v in &st.params {
w.value(v)?;
}
match request {
IndexRequest::Reset => Ok(Writer::new(limits, 1)?.bytes),
IndexRequest::Run(batch) => encode_batch(batch.mode, &batch.stmts, limits),
}
}

/// Encode borrowed statements in their host transaction mode.
pub fn encode_batch(mode: BatchMode, stmts: &[Stmt], limits: CodecLimits) -> Result<Vec<u8>> {
let mut w = Writer::new(limits, 0)?;
w.byte(match mode {
BatchMode::Transaction => 0,
BatchMode::Autocommit => 1,
})?;
w.count(stmts.len(), limits.max_statements, "statements")?;
for st in stmts {
w.data(st.sql.as_bytes(), limits.max_sql_bytes, "SQL bytes")?;
w.count(st.params.len(), limits.max_parameters, "parameters")?;
for v in &st.params {
w.value(v)?;
}
}
Ok(w.bytes)
Expand Down
34 changes: 31 additions & 3 deletions runtime/crates/store-file/src/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,16 @@ use crate::index::{
Batch, BatchMode, IndexError, IndexErrorKind, IndexStorage, SqlValue, Stmt, StmtResult,
};

const RECORD_TABLE: &str = "CREATE TABLE IF NOT EXISTS st_rec(id BLOB PRIMARY KEY, path_key TEXT NOT NULL, bucket INTEGER NOT NULL, row BLOB NOT NULL) WITHOUT ROWID";
const RECORD_PATH_INDEX: &str = "CREATE INDEX IF NOT EXISTS st_rec_pk ON st_rec(path_key)";
const RECORD_BUCKET_INDEX: &str = "CREATE INDEX IF NOT EXISTS st_rec_b ON st_rec(bucket, id)";

const SCHEMA: &[&str] = &[
"CREATE TABLE IF NOT EXISTS st_kv(k TEXT PRIMARY KEY, v BLOB NOT NULL) WITHOUT ROWID",
"CREATE TABLE IF NOT EXISTS st_meta(k TEXT PRIMARY KEY, v BLOB NOT NULL) WITHOUT ROWID",
"CREATE TABLE IF NOT EXISTS st_rec(id BLOB PRIMARY KEY, path_key TEXT NOT NULL, bucket INTEGER NOT NULL, row BLOB NOT NULL) WITHOUT ROWID",
"CREATE INDEX IF NOT EXISTS st_rec_pk ON st_rec(path_key)",
"CREATE INDEX IF NOT EXISTS st_rec_b ON st_rec(bucket, id)",
RECORD_TABLE,
RECORD_PATH_INDEX,
RECORD_BUCKET_INDEX,
"CREATE TABLE IF NOT EXISTS st_link(k TEXT NOT NULL, id BLOB NOT NULL, PRIMARY KEY(k, id)) WITHOUT ROWID",
"CREATE INDEX IF NOT EXISTS st_link_id ON st_link(id)",
"CREATE TABLE IF NOT EXISTS st_uniq(f TEXT NOT NULL, v TEXT NOT NULL, id BLOB NOT NULL, PRIMARY KEY(f, v, id)) WITHOUT ROWID",
Expand Down Expand Up @@ -340,6 +344,26 @@ fn stage_records(records: &[RecordRow], out: &mut Vec<Stmt>) -> StoreResult<()>
Ok(())
}

/// Promote the staged document B-tree in the swap transaction. Copying its
/// overflow pages into a second table dominates the browser's OPFS writes.
/// SQLite keeps index names on rename, so rebuild both pairs under their
/// canonical names before publishing the head.
fn promote_staged_records(out: &mut Vec<Stmt>) {
for sql in [
"DROP TABLE st_rec",
"DROP INDEX sg_rec_pk",
"DROP INDEX sg_rec_b",
"ALTER TABLE sg_rec RENAME TO st_rec",
RECORD_PATH_INDEX,
RECORD_BUCKET_INDEX,
] {
out.push(st(sql, vec![]));
}
for sql in [RECORD_TABLE, RECORD_PATH_INDEX, RECORD_BUCKET_INDEX] {
out.push(st(&sql.replace("st_", "sg_"), vec![]));
}
}

fn enc(c: Cbor) -> StoreResult<Vec<u8>> {
cbor::encode(&c).map_err(|_| corrupt("CBOR input"))
}
Expand Down Expand Up @@ -1746,6 +1770,10 @@ impl<I: IndexStorage> SqlStore<I> {
Stage::Swap => {
// Confirmed state becomes the staging area, which ends empty.
for t in CONFIRMED {
if *t == "rec" {
promote_staged_records(&mut s);
continue;
}
s.push(st(&format!("DELETE FROM st_{t}"), vec![]));
s.push(st(
&format!("INSERT INTO st_{t} SELECT * FROM sg_{t}"),
Expand Down
Loading
Loading