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
+342
@@ -0,0 +1,342 @@
|
||||
//! Deterministic search normalisation and tokenisation.
|
||||
//!
|
||||
//! Used by the write path to build the FTS/gram indexes and by the read path to
|
||||
//! segment queries. Normalisation is for indexing and queries only: original
|
||||
//! text, canonical ids and program symbols keep their exact case and Unicode
|
||||
//! form.
|
||||
//!
|
||||
//! * NFKC + lowercase + whitespace collapse for search text;
|
||||
//! * ASCII identifiers are split on camelCase/snake_case/kebab-case boundaries;
|
||||
//! * CJK runs are represented by character bigrams (and trigrams for grams) so
|
||||
//! two-character Chinese queries do not depend on a trigram tokenizer;
|
||||
//! * single-character CJK queries are handled by a bounded exact-character
|
||||
//! fallback in the query layer, not by unbounded scan;
|
||||
//! * quotes/brackets/operators are never passed through as FTS syntax.
|
||||
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
|
||||
/// A CJK/kana/hangul character, treated as one search unit.
|
||||
pub fn is_cjk(ch: char) -> bool {
|
||||
matches!(ch,
|
||||
'\u{3040}'..='\u{30FF}' // kana
|
||||
| '\u{3400}'..='\u{4DBF}' // CJK extension A
|
||||
| '\u{4E00}'..='\u{9FFF}' // CJK unified
|
||||
| '\u{F900}'..='\u{FAFF}' // compatibility ideographs
|
||||
| '\u{AC00}'..='\u{D7AF}' // hangul syllables
|
||||
| '\u{20000}'..='\u{2FA1F}' // CJK extensions B-F
|
||||
)
|
||||
}
|
||||
|
||||
/// Search normalisation: NFKC, Unicode lowercase, control characters removed,
|
||||
/// whitespace runs collapsed to one space and trimmed.
|
||||
pub fn normalize(text: &str) -> String {
|
||||
let normalized: String = text.nfkc().flat_map(char::to_lowercase).collect();
|
||||
let mut out = String::with_capacity(normalized.len());
|
||||
let mut pending_space = false;
|
||||
for ch in normalized.chars() {
|
||||
if ch.is_control() {
|
||||
continue;
|
||||
}
|
||||
if ch.is_whitespace() {
|
||||
pending_space = !out.is_empty();
|
||||
continue;
|
||||
}
|
||||
if pending_space {
|
||||
out.push(' ');
|
||||
pending_space = false;
|
||||
}
|
||||
out.push(ch);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// NFKC without lowercasing or whitespace collapsing, used before identifier
|
||||
/// splitting so camelCase boundaries survive.
|
||||
fn nfkc_only(text: &str) -> String {
|
||||
text.nfkc().filter(|ch| !ch.is_control()).collect()
|
||||
}
|
||||
|
||||
/// Split one ASCII identifier run into searchable parts. Both the whole word
|
||||
/// and the parts are returned, in a stable order.
|
||||
fn identifier_parts(word: &str) -> Vec<String> {
|
||||
let mut parts = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut previous: Option<char> = None;
|
||||
for ch in word.chars() {
|
||||
let boundary = match previous {
|
||||
Some(previous) => {
|
||||
(previous.is_ascii_lowercase() || previous.is_ascii_digit())
|
||||
&& ch.is_ascii_uppercase()
|
||||
|| !ch.is_ascii_alphanumeric()
|
||||
}
|
||||
None => !ch.is_ascii_alphanumeric(),
|
||||
};
|
||||
if boundary && !current.is_empty() {
|
||||
parts.push(std::mem::take(&mut current));
|
||||
}
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
current.push(ch.to_ascii_lowercase());
|
||||
}
|
||||
previous = Some(ch);
|
||||
}
|
||||
if !current.is_empty() {
|
||||
parts.push(current);
|
||||
}
|
||||
if parts.len() > 1 {
|
||||
let whole = parts.concat();
|
||||
if !parts.iter().any(|part| part == &whole) {
|
||||
parts.insert(0, whole);
|
||||
}
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// Tokenise text for the FTS index and for queries.
|
||||
pub fn tokens(text: &str) -> Vec<String> {
|
||||
let normalized = nfkc_only(text);
|
||||
let mut out = Vec::new();
|
||||
let mut ascii = String::new();
|
||||
let mut cjk_run: Vec<char> = Vec::new();
|
||||
let flush_ascii = |ascii: &mut String, out: &mut Vec<String>| {
|
||||
if !ascii.is_empty() {
|
||||
out.extend(identifier_parts(ascii));
|
||||
ascii.clear();
|
||||
}
|
||||
};
|
||||
let flush_cjk = |run: &mut Vec<char>, out: &mut Vec<String>| {
|
||||
if run.is_empty() {
|
||||
return;
|
||||
}
|
||||
if run.len() == 1 {
|
||||
out.push(run[0].to_string());
|
||||
} else {
|
||||
for window in run.windows(2) {
|
||||
out.push(window.iter().collect());
|
||||
}
|
||||
}
|
||||
run.clear();
|
||||
};
|
||||
for ch in normalized.chars() {
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
flush_cjk(&mut cjk_run, &mut out);
|
||||
ascii.push(ch);
|
||||
} else if is_cjk(ch) {
|
||||
flush_ascii(&mut ascii, &mut out);
|
||||
cjk_run.push(ch);
|
||||
} else {
|
||||
flush_ascii(&mut ascii, &mut out);
|
||||
flush_cjk(&mut cjk_run, &mut out);
|
||||
}
|
||||
}
|
||||
flush_ascii(&mut ascii, &mut out);
|
||||
flush_cjk(&mut cjk_run, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Join tokens into the space-separated text stored in the FTS content columns.
|
||||
pub fn segment(text: &str) -> String {
|
||||
tokens(text).join(" ")
|
||||
}
|
||||
|
||||
/// Fuzzy gram candidates: 2/3-gram CJK windows and ASCII identifier parts.
|
||||
pub fn grams(text: &str) -> Vec<String> {
|
||||
let normalized = nfkc_only(text);
|
||||
let mut out = Vec::new();
|
||||
let mut ascii = String::new();
|
||||
let mut cjk_run: Vec<char> = Vec::new();
|
||||
let flush_ascii = |ascii: &mut String, out: &mut Vec<String>| {
|
||||
if ascii.is_empty() {
|
||||
return;
|
||||
}
|
||||
for part in identifier_parts(ascii) {
|
||||
if part.chars().count() >= 2 {
|
||||
out.push(part);
|
||||
}
|
||||
}
|
||||
ascii.clear();
|
||||
};
|
||||
let flush_cjk = |run: &mut Vec<char>, out: &mut Vec<String>| {
|
||||
for width in [2usize, 3usize] {
|
||||
if run.len() >= width {
|
||||
for window in run.windows(width) {
|
||||
out.push(window.iter().collect());
|
||||
}
|
||||
}
|
||||
}
|
||||
run.clear();
|
||||
};
|
||||
for ch in normalized.chars() {
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
flush_cjk(&mut cjk_run, &mut out);
|
||||
ascii.push(ch);
|
||||
} else if is_cjk(ch) {
|
||||
flush_ascii(&mut ascii, &mut out);
|
||||
cjk_run.push(ch);
|
||||
} else {
|
||||
flush_ascii(&mut ascii, &mut out);
|
||||
flush_cjk(&mut cjk_run, &mut out);
|
||||
}
|
||||
}
|
||||
flush_ascii(&mut ascii, &mut out);
|
||||
flush_cjk(&mut cjk_run, &mut out);
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// Bounded Damerau-Levenshtein distance (adjacent transposition) with an early
|
||||
/// exit when the distance is already above `limit`. Never panics.
|
||||
pub fn edit_distance_at_most(left: &str, right: &str, limit: usize) -> Option<usize> {
|
||||
let a: Vec<char> = left.chars().collect();
|
||||
let b: Vec<char> = right.chars().collect();
|
||||
if a.len().abs_diff(b.len()) > limit {
|
||||
return None;
|
||||
}
|
||||
if a == b {
|
||||
return Some(0);
|
||||
}
|
||||
let mut previous_previous: Vec<usize> = Vec::new();
|
||||
let mut previous: Vec<usize> = (0..=b.len()).collect();
|
||||
for (i, a_char) in a.iter().enumerate() {
|
||||
let mut current = vec![i + 1; b.len() + 1];
|
||||
let mut row_min = i + 1;
|
||||
for (j, b_char) in b.iter().enumerate() {
|
||||
let cost = usize::from(a_char != b_char);
|
||||
let mut value = (previous[j + 1] + 1)
|
||||
.min(current[j] + 1)
|
||||
.min(previous[j] + cost);
|
||||
if i > 0 && j > 0 && a_char == &b[j - 1] && a[i - 1] == *b_char {
|
||||
value = value.min(previous_previous[j - 1] + 1);
|
||||
}
|
||||
current[j + 1] = value;
|
||||
row_min = row_min.min(value);
|
||||
}
|
||||
if row_min > limit {
|
||||
return None;
|
||||
}
|
||||
previous_previous = std::mem::replace(&mut previous, current);
|
||||
}
|
||||
let distance = previous[b.len()];
|
||||
(distance <= limit).then_some(distance)
|
||||
}
|
||||
|
||||
/// Similarity in `0.0..=1.0` between a query and one candidate token/title.
|
||||
pub fn similarity(left: &str, right: &str) -> f64 {
|
||||
let left = normalize(left);
|
||||
let right = normalize(right);
|
||||
if left.is_empty() || right.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let max_len = left.chars().count().max(right.chars().count());
|
||||
let limit = max_len.min(8);
|
||||
match edit_distance_at_most(&left, &right, limit) {
|
||||
Some(distance) => 1.0 - distance as f64 / max_len as f64,
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape one token for an FTS5 query: the token is emitted as a quoted string
|
||||
/// literal, so no FTS operator can be injected. Empty tokens are dropped.
|
||||
pub fn fts_quote(token: &str) -> Option<String> {
|
||||
let cleaned = token.replace('"', "");
|
||||
if cleaned.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(format!("\"{cleaned}\""))
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a safe OR query from user text. Returns `None` when no token remains.
|
||||
pub fn fts_query(text: &str) -> Option<String> {
|
||||
let quoted: Vec<String> = tokens(text)
|
||||
.iter()
|
||||
.filter_map(|token| fts_quote(token))
|
||||
.collect();
|
||||
if quoted.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(quoted.join(" OR "))
|
||||
}
|
||||
}
|
||||
|
||||
/// Single CJK character fallback candidates (bounded by the caller).
|
||||
pub fn single_char_terms(text: &str) -> Vec<char> {
|
||||
normalize(text)
|
||||
.chars()
|
||||
.filter(|ch| is_cjk(*ch))
|
||||
.take(8)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn normalization_is_search_only() {
|
||||
assert_eq!(normalize(" Hello WORLD "), "hello world");
|
||||
assert_eq!(normalize("ABC123"), "abc123");
|
||||
assert_eq!(normalize("e\u{0301}"), "\u{00e9}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identifiers_split_on_case_and_separators() {
|
||||
let parts = tokens("normalizeVectorMagnitude");
|
||||
assert!(parts.contains(&"normalize".to_string()));
|
||||
assert!(parts.contains(&"vector".to_string()));
|
||||
assert!(parts.contains(&"magnitude".to_string()));
|
||||
assert!(parts.contains(&"normalizevectormagnitude".to_string()));
|
||||
let parts = tokens("snake_case-kebab");
|
||||
assert!(parts.contains(&"snake".to_string()));
|
||||
assert!(parts.contains(&"case".to_string()));
|
||||
assert!(parts.contains(&"kebab".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cjk_two_character_queries_use_bigrams() {
|
||||
assert_eq!(tokens("量子"), vec!["量子"]);
|
||||
assert_eq!(tokens("量子力学"), vec!["量子", "子力", "力学"]);
|
||||
assert_eq!(tokens("力"), vec!["力"]);
|
||||
let segmented = segment("概率归一化");
|
||||
assert!(segmented.split_whitespace().any(|token| token == "概率"));
|
||||
assert!(segmented.split_whitespace().any(|token| token == "归一"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grams_include_bigrams_and_trigrams() {
|
||||
let cjk_grams = grams("量子力学");
|
||||
assert!(cjk_grams.contains(&"量子".to_string()));
|
||||
assert!(cjk_grams.contains(&"量子力".to_string()));
|
||||
assert!(cjk_grams.contains(&"力学".to_string()));
|
||||
let ascii_grams = grams("normalizeVector");
|
||||
assert!(ascii_grams.contains(&"normalize".to_string()));
|
||||
assert!(ascii_grams.contains(&"vector".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fts_queries_cannot_inject_operators() {
|
||||
let query = fts_query("\"quoted\" AND (paren) *").unwrap();
|
||||
assert!(!query.contains("AND"));
|
||||
assert!(!query.contains("("));
|
||||
assert!(!query.contains("*"));
|
||||
assert!(query.contains("\"quoted\""));
|
||||
assert!(fts_query(" ").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_distance_is_bounded_and_counts_transpositions() {
|
||||
assert_eq!(edit_distance_at_most("kitten", "sitting", 3), Some(3));
|
||||
assert_eq!(edit_distance_at_most("量子", "量子", 1), Some(0));
|
||||
assert_eq!(edit_distance_at_most("归一化", "归一话", 1), Some(1));
|
||||
assert_eq!(edit_distance_at_most("abc", "xyz", 1), None);
|
||||
assert_eq!(edit_distance_at_most("ab", "ba", 1), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn similarity_is_bounded() {
|
||||
assert!(similarity("归一化", "归一化") == 1.0);
|
||||
let score = similarity("归一话", "归一化检查");
|
||||
assert!((0.0..=1.0).contains(&score));
|
||||
assert_eq!(similarity("", "x"), 0.0);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user