feat(storage): one rebuildable SQLite projection with derived indexes
- add schema revision 1 with application id, singleton build row, documents, nodes, aliases, edges, contexts, inputs, diagnostics, search_units, FTS5 search_fts, grams and embeddings tables; spans and resolved-target invariants are enforced by CHECK constraints and foreign_keys=ON - full rebuild stages a private database in the target directory and renames it atomically after source recheck and quick_check; a foreign or symlinked database is refused, never overwritten - incremental publish replaces the projection inside one transaction, so readers see the old or the new complete snapshot and failures roll back to the last successful artifact - store exact UTF-8 source bytes and digest-guarded normalised facts for the incremental re-analysis cache; inputs are content digests, never mtimes - build one search unit per structural node/chunk with CJK bigram FTS segmentation, weighted FTS fields and bounded 2/3-gram fuzzy rows - add read-only store API (nodes, aliases, edges, units, FTS/gram candidates, exact-name lookup, embeddings, diagnostics, integrity, currentness) and integration tests for publish/read/search/incremental/foreign-db safety
This commit is contained in:
1 parent
1871ded5ed
commit
cca8fbdab1
7 files changed
+2990
No files matched your search
@@ -0,0 +1,424 @@
|
||||
//! Derived search-index construction.
|
||||
//!
|
||||
//! Search units are generated only from source structure: heading scopes,
|
||||
//! extracted blocks, function interface metadata and front-matter metadata.
|
||||
//! Texts are segmented with [`crate::text`] before entering FTS5 so two-character
|
||||
//! Chinese queries do not depend on a trigram tokenizer. Gram rows support the
|
||||
//! bounded fuzzy channel. Nothing here generates facts or rewrites source.
|
||||
|
||||
use crate::document::{BlockFact, DocumentFacts, UnitKind};
|
||||
use crate::graph::identity;
|
||||
use crate::graph::{Graph, Node};
|
||||
use crate::model::Span;
|
||||
use crate::text;
|
||||
use rusqlite::Transaction;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Maximum source bytes in one search unit chunk.
|
||||
const MAX_CHUNK_BYTES: usize = 4096;
|
||||
/// Per-field gram caps keep the fuzzy index bounded for large documents.
|
||||
const MAX_GRAMS_PER_FIELD: usize = 2048;
|
||||
const MAX_BODY_GRAMS: usize = 2048;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct IndexStats {
|
||||
pub search_units: u64,
|
||||
pub grams: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct UnitSpec {
|
||||
node_key: String,
|
||||
span: Span,
|
||||
fields: SearchFields,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct SearchFields {
|
||||
title: String,
|
||||
body: String,
|
||||
symbols: String,
|
||||
metadata: String,
|
||||
formula: String,
|
||||
tabular: String,
|
||||
links: String,
|
||||
}
|
||||
|
||||
impl SearchFields {
|
||||
fn append_block(&mut self, block: &BlockFact) {
|
||||
push_field(&mut self.body, &block.text);
|
||||
push_field(&mut self.formula, &block.formula);
|
||||
push_field(&mut self.tabular, &block.table);
|
||||
push_field(&mut self.links, &block.links);
|
||||
}
|
||||
|
||||
fn byte_len(&self) -> usize {
|
||||
self.body.len() + self.formula.len() + self.tabular.len() + self.links.len()
|
||||
}
|
||||
}
|
||||
|
||||
fn push_field(field: &mut String, value: &str) {
|
||||
if value.is_empty() {
|
||||
return;
|
||||
}
|
||||
if !field.is_empty() {
|
||||
field.push('\n');
|
||||
}
|
||||
field.push_str(value);
|
||||
}
|
||||
|
||||
/// Build search units and gram rows for the whole graph inside the publish
|
||||
/// transaction.
|
||||
pub fn build_index(
|
||||
tx: &Transaction<'_>,
|
||||
graph: &Graph,
|
||||
doc_ids: &HashMap<&str, i64>,
|
||||
node_ids: &HashMap<&str, i64>,
|
||||
) -> Result<IndexStats, rusqlite::Error> {
|
||||
let mut stats = IndexStats::default();
|
||||
let mut seen: HashSet<(String, u64)> = HashSet::new();
|
||||
for facts in &graph.facts {
|
||||
let Some(doc_id) = doc_ids.get(facts.rel_path.as_str()).copied() else {
|
||||
continue;
|
||||
};
|
||||
let specs = unit_specs(facts, graph);
|
||||
for spec in specs {
|
||||
let Some(node_id) = node_ids.get(spec.node_key.as_str()).copied() else {
|
||||
continue;
|
||||
};
|
||||
// One search unit per (node, span chunk): never duplicate text.
|
||||
if !seen.insert((spec.node_key.clone(), spec.span.start)) {
|
||||
continue;
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO search_units
|
||||
(node_id, doc_id, span_start, span_end,
|
||||
title, body, symbols, metadata, formula, tabular, links)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
|
||||
rusqlite::params![
|
||||
node_id,
|
||||
doc_id,
|
||||
spec.span.start as i64,
|
||||
spec.span.end as i64,
|
||||
text::segment(&spec.fields.title),
|
||||
text::segment(&spec.fields.body),
|
||||
text::segment(&spec.fields.symbols),
|
||||
text::segment(&spec.fields.metadata),
|
||||
text::segment(&spec.fields.formula),
|
||||
text::segment(&spec.fields.tabular),
|
||||
text::segment(&spec.fields.links),
|
||||
],
|
||||
)?;
|
||||
let unit_id = tx.last_insert_rowid();
|
||||
tx.execute(
|
||||
"INSERT INTO search_fts(rowid, title, body, symbols, metadata, formula, tabular, links)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
|
||||
rusqlite::params![
|
||||
unit_id,
|
||||
text::segment(&spec.fields.title),
|
||||
text::segment(&spec.fields.body),
|
||||
text::segment(&spec.fields.symbols),
|
||||
text::segment(&spec.fields.metadata),
|
||||
text::segment(&spec.fields.formula),
|
||||
text::segment(&spec.fields.tabular),
|
||||
text::segment(&spec.fields.links),
|
||||
],
|
||||
)?;
|
||||
stats.search_units += 1;
|
||||
stats.grams += insert_grams(tx, unit_id, &spec.fields)?;
|
||||
}
|
||||
}
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
fn insert_grams(
|
||||
tx: &Transaction<'_>,
|
||||
unit_id: i64,
|
||||
fields: &SearchFields,
|
||||
) -> Result<u64, rusqlite::Error> {
|
||||
let mut count = 0u64;
|
||||
let mut seen: HashSet<(String, &'static str)> = HashSet::new();
|
||||
for (field_name, text_value) in [
|
||||
("title", fields.title.as_str()),
|
||||
("symbols", fields.symbols.as_str()),
|
||||
("metadata", fields.metadata.as_str()),
|
||||
] {
|
||||
let mut grams = text::grams(text_value);
|
||||
grams.truncate(MAX_GRAMS_PER_FIELD);
|
||||
for gram in grams {
|
||||
if !seen.insert((gram.clone(), field_name)) {
|
||||
continue;
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT OR IGNORE INTO grams (norm_gram, search_unit_id, field) VALUES (?1, ?2, ?3)",
|
||||
rusqlite::params![gram, unit_id, field_name],
|
||||
)?;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
let mut body_grams: Vec<String> = text::grams(&fields.body)
|
||||
.into_iter()
|
||||
.filter(|gram| {
|
||||
let chars: Vec<char> = gram.chars().collect();
|
||||
chars.len() == 2 && chars.iter().all(|ch| text::is_cjk(*ch))
|
||||
})
|
||||
.collect();
|
||||
body_grams.truncate(MAX_BODY_GRAMS);
|
||||
for gram in body_grams {
|
||||
if !seen.insert((gram.clone(), "body")) {
|
||||
continue;
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT OR IGNORE INTO grams (norm_gram, search_unit_id, field) VALUES (?1, ?2, ?3)",
|
||||
rusqlite::params![gram, unit_id, "body"],
|
||||
)?;
|
||||
count += 1;
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// Generate deterministic search-unit specs for one document, chunked on block
|
||||
/// boundaries with a hard byte budget.
|
||||
fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec<UnitSpec> {
|
||||
let mut specs = Vec::new();
|
||||
let node_by_key: HashMap<&str, &Node> = graph
|
||||
.nodes
|
||||
.iter()
|
||||
.map(|node| (node.key.as_str(), node))
|
||||
.collect();
|
||||
let mut blocks_by_unit: HashMap<usize, Vec<&BlockFact>> = HashMap::new();
|
||||
for block in &facts.blocks {
|
||||
blocks_by_unit.entry(block.unit).or_default().push(block);
|
||||
}
|
||||
for (unit_index, unit) in facts.units.iter().enumerate() {
|
||||
let node_key = if unit_index == 0 {
|
||||
identity::document_key(&facts.rel_path)
|
||||
} else {
|
||||
identity::unit_key(&facts.rel_path, unit.occurrence, &unit.path)
|
||||
};
|
||||
let node_key = node_key.as_str().to_string();
|
||||
let Some(node) = node_by_key.get(node_key.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
if !node.is_searchable() {
|
||||
continue;
|
||||
}
|
||||
let base = SearchFields {
|
||||
title: node.title.clone(),
|
||||
symbols: symbols_for(facts, unit_index),
|
||||
metadata: metadata_for(facts, unit_index, node),
|
||||
..SearchFields::default()
|
||||
};
|
||||
let blocks = blocks_by_unit.get(&unit_index).cloned().unwrap_or_default();
|
||||
if blocks.is_empty() {
|
||||
let span = if unit_index == 0 {
|
||||
Span::new(0, source_len(facts))
|
||||
} else {
|
||||
unit.span
|
||||
};
|
||||
specs.push(UnitSpec {
|
||||
node_key,
|
||||
span,
|
||||
fields: base,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
// Chunk on block boundaries. Title/symbols/metadata are emitted only in
|
||||
// the first chunk so a long document cannot multiply title matches.
|
||||
let mut current_fields = SearchFields::default();
|
||||
let mut chunk_start = blocks[0].span.start;
|
||||
let mut chunk_end = blocks[0].span.end;
|
||||
let mut first = true;
|
||||
let flush = |fields: SearchFields,
|
||||
start: u64,
|
||||
end: u64,
|
||||
first: bool,
|
||||
specs: &mut Vec<UnitSpec>,
|
||||
base: &SearchFields,
|
||||
node_key: &str| {
|
||||
if fields.byte_len() == 0 && !first {
|
||||
return;
|
||||
}
|
||||
let mut merged = fields;
|
||||
if first {
|
||||
merged.title = base.title.clone();
|
||||
merged.symbols = base.symbols.clone();
|
||||
merged.metadata = base.metadata.clone();
|
||||
}
|
||||
specs.push(UnitSpec {
|
||||
node_key: node_key.to_string(),
|
||||
span: Span::new(start, end),
|
||||
fields: merged,
|
||||
});
|
||||
};
|
||||
for block in blocks {
|
||||
let block_len =
|
||||
block.text.len() + block.formula.len() + block.table.len() + block.links.len();
|
||||
if !first && current_fields.byte_len() + block_len > MAX_CHUNK_BYTES {
|
||||
flush(
|
||||
std::mem::take(&mut current_fields),
|
||||
chunk_start,
|
||||
chunk_end,
|
||||
first,
|
||||
&mut specs,
|
||||
&base,
|
||||
&node_key,
|
||||
);
|
||||
first = false;
|
||||
chunk_start = block.span.start;
|
||||
}
|
||||
current_fields.append_block(block);
|
||||
chunk_end = block.span.end;
|
||||
}
|
||||
flush(
|
||||
current_fields,
|
||||
chunk_start,
|
||||
chunk_end,
|
||||
first,
|
||||
&mut specs,
|
||||
&base,
|
||||
&node_key,
|
||||
);
|
||||
}
|
||||
let _ = node_by_key;
|
||||
specs
|
||||
}
|
||||
|
||||
fn source_len(facts: &DocumentFacts) -> u64 {
|
||||
facts
|
||||
.units
|
||||
.first()
|
||||
.map(|unit| unit.span.end)
|
||||
.unwrap_or_else(|| facts.ast.span.end)
|
||||
}
|
||||
|
||||
fn symbols_for(facts: &DocumentFacts, unit_index: usize) -> String {
|
||||
let mut symbols = String::new();
|
||||
if facts.units[unit_index].kind == UnitKind::Function {
|
||||
if let Some(function) = facts
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.unit == unit_index)
|
||||
{
|
||||
push_field(&mut symbols, &function.local_name);
|
||||
push_field(&mut symbols, &function.function_id);
|
||||
if let Some(namespace) = &function.namespace {
|
||||
push_field(&mut symbols, namespace);
|
||||
}
|
||||
if let Some(params) = function
|
||||
.signature
|
||||
.get("params")
|
||||
.and_then(|params| params.as_array())
|
||||
{
|
||||
for param in params {
|
||||
if let Some(name) = param.get("name").and_then(|name| name.as_str()) {
|
||||
push_field(&mut symbols, name);
|
||||
}
|
||||
if let Some(type_name) =
|
||||
param.get("type").and_then(|type_name| type_name.as_str())
|
||||
{
|
||||
push_field(&mut symbols, type_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
push_field(&mut symbols, &facts.units[unit_index].path.join(" "));
|
||||
if let Some(unit_id) = &facts.units[unit_index].unit_id {
|
||||
push_field(&mut symbols, unit_id);
|
||||
}
|
||||
symbols
|
||||
}
|
||||
|
||||
fn metadata_for(facts: &DocumentFacts, unit_index: usize, node: &Node) -> String {
|
||||
let mut metadata = String::new();
|
||||
if unit_index == 0 {
|
||||
if let Some(front_matter) = &facts.front_matter {
|
||||
if let Some(value) = &front_matter.value {
|
||||
let mut flat = String::new();
|
||||
flatten_json(value, &mut flat, 0);
|
||||
push_field(&mut metadata, &flat);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(analysis) = &facts.analysis {
|
||||
push_field(&mut metadata, &analysis.module_id);
|
||||
push_field(&mut metadata, &analysis.entry_module_id);
|
||||
push_field(&mut metadata, &analysis.root_id);
|
||||
}
|
||||
if let Some(signature) = node.metadata.get("signature") {
|
||||
if let Ok(serialized) = serde_json::to_string(signature) {
|
||||
push_field(&mut metadata, &serialized);
|
||||
}
|
||||
}
|
||||
metadata
|
||||
}
|
||||
|
||||
fn flatten_json(value: &serde_json::Value, out: &mut String, depth: usize) {
|
||||
if depth > 8 {
|
||||
return;
|
||||
}
|
||||
match value {
|
||||
serde_json::Value::Object(object) => {
|
||||
for (key, value) in object {
|
||||
push_field(out, key);
|
||||
flatten_json(value, out, depth + 1);
|
||||
}
|
||||
}
|
||||
serde_json::Value::Array(items) => {
|
||||
for item in items {
|
||||
flatten_json(item, out, depth + 1);
|
||||
}
|
||||
}
|
||||
serde_json::Value::String(text) => push_field(out, text),
|
||||
serde_json::Value::Number(number) => push_field(out, &number.to_string()),
|
||||
serde_json::Value::Bool(boolean) => {
|
||||
push_field(out, if *boolean { "true" } else { "false" })
|
||||
}
|
||||
serde_json::Value::Null => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn field_append_keeps_lines_separate() {
|
||||
let mut fields = SearchFields::default();
|
||||
fields.append_block(&BlockFact {
|
||||
kind: crate::document::BlockKind::Paragraph,
|
||||
span: Span::new(0, 1),
|
||||
unit: 0,
|
||||
text: "a".into(),
|
||||
formula: "f".into(),
|
||||
table: "t".into(),
|
||||
links: "l".into(),
|
||||
code: String::new(),
|
||||
});
|
||||
fields.append_block(&BlockFact {
|
||||
kind: crate::document::BlockKind::Paragraph,
|
||||
span: Span::new(1, 2),
|
||||
unit: 0,
|
||||
text: "b".into(),
|
||||
formula: String::new(),
|
||||
table: String::new(),
|
||||
links: String::new(),
|
||||
code: String::new(),
|
||||
});
|
||||
assert_eq!(fields.body, "a\nb");
|
||||
assert_eq!(fields.formula, "f");
|
||||
assert_eq!(fields.byte_len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatten_json_preserves_keys_and_scalars() {
|
||||
let value = serde_json::json!({"type": "Theory", "tags": ["physics"], "n": 3});
|
||||
let mut out = String::new();
|
||||
flatten_json(&value, &mut out, 0);
|
||||
assert!(out.contains("type"));
|
||||
assert!(out.contains("Theory"));
|
||||
assert!(out.contains("physics"));
|
||||
assert!(out.contains('3'));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user