- exact channel resolves canonical ids, aliases and unique exact names only; multiple exact names are returned as candidates, never silently chosen - lexical channel uses weighted FTS5 BM25 over CJK-bigram segmented fields and reports the matching field; fuzzy channel recalls via the gram index with bounded edit distance, CJK single-character and prefix fallbacks for typos whose bigrams do not overlap - weighted RRF fuses per-node ranks (exact 1.5, lexical/fuzzy/semantic 1.0) and bounded graph expansion follows references both ways, contains children, calls/imports in their direction with --relation/--reverse, depth decay and explicit truncation; --kind filters after expansion - document/execution/hybrid slices share one plan+materialise traversal, skip ancestor duplication, include module context for execution imports, report external/dynamic gaps, enforce the 32 KiB budget on UTF-8 boundaries and keep exact source text with path/span provenance - stale databases are refused unless --snapshot is explicit; query never compiles implicitly and emits the single result envelope with honest channels/truncated/diagnostics - add end-to-end query tests for CJK recall, typo recall, exact/ambiguous ids, kind filtering, graph neighbours, slices, staleness, missing database, no-result honesty and explicit semantic-config failure
372 lines
13 KiB
Rust
372 lines
13 KiB
Rust
//! 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,
|
|
}
|
|
}
|
|
|
|
/// Best similarity between the query and any character window of `text` whose
|
|
/// length is close to the query length. Bounded to short strings; used only for
|
|
/// fuzzy ranking. This tolerates a title suffix ("归一化动机" vs "归依化") without
|
|
/// scanning the corpus.
|
|
pub fn best_window_similarity(query: &str, text: &str) -> f64 {
|
|
let normalized_query = normalize(query);
|
|
let normalized_text = normalize(text);
|
|
let query_chars: Vec<char> = normalized_query.chars().collect();
|
|
let text_chars: Vec<char> = normalized_text.chars().collect();
|
|
if query_chars.is_empty() || text_chars.is_empty() {
|
|
return 0.0;
|
|
}
|
|
if text_chars.len() <= query_chars.len() {
|
|
return similarity(&normalized_query, &normalized_text);
|
|
}
|
|
let width = query_chars.len();
|
|
let mut best = 0.0f64;
|
|
let max_start = text_chars.len().saturating_sub(width).min(32);
|
|
for start in 0..=max_start {
|
|
let end = (start + width).min(text_chars.len());
|
|
let window: String = text_chars[start..end].iter().collect();
|
|
best = best.max(similarity(&normalized_query, &window));
|
|
if best >= 0.999 {
|
|
break;
|
|
}
|
|
}
|
|
best
|
|
}
|
|
|
|
/// 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);
|
|
}
|
|
}
|