Merge branch 'refs/heads/claude/search-f73aec' into feat/integration

# Conflicts:
#	Cargo.lock
This commit is contained in:
dasemu committed 2026-10-21 13:59:55 +02:00
commit b02ec34371
11 files changed
+3321 -5

No files matched your search

Generated
+782 -5
View File
File diff suppressed because it is too large. Load diff
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "synapse-search"
version = "0.1.0"
edition.workspace = true
license.workspace = true
description = "Full-text, vector and hybrid search plus auto-link suggestions for Synapse graphs"
[dependencies]
synapse-core.workspace = true
chrono.workspace = true
rusqlite.workspace = true
thiserror.workspace = true
uuid.workspace = true
# Full-text engine (pure Rust, builds for Android). Only the default-free feature set we need.
tantivy = { version = "0.25", default-features = false, features = ["mmap", "lz4-compression"] }
# Multi-pattern matching of page titles inside block text.
aho-corasick = "1"
[dev-dependencies]
tempfile = "3"
+156
View File
@@ -0,0 +1,156 @@
//! Generates synthetic blocks and prints index/query timings.
//! `cargo run --release -p synapse-search --example bench -- [blocks]`
use std::time::{Duration, Instant};
use synapse_core::{Graph, Placement};
use synapse_search::testing::HashEmbedder;
use synapse_search::{Filter, LinkMatcher, Search};
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n as u64) as usize
}
}
fn pct(mut v: Vec<Duration>, p: f64) -> Duration {
v.sort();
v[((v.len() as f64 * p) as usize).min(v.len() - 1)]
}
fn timed<T>(label: &str, f: impl FnOnce() -> T) -> T {
let t = Instant::now();
let r = f();
println!("{label}: {:.2?}", t.elapsed());
r
}
fn main() {
let n: usize = std::env::args()
.nth(1)
.and_then(|a| a.parse().ok())
.unwrap_or(50_000);
let dir = std::env::temp_dir().join(format!("synapse-bench-{}", std::process::id()));
let g = Graph::open(&dir).unwrap();
let syll = [
"ca", "sa", "ción", "mar", "ten", "lo", "ver", "pro", "ject", "ñan", "dú", "re", "da",
"tion", "ing", "sys",
];
let mut rng = Rng(0x9E3779B97F4A7C15);
let vocab: Vec<String> = (0..8000)
.map(|_| {
(0..2 + rng.below(3))
.map(|_| syll[rng.below(syll.len())])
.collect::<String>()
+ &rng.below(40).to_string()
})
.collect();
let pages: Vec<_> = (0..n / 100 + 1)
.map(|i| {
g.ensure_page(&format!("{} {}", vocab[rng.below(vocab.len())], i), None)
.unwrap()
})
.collect();
timed(&format!("generate {n} blocks (graph writes)"), || {
for _ in 0..n {
let words: Vec<&str> = (0..8 + rng.below(20))
.map(|_| vocab[rng.below(vocab.len())].as_str())
.collect();
let p = &pages[rng.below(pages.len())];
g.insert_block(p.id, Placement::LastChildOf(None), &words.join(" "))
.unwrap();
}
});
let mut s = Search::open(&g).unwrap();
timed("full-text sync (index everything)", || s.sync(&g).unwrap());
println!("index docs: {}", s.doc_count());
let f = Filter::default();
let queries: Vec<String> = (0..300)
.map(|_| {
let w = &vocab[rng.below(vocab.len())];
w.chars().take(2 + rng.below(5)).collect::<String>()
})
.collect();
let mut qs = Vec::new();
for q in &queries {
let t = Instant::now();
s.quick_switch(&g, q, 10).unwrap();
qs.push(t.elapsed());
}
println!(
"quick_switch p50 {:.2?} p99 {:.2?}",
pct(qs.clone(), 0.5),
pct(qs, 0.99)
);
let mut ss = Vec::new();
for q in &queries {
let t = Instant::now();
s.search(&g, q, &f, 20).unwrap();
ss.push(t.elapsed());
}
println!(
"search (prefix, 1 term) p50 {:.2?} p99 {:.2?}",
pct(ss.clone(), 0.5),
pct(ss, 0.99)
);
let mut ms = Vec::new();
for _ in 0..200 {
let q = format!(
"{} {}",
vocab[rng.below(vocab.len())],
vocab[rng.below(vocab.len())]
);
let t = Instant::now();
s.search(&g, &q, &f, 20).unwrap();
ms.push(t.elapsed());
}
println!(
"search (2 full terms) p50 {:.2?} p99 {:.2?}",
pct(ms.clone(), 0.5),
pct(ms, 0.99)
);
let emb = HashEmbedder::new(384);
let stored = timed("embed + store all (fake embedder, 384 dims)", || {
s.embed_pending(&g, &emb, 512, usize::MAX).unwrap()
});
println!("vectors stored: {stored}");
let qv = emb.embed_one(&vocab[1]);
let mut vs = Vec::new();
for _ in 0..20 {
let t = Instant::now();
s.vector_search(&g, "test/hash", &qv, &f, 20).unwrap();
vs.push(t.elapsed());
}
println!("vector_search p50 {:.2?}", pct(vs, 0.5));
let mut hs = Vec::new();
for q in queries.iter().take(20) {
let t = Instant::now();
s.hybrid_search(&g, q, Some(&emb), &f, 20).unwrap();
hs.push(t.elapsed());
}
println!("hybrid_search p50 {:.2?}", pct(hs, 0.5));
let m = timed("LinkMatcher::new", || LinkMatcher::new(&g).unwrap());
let t = Instant::now();
let mut found = 0;
for p in pages.iter().take(50) {
found += m.suggest_page(&g, p.id).unwrap().len();
}
println!(
"suggest_page x50 pages: {:.2?} ({found} suggestions)",
t.elapsed()
);
timed("unlinked_references (1 page)", || {
s.unlinked_references(&g, pages[0].id, 50).unwrap().len()
});
std::fs::remove_dir_all(dir).ok();
}
+426
View File
@@ -0,0 +1,426 @@
//! Auto-link suggestions: unlinked references (Aho-Corasick over page titles/aliases) and
//! semantic suggestions (page embeddings close to a block).
use crate::error::{Error, Result};
use aho_corasick::{AhoCorasick, MatchKind};
use std::collections::HashMap;
use std::ops::Range;
use synapse_core::{Block, BlockId, Graph, PageId, parse};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Reason {
/// The block text contains the title of an existing page.
ExactTitle,
/// The block text contains an alias of an existing page.
Alias,
/// The block is semantically close to the page (cosine similarity).
Semantic { similarity: f32 },
}
#[derive(Debug, Clone, PartialEq)]
pub struct Suggestion {
pub block: BlockId,
/// Byte range in the block content to replace by `[[Title]]`. `None` for semantic
/// suggestions, which are appended to the block instead.
pub span: Option<Range<usize>>,
/// The text found at `span` (used to detect stale suggestions).
pub matched: String,
pub target_page: PageId,
pub score: f32,
pub reason: Reason,
}
struct Pattern {
page: PageId,
alias: bool,
len: usize,
}
/// Finds occurrences of page titles and aliases in text.
pub struct LinkMatcher {
ac: Option<AhoCorasick>,
patterns: Vec<Pattern>,
min_chars: usize,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Match {
pub span: Range<usize>,
pub page: PageId,
pub alias: bool,
}
impl LinkMatcher {
/// Builds a matcher from every page title and alias of the graph.
pub fn new(graph: &Graph) -> Result<Self> {
let aliases: std::collections::HashSet<String> = {
let mut st = graph.conn().prepare("SELECT alias FROM aliases")?;
st.query_map([], |r| r.get::<_, String>(0))?
.collect::<std::result::Result<_, _>>()?
};
let titles = graph
.all_titles()?
.into_iter()
.map(|(t, id)| {
let a = aliases.contains(&t);
(t, id, a)
})
.collect();
Ok(Self::from_titles(titles))
}
/// Builds a matcher from `(text, page, is_alias)` entries. Entries shorter than 3
/// characters are ignored (too noisy).
pub fn from_titles(titles: Vec<(String, PageId, bool)>) -> Self {
let min_chars = 3;
let mut seen: HashMap<String, ()> = HashMap::new();
let mut keys = Vec::new();
let mut patterns = Vec::new();
// Titles before aliases so a title wins when both spell the same text.
let mut titles = titles;
titles.sort_by_key(|t| t.2);
for (text, page, alias) in titles {
let key = text.trim().to_lowercase();
if key.chars().count() < min_chars || seen.insert(key.clone(), ()).is_some() {
continue;
}
patterns.push(Pattern {
page,
alias,
len: key.len(),
});
keys.push(key);
}
let ac = if keys.is_empty() {
None
} else {
AhoCorasick::builder()
.match_kind(MatchKind::Standard)
.build(&keys)
.ok()
};
Self {
ac,
patterns,
min_chars,
}
}
pub fn is_empty(&self) -> bool {
self.patterns.is_empty()
}
pub fn min_chars(&self) -> usize {
self.min_chars
}
/// Non-overlapping, longest-first, word-bounded matches outside code spans, existing
/// links, tags, URLs and property lines.
pub fn find(&self, text: &str) -> Vec<Match> {
let Some(ac) = &self.ac else {
return Vec::new();
};
let (lower, map) = lower_with_map(text);
let orig = |i: usize| map.as_ref().map_or(i, |m| m[i]);
let excluded = excluded_ranges(text);
let mut cands: Vec<Match> = Vec::new();
for m in ac.find_overlapping_iter(&lower) {
let (s, e) = (orig(m.start()), orig(m.end()));
if s >= e || !word_bounded(text, s, e) {
continue;
}
if excluded.iter().any(|r| s < r.end && r.start < e) {
continue;
}
let p = &self.patterns[m.pattern().as_usize()];
debug_assert!(p.len > 0);
cands.push(Match {
span: s..e,
page: p.page,
alias: p.alias,
});
}
// Greedy: leftmost first, longest first.
cands.sort_by(|a, b| {
a.span
.start
.cmp(&b.span.start)
.then(b.span.end.cmp(&a.span.end))
});
let mut out: Vec<Match> = Vec::new();
for c in cands {
if out.last().is_none_or(|l| c.span.start >= l.span.end) {
out.push(c);
}
}
out
}
/// Unlinked-reference suggestions for one block.
pub fn suggest_block(&self, block: &Block, skip_own_page: bool) -> Vec<Suggestion> {
self.find(&block.content)
.into_iter()
.filter(|m| !(skip_own_page && m.page == block.page_id))
.map(|m| {
let matched = block.content[m.span.clone()].to_string();
let chars = matched.chars().count() as f32;
Suggestion {
block: block.id,
score: 0.8 + 0.2 * (chars / 20.0).min(1.0),
reason: if m.alias {
Reason::Alias
} else {
Reason::ExactTitle
},
target_page: m.page,
span: Some(m.span),
matched,
}
})
.collect()
}
/// Unlinked-reference suggestions for every block of a page.
pub fn suggest_page(&self, graph: &Graph, page: PageId) -> Result<Vec<Suggestion>> {
let mut out = Vec::new();
for (_, b) in graph.page_tree(page)? {
out.extend(self.suggest_block(&b, true));
}
Ok(out)
}
}
/// Rewrites the block so the suggested text becomes `[[Title]]` (semantic suggestions are
/// appended as ` [[Title]]`). Fails with [`Error::Stale`] if the block changed meanwhile.
pub fn apply_suggestion(graph: &Graph, s: &Suggestion) -> Result<Block> {
let block = graph
.get_block(s.block)?
.ok_or_else(|| Error::Stale(format!("block {} is gone", s.block)))?;
let page = graph
.get_page(s.target_page)?
.ok_or_else(|| Error::Stale(format!("page {} is gone", s.target_page)))?;
let link = format!("[[{}]]", page.title);
let content = match &s.span {
Some(r) => {
let ok = block.content.get(r.clone()) == Some(s.matched.as_str());
if !ok {
return Err(Error::Stale("block text changed".into()));
}
format!(
"{}{}{}",
&block.content[..r.start],
link,
&block.content[r.end..]
)
}
None => format!("{} {}", block.content.trim_end(), link),
};
Ok(graph.update_block(s.block, &content)?)
}
fn lower_with_map(text: &str) -> (String, Option<Vec<usize>>) {
let lower = text.to_lowercase();
if lower.len() == text.len() {
return (lower, None);
}
let mut out = String::with_capacity(text.len());
let mut map = Vec::with_capacity(text.len() + 1);
for (i, c) in text.char_indices() {
for lc in c.to_lowercase() {
let before = out.len();
out.push(lc);
map.extend(std::iter::repeat_n(i, out.len() - before));
}
}
map.push(text.len());
(out, Some(map))
}
fn word_bounded(text: &str, s: usize, e: usize) -> bool {
let first = text[s..].chars().next();
let last = text[..e].chars().next_back();
let before_ok = !first.is_some_and(|c| c.is_alphanumeric())
|| !text[..s]
.chars()
.next_back()
.is_some_and(|c| c.is_alphanumeric());
let after_ok = !last.is_some_and(|c| c.is_alphanumeric())
|| !text[e..]
.chars()
.next()
.is_some_and(|c| c.is_alphanumeric());
before_ok && after_ok
}
/// Byte ranges where a match must not be turned into a link.
pub(crate) fn excluded_ranges(text: &str) -> Vec<Range<usize>> {
let mut out = Vec::new();
let mut in_fence = false;
let mut offset = 0;
for line in text.split_inclusive('\n') {
let start = offset;
offset += line.len();
let trimmed = line.trim_start();
if trimmed.starts_with("```") {
in_fence = !in_fence;
out.push(start..offset);
continue;
}
if in_fence || parse::property_split(line.trim_end_matches(['\n', '\r'])).is_some() {
out.push(start..offset);
continue;
}
scan_inline(line, start, &mut out);
}
out
}
fn scan_inline(line: &str, base: usize, out: &mut Vec<Range<usize>>) {
let b = line.as_bytes();
let mut i = 0;
let find = |from: usize, pat: &str| line[from..].find(pat).map(|p| p + from);
while i < b.len() {
match b[i] {
b'`' => {
let run = b[i..].iter().take_while(|&&c| c == b'`').count();
let fence = "`".repeat(run);
match find(i + run, &fence) {
Some(end) => {
out.push(base + i..base + end + run);
i = end + run;
}
None => i += run,
}
}
b'[' if b.get(i + 1) == Some(&b'[') => match find(i + 2, "]]") {
Some(end) => {
out.push(base + i..base + end + 2);
i = end + 2;
}
None => i += 2,
},
b'[' => {
// [text](target) markdown link.
let close = find(i + 1, "](");
match close.and_then(|c| find(c + 2, ")").map(|e| (c, e))) {
Some((_, end)) => {
out.push(base + i..base + end + 1);
i = end + 1;
}
None => i += 1,
}
}
b'(' if b.get(i + 1) == Some(&b'(') => match find(i + 2, "))") {
Some(end) => {
out.push(base + i..base + end + 2);
i = end + 2;
}
None => i += 2,
},
b'{' if b.get(i + 1) == Some(&b'{') => match find(i + 2, "}}") {
Some(end) => {
out.push(base + i..base + end + 2);
i = end + 2;
}
None => i += 2,
},
b'#' if i == 0 || b[i - 1].is_ascii_whitespace() || b[i - 1] == b'(' => {
let end = line[i..]
.find(char::is_whitespace)
.map_or(line.len(), |p| p + i);
out.push(base + i..base + end);
i = end.max(i + 1);
}
b'h' if line[i..].starts_with("http://") || line[i..].starts_with("https://") => {
let end = line[i..]
.find(char::is_whitespace)
.map_or(line.len(), |p| p + i);
out.push(base + i..base + end);
i = end;
}
_ => i += 1,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use uuid::Uuid;
fn matcher(titles: &[(&str, bool)]) -> (LinkMatcher, Vec<Uuid>) {
let ids: Vec<Uuid> = titles.iter().map(|_| Uuid::now_v7()).collect();
let m = LinkMatcher::from_titles(
titles
.iter()
.zip(&ids)
.map(|((t, a), id)| (t.to_string(), *id, *a))
.collect(),
);
(m, ids)
}
fn found(m: &LinkMatcher, text: &str) -> Vec<String> {
m.find(text)
.into_iter()
.map(|x| text[x.span].to_string())
.collect()
}
#[test]
fn word_boundaries_and_longest() {
let (m, _) = matcher(&[("Rust", false), ("Rust Language", false), ("art", false)]);
assert_eq!(
found(&m, "I love rust language and Rusty things, smart"),
vec!["rust language"]
);
assert_eq!(found(&m, "(Rust)"), vec!["Rust"]);
}
#[test]
fn skips_code_links_tags_urls_properties() {
let (m, _) = matcher(&[("Rust", false)]);
assert!(
found(
&m,
"`Rust` and [[Rust]] and #Rust and https://rust.org/Rust"
)
.is_empty()
);
assert!(found(&m, "[Rust](http://x) ((Rust))").is_empty());
assert!(found(&m, "```\nRust\n```").is_empty());
assert!(found(&m, "tags:: Rust").is_empty());
assert_eq!(found(&m, "line one\nRust here"), vec!["Rust"]);
}
#[test]
fn unicode_case_and_accents() {
let (m, _) = matcher(&[("Canción", false)]);
assert_eq!(found(&m, "Una CANCIÓN bonita"), vec!["CANCIÓN"]);
assert!(found(&m, "una cancion bonita").is_empty());
}
#[test]
fn short_titles_ignored_and_alias_flag() {
let (m, ids) = matcher(&[
("ab", false),
("Machine Learning", false),
("ML tech", true),
]);
assert_eq!(found(&m, "ab is short"), Vec::<String>::new());
let r = m.find("ml tech rocks");
assert_eq!(r.len(), 1);
assert!(r[0].alias);
assert_eq!(r[0].page, ids[2]);
}
#[test]
fn offsets_survive_length_changing_lowercase() {
// 'İ' lowercases to two chars ("i̇"), shifting byte offsets.
let (m, _) = matcher(&[("Rust", false)]);
let text = "İİ Rust";
let r = m.find(text);
assert_eq!(r.len(), 1);
assert_eq!(&text[r[0].span.clone()], "Rust");
}
}
+24
View File
@@ -0,0 +1,24 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("core: {0}")]
Core(#[from] synapse_core::Error),
#[error("sqlite: {0}")]
Sqlite(#[from] rusqlite::Error),
#[error("tantivy: {0}")]
Tantivy(#[from] tantivy::TantivyError),
#[error("tantivy directory: {0}")]
Directory(#[from] tantivy::directory::error::OpenDirectoryError),
#[error("io: {0}")]
Io(#[from] std::io::Error),
#[error("embedder: {0}")]
Embed(String),
#[error("invalid: {0}")]
Invalid(String),
/// A suggestion no longer matches the block text (the block changed since).
#[error("stale suggestion: {0}")]
Stale(String),
}
pub type Result<T> = std::result::Result<T, Error>;
+430
View File
@@ -0,0 +1,430 @@
//! tantivy-backed full-text index: one document per block and one per page (title + aliases).
use crate::error::Result;
use crate::{Filter, JournalFilter, Scope};
use chrono::{Local, NaiveDate};
use std::collections::BTreeSet;
use std::ops::Bound;
use std::path::Path;
use tantivy::collector::TopDocs;
use tantivy::query::{
BooleanQuery, BoostQuery, FuzzyTermQuery, Occur, PhraseQuery, Query, RangeQuery, TermQuery,
};
use tantivy::schema::{
Field, IndexRecordOption, STRING, Schema, TextFieldIndexing, TextOptions, Value,
};
use tantivy::tokenizer::{
AsciiFoldingFilter, Language, LowerCaser, RemoveLongFilter, SimpleTokenizer, Stemmer,
TextAnalyzer,
};
use tantivy::{Index, IndexReader, IndexWriter, ReloadPolicy, TantivyDocument, Term};
use uuid::Uuid;
const TOKENIZER: &str = "synapse";
/// Optional stemming applied at index and query time (changing it triggers a rebuild).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Stemming {
#[default]
None,
English,
Spanish,
}
impl Stemming {
pub(crate) fn as_str(self) -> &'static str {
match self {
Stemming::None => "none",
Stemming::English => "en",
Stemming::Spanish => "es",
}
}
}
fn analyzer(stemming: Stemming) -> TextAnalyzer {
let b = TextAnalyzer::builder(SimpleTokenizer::default())
.filter(RemoveLongFilter::limit(48))
.filter(LowerCaser)
.filter(AsciiFoldingFilter);
match stemming {
Stemming::None => b.build(),
Stemming::English => b.filter(Stemmer::new(Language::English)).build(),
Stemming::Spanish => b.filter(Stemmer::new(Language::Spanish)).build(),
}
}
#[derive(Clone, Copy)]
struct Fields {
kind: Field,
id: Field,
page_id: Field,
content: Field,
title: Field,
day: Field,
journal: Field,
}
pub(crate) struct FullText {
index: Index,
reader: IndexReader,
writer: IndexWriter,
f: Fields,
analyzer: TextAnalyzer,
}
pub(crate) struct RawHit {
pub is_page: bool,
pub id: Uuid,
pub page_id: Uuid,
pub score: f32,
}
pub(crate) fn day_of_ms(ms: i64) -> i64 {
let d = chrono::DateTime::from_timestamp_millis(ms)
.map(|t| t.with_timezone(&Local).date_naive())
.unwrap_or_default();
day_of_date(d)
}
pub(crate) fn day_of_date(d: NaiveDate) -> i64 {
use chrono::Datelike;
d.num_days_from_ce() as i64 - 719_163
}
impl FullText {
pub fn open(dir: &Path, stemming: Stemming, heap_bytes: usize) -> Result<Self> {
std::fs::create_dir_all(dir)?;
let mut sb = Schema::builder();
let text = |positions: bool| {
TextOptions::default().set_indexing_options(
TextFieldIndexing::default()
.set_tokenizer(TOKENIZER)
.set_index_option(if positions {
IndexRecordOption::WithFreqsAndPositions
} else {
IndexRecordOption::WithFreqs
}),
)
};
let f = Fields {
kind: sb.add_text_field("kind", STRING | tantivy::schema::STORED),
id: sb.add_text_field("id", STRING | tantivy::schema::STORED),
page_id: sb.add_text_field("page_id", STRING | tantivy::schema::STORED),
content: sb.add_text_field("content", text(true)),
title: sb.add_text_field("title", text(true)),
day: sb.add_i64_field(
"day",
tantivy::schema::INDEXED | tantivy::schema::FAST | tantivy::schema::STORED,
),
journal: sb.add_u64_field(
"journal",
tantivy::schema::INDEXED | tantivy::schema::FAST | tantivy::schema::STORED,
),
};
let index =
Index::open_or_create(tantivy::directory::MmapDirectory::open(dir)?, sb.build())?;
let analyzer = analyzer(stemming);
index.tokenizers().register(TOKENIZER, analyzer.clone());
let writer = index.writer(heap_bytes.max(15_000_000))?;
let reader = index
.reader_builder()
.reload_policy(ReloadPolicy::Manual)
.try_into()?;
Ok(Self {
index,
reader,
writer,
f,
analyzer,
})
}
pub fn clear(&mut self) -> Result<()> {
self.writer.delete_all_documents()?;
Ok(())
}
pub fn commit(&mut self) -> Result<()> {
self.writer.commit()?;
self.reader.reload()?;
Ok(())
}
pub fn doc_count(&self) -> u64 {
self.reader.searcher().num_docs()
}
pub fn delete(&mut self, id: Uuid) {
self.writer
.delete_term(Term::from_field_text(self.f.id, &id.to_string()));
}
pub fn upsert_block(
&mut self,
id: Uuid,
page_id: Uuid,
content: &str,
day: i64,
journal: bool,
) -> Result<()> {
self.delete(id);
let mut d = TantivyDocument::default();
d.add_text(self.f.kind, "b");
d.add_text(self.f.id, id.to_string());
d.add_text(self.f.page_id, page_id.to_string());
d.add_text(self.f.content, content);
d.add_i64(self.f.day, day);
d.add_u64(self.f.journal, journal as u64);
self.writer.add_document(d)?;
Ok(())
}
pub fn upsert_page(
&mut self,
id: Uuid,
title: &str,
aliases: &[String],
day: i64,
journal: bool,
) -> Result<()> {
self.delete(id);
let mut d = TantivyDocument::default();
d.add_text(self.f.kind, "p");
d.add_text(self.f.id, id.to_string());
d.add_text(self.f.page_id, id.to_string());
d.add_text(self.f.title, title);
for a in aliases {
d.add_text(self.f.title, a);
}
d.add_i64(self.f.day, day);
d.add_u64(self.f.journal, journal as u64);
self.writer.add_document(d)?;
Ok(())
}
pub fn tokens(&self, text: &str) -> Vec<String> {
let mut a = self.analyzer.clone();
let mut out = Vec::new();
let mut s = a.token_stream(text);
s.process(&mut |t| out.push(t.text.clone()));
out
}
fn term_query(&self, field: Field, tok: &str, last: bool) -> Box<dyn Query> {
let term = Term::from_field_text(field, tok);
let n = tok.chars().count();
if last {
// Search-as-you-type: prefix match, tolerating one typo from 5 characters on.
Box::new(FuzzyTermQuery::new_prefix(term, (n >= 5) as u8, true))
} else if n >= 5 {
Box::new(BooleanQuery::new(vec![
(
Occur::Should,
Box::new(TermQuery::new(term.clone(), IndexRecordOption::WithFreqs))
as Box<dyn Query>,
),
(
Occur::Should,
Box::new(BoostQuery::new(
Box::new(FuzzyTermQuery::new(term, 1, true)),
0.4,
)),
),
]))
} else {
Box::new(TermQuery::new(term, IndexRecordOption::WithFreqs))
}
}
fn text_query(&self, fields: &[(Field, f32)], toks: &[String], all: bool) -> Box<dyn Query> {
let occur = if all { Occur::Must } else { Occur::Should };
let clauses = toks
.iter()
.enumerate()
.map(|(i, tok)| {
let per_field = fields
.iter()
.map(|&(f, boost)| {
let q = self.term_query(f, tok, i + 1 == toks.len());
(
Occur::Should,
Box::new(BoostQuery::new(q, boost)) as Box<dyn Query>,
)
})
.collect();
(
occur,
Box::new(BooleanQuery::new(per_field)) as Box<dyn Query>,
)
})
.collect();
Box::new(BooleanQuery::new(clauses))
}
fn filter_clauses(&self, filter: &Filter) -> Vec<(Occur, Box<dyn Query>)> {
let mut c: Vec<(Occur, Box<dyn Query>)> = Vec::new();
let term = |f: Field, v: &str| -> Box<dyn Query> {
Box::new(TermQuery::new(
Term::from_field_text(f, v),
IndexRecordOption::Basic,
))
};
match filter.scope {
Scope::All => {}
Scope::Pages => c.push((Occur::Must, term(self.f.kind, "p"))),
Scope::Blocks => c.push((Occur::Must, term(self.f.kind, "b"))),
}
match filter.journals {
JournalFilter::Any => {}
JournalFilter::Only => c.push((
Occur::Must,
Box::new(TermQuery::new(
Term::from_field_u64(self.f.journal, 1),
IndexRecordOption::Basic,
)),
)),
JournalFilter::Exclude => c.push((
Occur::Must,
Box::new(TermQuery::new(
Term::from_field_u64(self.f.journal, 0),
IndexRecordOption::Basic,
)),
)),
}
if let Some(p) = filter.page {
c.push((Occur::Must, term(self.f.page_id, &p.to_string())));
}
if filter.from.is_some() || filter.to.is_some() {
let b = |d: Option<NaiveDate>| match d {
Some(d) => Bound::Included(Term::from_field_i64(self.f.day, day_of_date(d))),
None => Bound::Unbounded,
};
c.push((
Occur::Must,
Box::new(RangeQuery::new(b(filter.from), b(filter.to))),
));
}
c
}
fn run(&self, q: Box<dyn Query>, limit: usize) -> Result<Vec<RawHit>> {
let searcher = self.reader.searcher();
let top = searcher.search(&q, &TopDocs::with_limit(limit.max(1)))?;
let mut out = Vec::with_capacity(top.len());
for (score, addr) in top {
let d: TantivyDocument = searcher.doc(addr)?;
let get = |f: Field| {
d.get_first(f)
.and_then(|v| v.as_str())
.and_then(|s| Uuid::parse_str(s).ok())
};
let (Some(id), Some(page_id)) = (get(self.f.id), get(self.f.page_id)) else {
continue;
};
let is_page = d.get_first(self.f.kind).and_then(|v| v.as_str()) == Some("p");
out.push(RawHit {
is_page,
id,
page_id,
score,
});
}
Ok(out)
}
/// Ranked full-text search over blocks and page titles. All terms must match; when that
/// finds nothing the query is relaxed to "any term".
pub fn search(&self, text: &str, filter: &Filter, limit: usize) -> Result<Vec<RawHit>> {
let toks = self.tokens(text);
if toks.is_empty() {
return Ok(Vec::new());
}
let fields = [(self.f.content, 1.0), (self.f.title, 3.0)];
for all in [true, false] {
let mut clauses = self.filter_clauses(filter);
clauses.push((Occur::Must, self.text_query(&fields, &toks, all)));
let hits = self.run(Box::new(BooleanQuery::new(clauses)), limit)?;
if !hits.is_empty() || toks.len() == 1 {
return Ok(hits);
}
}
Ok(Vec::new())
}
/// Quick switcher: page titles and aliases only, prefix + typo tolerant.
pub fn quick_switch(&self, text: &str, limit: usize) -> Result<Vec<RawHit>> {
let toks = self.tokens(text);
if toks.is_empty() {
return Ok(Vec::new());
}
let clauses = vec![
(
Occur::Must,
Box::new(TermQuery::new(
Term::from_field_text(self.f.kind, "p"),
IndexRecordOption::Basic,
)) as Box<dyn Query>,
),
(
Occur::Must,
self.text_query(&[(self.f.title, 1.0)], &toks, true),
),
];
self.run(Box::new(BooleanQuery::new(clauses)), limit)
}
/// Blocks whose text contains the phrase `text` (candidates for unlinked references).
pub fn phrase_blocks(&self, text: &str, limit: usize) -> Result<Vec<RawHit>> {
let toks = self.tokens(text);
let q: Box<dyn Query> = match toks.len() {
0 => return Ok(Vec::new()),
1 => Box::new(TermQuery::new(
Term::from_field_text(self.f.content, &toks[0]),
IndexRecordOption::WithFreqs,
)),
_ => Box::new(PhraseQuery::new(
toks.iter()
.map(|t| Term::from_field_text(self.f.content, t))
.collect(),
)),
};
let clauses = vec![
(
Occur::Must,
Box::new(TermQuery::new(
Term::from_field_text(self.f.kind, "b"),
IndexRecordOption::Basic,
)) as Box<dyn Query>,
),
(Occur::Must, q),
];
self.run(Box::new(BooleanQuery::new(clauses)), limit)
}
/// Test/diagnostic helper: ids of all indexed docs.
#[allow(dead_code)]
pub fn all_ids(&self) -> Result<BTreeSet<Uuid>> {
let searcher = self.reader.searcher();
let top = searcher.search(
&tantivy::query::AllQuery,
&TopDocs::with_limit(searcher.num_docs() as usize + 1),
)?;
let mut out = BTreeSet::new();
for (_, addr) in top {
let d: TantivyDocument = searcher.doc(addr)?;
if let Some(id) = d
.get_first(self.f.id)
.and_then(|v| v.as_str())
.and_then(|s| Uuid::parse_str(s).ok())
{
out.insert(id);
}
}
Ok(out)
}
#[allow(dead_code)]
pub fn index(&self) -> &Index {
&self.index
}
}
+911
View File
@@ -0,0 +1,911 @@
//! Search and auto-link suggestions over a [`synapse_core::Graph`].
//!
//! * Full-text: tantivy index in `<graph_dir>/index/`, kept up to date from the op log
//! ([`Search::sync`]).
//! * Vectors: int8-quantised embeddings in the graph's SQLite (`search_vectors`), exact scan.
//! * Hybrid: reciprocal rank fusion of both ([`Search::hybrid_search`]).
//! * Auto-links: [`LinkMatcher`] (unlinked references) and [`Search::semantic_suggestions`].
pub mod autolink;
mod error;
mod fulltext;
pub mod testing;
mod vectors;
pub use autolink::{LinkMatcher, Match, Reason, Suggestion, apply_suggestion};
pub use error::{Error, Result};
pub use fulltext::Stemming;
use chrono::NaiveDate;
use fulltext::{FullText, day_of_date, day_of_ms};
use rusqlite::{OptionalExtension, params};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use synapse_core::embed::Embedder;
use synapse_core::{BlockId, Graph, Op, PageId, parse};
use uuid::Uuid;
use vectors::{VecIndex, normalize, quantize};
const SCHEMA_VERSION: &str = "1";
const RRF_K: f32 = 60.0;
const MAX_CHUNK_CHARS: usize = 2000;
const SEARCH_SCHEMA: &str = r#"
CREATE TABLE IF NOT EXISTS search_state (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS search_vectors (
id TEXT NOT NULL,
model_id TEXT NOT NULL,
kind TEXT NOT NULL,
page_id TEXT NOT NULL,
stamp INTEGER NOT NULL,
dims INTEGER NOT NULL,
scale REAL NOT NULL,
vec BLOB NOT NULL,
PRIMARY KEY (id, model_id)
);
CREATE INDEX IF NOT EXISTS search_vectors_kind ON search_vectors(model_id, kind);
"#;
#[derive(Debug, Clone)]
pub struct Config {
pub stemming: Stemming,
/// tantivy indexing heap budget (bytes). Lower it on phones.
pub heap_bytes: usize,
}
impl Default for Config {
fn default() -> Self {
Self {
stemming: Stemming::None,
heap_bytes: 32 << 20,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Scope {
#[default]
All,
Pages,
Blocks,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum JournalFilter {
#[default]
Any,
Only,
Exclude,
}
/// Search filters. The date range applies to the journal date of journal content and to the
/// last edit day of everything else.
#[derive(Debug, Clone, Default)]
pub struct Filter {
pub scope: Scope,
pub journals: JournalFilter,
pub from: Option<NaiveDate>,
pub to: Option<NaiveDate>,
/// Restrict to one page (its blocks, or the page itself).
pub page: Option<PageId>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HitKind {
Page,
Block,
}
#[derive(Debug, Clone)]
pub struct SearchHit {
pub kind: HitKind,
/// Block id for blocks, page id for pages.
pub id: Uuid,
pub page_id: PageId,
pub page_title: String,
/// Block content (truncated) or the page title.
pub snippet: String,
pub score: f32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VectorKind {
Page,
Block,
}
impl VectorKind {
fn as_str(self) -> &'static str {
match self {
VectorKind::Page => "p",
VectorKind::Block => "b",
}
}
}
/// Text waiting to be embedded. Pass it back to [`Search::store_embeddings`] with its vector.
#[derive(Debug, Clone)]
pub struct PendingEmbedding {
pub id: Uuid,
pub kind: VectorKind,
pub page_id: PageId,
pub stamp: i64,
/// Chunk to embed: page title context + block text.
pub text: String,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SyncStats {
pub ops_processed: usize,
pub blocks_indexed: usize,
pub docs_deleted: usize,
}
#[derive(Default)]
struct ModelVectors {
blocks: VecIndex,
pages: VecIndex,
}
pub struct Search {
ft: FullText,
vectors: RefCell<HashMap<String, ModelVectors>>,
}
fn state_get(graph: &Graph, key: &str) -> Result<Option<String>> {
Ok(graph
.conn()
.query_row("SELECT value FROM search_state WHERE key=?1", [key], |r| {
r.get(0)
})
.optional()?)
}
fn state_set(graph: &Graph, key: &str, value: &str) -> Result<()> {
graph.conn().execute(
"INSERT OR REPLACE INTO search_state(key, value) VALUES (?1, ?2)",
params![key, value],
)?;
Ok(())
}
fn fnv(text: &str) -> i64 {
let mut h: u64 = 0xcbf29ce484222325;
for b in text.bytes() {
h = (h ^ b as u64).wrapping_mul(0x100000001b3);
}
h as i64
}
fn truncate(s: &str, max: usize) -> String {
match s.char_indices().nth(max) {
Some((i, _)) => format!("{}…", &s[..i]),
None => s.to_string(),
}
}
fn clean_for_embedding(content: &str) -> String {
truncate(
&content.replace("[[", "").replace("]]", ""),
MAX_CHUNK_CHARS,
)
}
impl Search {
/// Opens the index at `<graph_dir>/index/`, creating it if needed. Call [`Search::sync`]
/// afterwards to catch up with the op log.
pub fn open(graph: &Graph) -> Result<Self> {
Self::open_with(graph, Config::default())
}
pub fn open_with(graph: &Graph, config: Config) -> Result<Self> {
graph.conn().execute_batch(SEARCH_SCHEMA)?;
let dir = graph.dir().join("index");
let want = format!("{SCHEMA_VERSION}/{}", config.stemming.as_str());
let mismatch = state_get(graph, "index_config")?.as_deref() != Some(&want);
if mismatch && dir.exists() {
std::fs::remove_dir_all(&dir)?;
}
if mismatch {
state_set(graph, "last_seq", "0")?;
state_set(graph, "index_config", &want)?;
}
let ft = FullText::open(&dir, config.stemming, config.heap_bytes)?;
// The index directory was lost or never committed: start over from the op log.
if ft.doc_count() == 0 && last_seq(graph)? != 0 && graph.last_seq()? != 0 {
state_set(graph, "last_seq", "0")?;
}
Ok(Self {
ft,
vectors: RefCell::new(HashMap::new()),
})
}
/// Number of documents in the full-text index.
pub fn doc_count(&self) -> u64 {
self.ft.doc_count()
}
// ------------------------------------------------------------ indexing
/// Applies op-log entries newer than the persisted sequence to the index.
pub fn sync(&mut self, graph: &Graph) -> Result<SyncStats> {
let mut stats = SyncStats::default();
let mut last = last_seq(graph)?;
let start = last;
loop {
let ops = graph.ops_since(last, 5000)?;
let Some(tail) = ops.last() else { break };
let next = tail.seq;
let mut blocks: HashSet<BlockId> = HashSet::new();
let mut pages: HashSet<PageId> = HashSet::new();
let mut all_pages = false;
for rec in &ops {
match &rec.op {
Op::UpsertBlock { block } => {
blocks.insert(block.id);
}
Op::DeleteBlock { id } => {
blocks.insert(*id);
}
Op::UpsertPage { page } => {
pages.insert(page.id);
}
Op::DeletePage { id } => {
pages.insert(*id);
}
// The previous owner of an alias is not in the op, so refresh all pages.
Op::SetAlias { .. } => all_pages = true,
Op::PutAsset { .. } => {}
}
}
stats.ops_processed += ops.len();
let mut cache: HashMap<PageId, Option<(Option<NaiveDate>, i64)>> = HashMap::new();
for id in blocks {
match graph.get_block(id)? {
Some(b) => {
let info = *cache.entry(b.page_id).or_insert_with(|| {
graph
.get_page(b.page_id)
.ok()
.flatten()
.map(|p| (p.journal_date, p.updated_at))
});
let (day, journal) = match info.and_then(|i| i.0) {
Some(d) => (day_of_date(d), true),
None => (day_of_ms(b.updated_at), false),
};
self.ft
.upsert_block(b.id, b.page_id, &b.content, day, journal)?;
stats.blocks_indexed += 1;
}
None => {
self.ft.delete(id);
self.drop_vectors(graph, id)?;
stats.docs_deleted += 1;
}
}
}
if all_pages {
self.index_all_pages(graph)?;
} else {
for id in pages {
self.index_page(graph, id)?;
}
}
last = next;
}
if last != start {
self.ft.commit()?;
state_set(graph, "last_seq", &last.to_string())?;
}
Ok(stats)
}
/// Drops the index and rebuilds it from the current graph state.
pub fn rebuild(&mut self, graph: &Graph) -> Result<SyncStats> {
self.ft.clear()?;
self.ft.commit()?;
state_set(graph, "last_seq", "0")?;
self.sync(graph)
}
fn index_page(&mut self, graph: &Graph, id: PageId) -> Result<()> {
match graph.get_page(id)? {
Some(p) => {
let aliases = graph.aliases_of(id)?;
let (day, journal) = match p.journal_date {
Some(d) => (day_of_date(d), true),
None => (day_of_ms(p.updated_at), false),
};
self.ft.upsert_page(id, &p.title, &aliases, day, journal)?;
}
None => {
self.ft.delete(id);
self.drop_vectors(graph, id)?;
}
}
Ok(())
}
fn index_all_pages(&mut self, graph: &Graph) -> Result<()> {
let mut aliases: HashMap<String, Vec<String>> = HashMap::new();
{
let mut st = graph.conn().prepare("SELECT page_id, alias FROM aliases")?;
for r in st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))? {
let (p, a) = r?;
aliases.entry(p).or_default().push(a);
}
}
let mut offset = 0;
loop {
let pages = graph.list_pages(true, 1000, offset)?;
if pages.is_empty() {
break;
}
offset += pages.len() as u32;
for p in pages {
let al = aliases.remove(&p.id.to_string()).unwrap_or_default();
let (day, journal) = match p.journal_date {
Some(d) => (day_of_date(d), true),
None => (day_of_ms(p.updated_at), false),
};
self.ft.upsert_page(p.id, &p.title, &al, day, journal)?;
}
}
Ok(())
}
// ------------------------------------------------------------ full text
/// Ranked full-text search over blocks and page titles.
pub fn search(
&self,
graph: &Graph,
query: &str,
filter: &Filter,
limit: usize,
) -> Result<Vec<SearchHit>> {
let raw = self.ft.search(query, filter, limit)?;
hydrate(graph, raw.into_iter().map(|h| (h.is_page, h.id, h.score)))
}
/// Quick switcher: page titles/aliases, prefix and typo tolerant.
pub fn quick_switch(&self, graph: &Graph, query: &str, limit: usize) -> Result<Vec<SearchHit>> {
let raw = self.ft.quick_switch(query, limit)?;
hydrate(graph, raw.into_iter().map(|h| (true, h.id, h.score)))
}
// -------------------------------------------------------------- vectors
/// Chunks (page titles, then blocks) whose vector for `model_id` is missing or stale.
pub fn pending_embeddings(
&self,
graph: &Graph,
model_id: &str,
limit: usize,
) -> Result<Vec<PendingEmbedding>> {
let mut out = Vec::new();
// Pages: embed "title; alias; alias". Stale when that text's hash changes.
let mut aliases: HashMap<String, Vec<String>> = HashMap::new();
{
let mut st = graph.conn().prepare("SELECT page_id, alias FROM aliases")?;
for r in st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))? {
let (p, a) = r?;
aliases.entry(p).or_default().push(a);
}
}
{
let mut st = graph.conn().prepare(
"SELECT p.id, p.title, v.stamp FROM pages p
LEFT JOIN search_vectors v ON v.id = p.id AND v.model_id = ?1
WHERE p.journal_date IS NULL",
)?;
let rows = st.query_map([model_id], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, Option<i64>>(2)?,
))
})?;
for r in rows {
let (id, title, stamp) = r?;
let mut text = title;
for a in aliases.get(&id).into_iter().flatten() {
text.push_str("; ");
text.push_str(a);
}
let h = fnv(&text);
if stamp != Some(h) {
let id = parse_uuid(&id)?;
out.push(PendingEmbedding {
id,
kind: VectorKind::Page,
page_id: id,
stamp: h,
text,
});
if out.len() >= limit {
return Ok(out);
}
}
}
}
let mut st = graph.conn().prepare(
"SELECT b.id, b.page_id, b.content, b.updated_at, p.title FROM blocks b
JOIN pages p ON p.id = b.page_id
LEFT JOIN search_vectors v ON v.id = b.id AND v.model_id = ?1
WHERE trim(b.content) <> '' AND (v.id IS NULL OR v.stamp <> b.updated_at)
LIMIT ?2",
)?;
let rows = st.query_map(params![model_id, (limit - out.len()) as i64], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, String>(2)?,
r.get::<_, i64>(3)?,
r.get::<_, String>(4)?,
))
})?;
for r in rows {
let (id, page, content, stamp, title) = r?;
out.push(PendingEmbedding {
id: parse_uuid(&id)?,
kind: VectorKind::Block,
page_id: parse_uuid(&page)?,
stamp,
text: format!("{title}\n{}", clean_for_embedding(&content)),
});
}
Ok(out)
}
/// Stores vectors for previously pending chunks (L2-normalised, int8-quantised).
pub fn store_embeddings(
&self,
graph: &Graph,
model_id: &str,
items: &[(PendingEmbedding, Vec<f32>)],
) -> Result<()> {
let tx = graph.conn().unchecked_transaction()?;
self.ensure_loaded(graph, model_id)?;
let mut vectors = self.vectors.borrow_mut();
let mv = vectors.get_mut(model_id).expect("loaded");
for (p, v) in items {
let (q, scale) = quantize(&normalize(v));
let bytes: Vec<u8> = q.iter().map(|&x| x as u8).collect();
tx.execute(
"INSERT OR REPLACE INTO search_vectors
(id, model_id, kind, page_id, stamp, dims, scale, vec)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
params![
p.id.to_string(),
model_id,
p.kind.as_str(),
p.page_id.to_string(),
p.stamp,
q.len() as i64,
scale,
bytes
],
)?;
let ix = match p.kind {
VectorKind::Page => &mut mv.pages,
VectorKind::Block => &mut mv.blocks,
};
ix.upsert_quantized(p.id, p.page_id, p.stamp, &q, scale);
}
tx.commit()?;
Ok(())
}
/// Embeds up to `max_items` pending chunks with `embedder`, `batch` texts per call.
/// Returns how many vectors were stored.
pub fn embed_pending(
&self,
graph: &Graph,
embedder: &dyn Embedder,
batch: usize,
max_items: usize,
) -> Result<usize> {
let model = embedder.model_id();
let mut done = 0;
while done < max_items {
let pending =
self.pending_embeddings(graph, &model, batch.min(max_items - done).max(1))?;
if pending.is_empty() {
break;
}
let texts: Vec<String> = pending.iter().map(|p| p.text.clone()).collect();
let vecs = embedder
.embed(&texts)
.map_err(|e| Error::Embed(e.to_string()))?;
if vecs.len() != pending.len() {
return Err(Error::Embed(
"embedder returned a wrong vector count".into(),
));
}
let items: Vec<_> = pending.into_iter().zip(vecs).collect();
done += items.len();
self.store_embeddings(graph, &model, &items)?;
}
Ok(done)
}
/// Number of stored vectors `(pages, blocks)` for a model.
pub fn vector_counts(&self, graph: &Graph, model_id: &str) -> Result<(usize, usize)> {
self.ensure_loaded(graph, model_id)?;
let v = self.vectors.borrow();
let m = &v[model_id];
Ok((m.pages.len(), m.blocks.len()))
}
fn ensure_loaded(&self, graph: &Graph, model_id: &str) -> Result<()> {
if !self.vectors.borrow().contains_key(model_id) {
self.load_model(graph, model_id)?;
}
Ok(())
}
fn load_model(&self, graph: &Graph, model_id: &str) -> Result<()> {
let mut mv = ModelVectors::default();
let mut st = graph.conn().prepare(
"SELECT id, kind, page_id, stamp, scale, vec FROM search_vectors WHERE model_id=?1",
)?;
let rows = st.query_map([model_id], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, String>(2)?,
r.get::<_, i64>(3)?,
r.get::<_, f32>(4)?,
r.get::<_, Vec<u8>>(5)?,
))
})?;
for r in rows {
let (id, kind, page, stamp, scale, bytes) = r?;
let q: Vec<i8> = bytes.into_iter().map(|b| b as i8).collect();
let ix = if kind == "p" {
&mut mv.pages
} else {
&mut mv.blocks
};
ix.upsert_quantized(parse_uuid(&id)?, parse_uuid(&page)?, stamp, &q, scale);
}
self.vectors.borrow_mut().insert(model_id.to_string(), mv);
Ok(())
}
fn drop_vectors(&self, graph: &Graph, id: Uuid) -> Result<()> {
graph
.conn()
.execute("DELETE FROM search_vectors WHERE id=?1", [id.to_string()])?;
for mv in self.vectors.borrow_mut().values_mut() {
mv.blocks.remove(id);
mv.pages.remove(id);
}
Ok(())
}
/// Pure semantic search. `query` is any vector from the model `model_id`.
pub fn vector_search(
&self,
graph: &Graph,
model_id: &str,
query: &[f32],
filter: &Filter,
limit: usize,
) -> Result<Vec<SearchHit>> {
let ranked = self.vector_candidates(graph, model_id, query, filter, limit)?;
hydrate(graph, ranked.into_iter())
}
/// `(is_page, id, cosine)` ranked, post-filtered.
fn vector_candidates(
&self,
graph: &Graph,
model_id: &str,
query: &[f32],
filter: &Filter,
limit: usize,
) -> Result<Vec<(bool, Uuid, f32)>> {
self.ensure_loaded(graph, model_id)?;
let q = normalize(query);
let vectors = self.vectors.borrow();
let mv = &vectors[model_id];
// Over-fetch because journal/date filters are applied after the scan.
let fetch = if filter.journals == JournalFilter::Any
&& filter.from.is_none()
&& filter.to.is_none()
{
limit
} else {
limit * 5 + 50
};
let mut all: Vec<(bool, vectors::Neighbor)> = Vec::new();
if filter.scope != Scope::Pages {
all.extend(
mv.blocks
.top_k(&q, fetch, filter.page)
.into_iter()
.map(|n| (false, n)),
);
}
if filter.scope != Scope::Blocks {
all.extend(
mv.pages
.top_k(&q, fetch, filter.page)
.into_iter()
.map(|n| (true, n)),
);
}
all.sort_by(|a, b| b.1.score.total_cmp(&a.1.score));
let mut pages: HashMap<PageId, Option<Option<NaiveDate>>> = HashMap::new();
let mut out = Vec::new();
for (is_page, n) in all {
let jd = *pages.entry(n.page).or_insert_with(|| {
graph
.get_page(n.page)
.ok()
.flatten()
.map(|p| p.journal_date)
});
let Some(jd) = jd else { continue };
match (filter.journals, jd.is_some()) {
(JournalFilter::Only, false) | (JournalFilter::Exclude, true) => continue,
_ => {}
}
let day = jd.map(day_of_date).unwrap_or_else(|| day_of_ms(n.stamp));
if filter.from.is_some_and(|d| day < day_of_date(d))
|| filter.to.is_some_and(|d| day > day_of_date(d))
{
continue;
}
out.push((is_page, n.id, n.score));
if out.len() >= limit {
break;
}
}
Ok(out)
}
// --------------------------------------------------------------- hybrid
/// Hybrid search: embeds `query` with `embedder` (may block on the network) and fuses
/// full-text and vector rankings with reciprocal rank fusion. Without an embedder, or when
/// no vectors are stored yet, this is plain full-text search.
pub fn hybrid_search(
&self,
graph: &Graph,
query: &str,
embedder: Option<&dyn Embedder>,
filter: &Filter,
limit: usize,
) -> Result<Vec<SearchHit>> {
match embedder {
Some(e) => {
let v = e
.embed(&[query.to_string()])
.map_err(|e| Error::Embed(e.to_string()))?
.into_iter()
.next()
.ok_or_else(|| Error::Embed("empty embedding response".into()))?;
self.hybrid_with_vector(graph, query, Some((&e.model_id(), &v)), filter, limit)
}
None => self.hybrid_with_vector(graph, query, None, filter, limit),
}
}
/// Like [`Search::hybrid_search`] with a precomputed query vector `(model_id, vector)`.
pub fn hybrid_with_vector(
&self,
graph: &Graph,
query: &str,
vector: Option<(&str, &[f32])>,
filter: &Filter,
limit: usize,
) -> Result<Vec<SearchHit>> {
let pool = (limit * 3).max(50);
let text = self.ft.search(query, filter, pool)?;
let sem = match vector {
Some((model, v)) => self.vector_candidates(graph, model, v, filter, pool)?,
None => Vec::new(),
};
let mut fused: HashMap<(bool, Uuid), f32> = HashMap::new();
for (rank, h) in text.iter().enumerate() {
*fused.entry((h.is_page, h.id)).or_default() += 1.0 / (RRF_K + rank as f32 + 1.0);
}
for (rank, (is_page, id, _)) in sem.iter().enumerate() {
*fused.entry((*is_page, *id)).or_default() += 1.0 / (RRF_K + rank as f32 + 1.0);
}
let mut ranked: Vec<_> = fused.into_iter().collect();
ranked.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.1.cmp(&b.0.1)));
ranked.truncate(limit);
hydrate(graph, ranked.into_iter().map(|((p, id), s)| (p, id, s)))
}
// ------------------------------------------------------------ auto-link
/// Blocks that mention `page` by title or alias without linking it, best first.
pub fn unlinked_references(
&self,
graph: &Graph,
page: PageId,
limit: usize,
) -> Result<Vec<Suggestion>> {
let Some(p) = graph.get_page(page)? else {
return Ok(Vec::new());
};
let mut names = vec![(p.title.clone(), page, false)];
names.extend(graph.aliases_of(page)?.into_iter().map(|a| (a, page, true)));
let matcher = LinkMatcher::from_titles(names.clone());
let mut seen = HashSet::new();
let mut out = Vec::new();
for (name, _, _) in names {
for h in self.ft.phrase_blocks(&name, 1000)? {
if h.page_id == page || !seen.insert(h.id) {
continue;
}
let Some(b) = graph.get_block(h.id)? else {
continue;
};
out.extend(matcher.suggest_block(&b, true));
}
}
out.sort_by(|a, b| b.score.total_cmp(&a.score));
out.truncate(limit);
Ok(out)
}
/// Pages whose embedding is close to the block's, not yet linked from it.
pub fn semantic_suggestions(
&self,
graph: &Graph,
model_id: &str,
block: BlockId,
limit: usize,
min_similarity: f32,
) -> Result<Vec<Suggestion>> {
let Some(b) = graph.get_block(block)? else {
return Ok(Vec::new());
};
self.ensure_loaded(graph, model_id)?;
let vectors = self.vectors.borrow();
let mv = &vectors[model_id];
let Some(v) = mv.blocks.get(block) else {
return Ok(Vec::new());
};
let linked: HashSet<String> = parse::extract_refs(&b.content)
.pages
.iter()
.map(|(t, _)| synapse_core::title_key(t))
.collect();
let mut out = Vec::new();
for n in mv
.pages
.top_k(&normalize(&v), limit + linked.len() + 1, None)
{
if n.score < min_similarity || n.id == b.page_id {
continue;
}
let Some(p) = graph.get_page(n.id)? else {
continue;
};
if linked.contains(&synapse_core::title_key(&p.title)) {
continue;
}
out.push(Suggestion {
block,
span: None,
matched: String::new(),
target_page: n.id,
score: n.score,
reason: Reason::Semantic {
similarity: n.score,
},
});
if out.len() >= limit {
break;
}
}
Ok(out)
}
/// Lexical suggestions first, then semantic ones for pages not already suggested.
pub fn suggestions_for_block(
&self,
graph: &Graph,
matcher: &LinkMatcher,
model_id: Option<&str>,
block: BlockId,
limit: usize,
min_similarity: f32,
) -> Result<Vec<Suggestion>> {
let Some(b) = graph.get_block(block)? else {
return Ok(Vec::new());
};
let mut out = matcher.suggest_block(&b, true);
if let Some(m) = model_id {
let have: HashSet<PageId> = out.iter().map(|s| s.target_page).collect();
out.extend(
self.semantic_suggestions(graph, m, block, limit, min_similarity)?
.into_iter()
.filter(|s| !have.contains(&s.target_page)),
);
}
out.truncate(limit);
Ok(out)
}
/// Pages most similar to `page` by title embedding.
pub fn related_pages(
&self,
graph: &Graph,
model_id: &str,
page: PageId,
limit: usize,
) -> Result<Vec<(PageId, f32)>> {
self.ensure_loaded(graph, model_id)?;
let vectors = self.vectors.borrow();
let mv = &vectors[model_id];
let Some(v) = mv.pages.get(page) else {
return Ok(Vec::new());
};
Ok(mv
.pages
.top_k(&normalize(&v), limit + 1, None)
.into_iter()
.filter(|n| n.id != page)
.take(limit)
.map(|n| (n.id, n.score))
.collect())
}
}
fn last_seq(graph: &Graph) -> Result<i64> {
Ok(state_get(graph, "last_seq")?
.and_then(|s| s.parse().ok())
.unwrap_or(0))
}
fn parse_uuid(s: &str) -> Result<Uuid> {
Uuid::parse_str(s).map_err(|e| Error::Invalid(e.to_string()))
}
fn hydrate(graph: &Graph, raw: impl Iterator<Item = (bool, Uuid, f32)>) -> Result<Vec<SearchHit>> {
let mut titles: HashMap<PageId, Option<String>> = HashMap::new();
let mut out = Vec::new();
for (is_page, id, score) in raw {
if is_page {
let Some(p) = graph.get_page(id)? else {
continue;
};
out.push(SearchHit {
kind: HitKind::Page,
id,
page_id: id,
snippet: p.title.clone(),
page_title: p.title,
score,
});
} else {
let Some(b) = graph.get_block(id)? else {
continue;
};
let title = titles
.entry(b.page_id)
.or_insert_with(|| graph.get_page(b.page_id).ok().flatten().map(|p| p.title))
.clone();
let Some(page_title) = title else { continue };
out.push(SearchHit {
kind: HitKind::Block,
id,
page_id: b.page_id,
page_title,
snippet: truncate(&b.content, 300),
score,
});
}
}
Ok(out)
}
+50
View File
@@ -0,0 +1,50 @@
//! Deterministic fake embedder for tests, examples and benchmarks.
use synapse_core::embed::{EmbedError, Embedder};
/// Bag-of-words hashing embedder: texts sharing words get a high cosine similarity.
pub struct HashEmbedder {
dims: usize,
model: String,
}
impl HashEmbedder {
pub fn new(dims: usize) -> Self {
Self::with_model(dims, "test/hash")
}
pub fn with_model(dims: usize, model: &str) -> Self {
Self {
dims,
model: model.to_string(),
}
}
pub fn embed_one(&self, text: &str) -> Vec<f32> {
let mut v = vec![0f32; self.dims];
for word in text
.split(|c: char| !c.is_alphanumeric())
.filter(|w| !w.is_empty())
{
// FNV-1a over the lowercased word.
let mut h: u64 = 0xcbf29ce484222325;
for b in word.to_lowercase().bytes() {
h = (h ^ b as u64).wrapping_mul(0x100000001b3);
}
v[(h % self.dims as u64) as usize] += 1.0;
}
v
}
}
impl Embedder for HashEmbedder {
fn model_id(&self) -> String {
self.model.clone()
}
fn dims(&self) -> usize {
self.dims
}
fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>, EmbedError> {
Ok(texts.iter().map(|t| self.embed_one(t)).collect())
}
}
+182
View File
@@ -0,0 +1,182 @@
//! In-memory exact vector index over int8-quantised, L2-normalised embeddings.
//!
//! Why brute force instead of HNSW: pure Rust, no C++ toolchain, trivially correct, supports
//! deletes/updates in O(1), and int8 rows keep memory small (100k × 384 dims = 38 MB). A scan
//! with 8 independent accumulators auto-vectorises (NEON/SSE/AVX) and stays within a few tens
//! of milliseconds at 100k vectors. Beyond ~500k vectors an ANN structure becomes worthwhile.
use std::collections::HashMap;
use uuid::Uuid;
#[derive(Default)]
pub(crate) struct VecIndex {
dims: usize,
ids: Vec<Uuid>,
pages: Vec<Uuid>,
stamps: Vec<i64>,
scales: Vec<f32>,
data: Vec<i8>,
slot: HashMap<Uuid, usize>,
}
pub(crate) fn normalize(v: &[f32]) -> Vec<f32> {
let n = v.iter().map(|x| x * x).sum::<f32>().sqrt();
if n == 0.0 {
v.to_vec()
} else {
v.iter().map(|x| x / n).collect()
}
}
/// Quantises an (already normalised) vector to int8 with a per-vector scale.
pub(crate) fn quantize(v: &[f32]) -> (Vec<i8>, f32) {
let max = v.iter().fold(0f32, |m, x| m.max(x.abs()));
if max == 0.0 {
return (vec![0; v.len()], 0.0);
}
let scale = max / 127.0;
(v.iter().map(|x| (x / scale).round() as i8).collect(), scale)
}
fn dot(row: &[i8], q: &[f32]) -> f32 {
let mut acc = [0f32; 8];
let mut rc = row.chunks_exact(8);
let mut qc = q.chunks_exact(8);
for (r, c) in (&mut rc).zip(&mut qc) {
for i in 0..8 {
acc[i] += r[i] as f32 * c[i];
}
}
let mut s: f32 = acc.iter().sum();
for (r, c) in rc.remainder().iter().zip(qc.remainder()) {
s += *r as f32 * c;
}
s
}
impl VecIndex {
pub fn len(&self) -> usize {
self.ids.len()
}
pub fn upsert_quantized(&mut self, id: Uuid, page: Uuid, stamp: i64, q: &[i8], scale: f32) {
if self.dims == 0 {
self.dims = q.len();
}
if q.len() != self.dims {
return;
}
if let Some(&s) = self.slot.get(&id) {
self.pages[s] = page;
self.stamps[s] = stamp;
self.scales[s] = scale;
self.data[s * self.dims..(s + 1) * self.dims].copy_from_slice(q);
} else {
self.slot.insert(id, self.ids.len());
self.ids.push(id);
self.pages.push(page);
self.stamps.push(stamp);
self.scales.push(scale);
self.data.extend_from_slice(q);
}
}
pub fn remove(&mut self, id: Uuid) {
let Some(s) = self.slot.remove(&id) else {
return;
};
let last = self.ids.len() - 1;
if s != last {
let moved = self.ids[last];
self.ids.swap(s, last);
self.pages.swap(s, last);
self.stamps.swap(s, last);
self.scales.swap(s, last);
for i in 0..self.dims {
self.data.swap(s * self.dims + i, last * self.dims + i);
}
self.slot.insert(moved, s);
}
self.ids.pop();
self.pages.pop();
self.stamps.pop();
self.scales.pop();
self.data.truncate(last * self.dims);
}
/// Dequantised vector of `id`.
pub fn get(&self, id: Uuid) -> Option<Vec<f32>> {
let s = *self.slot.get(&id)?;
let sc = self.scales[s];
Some(
self.data[s * self.dims..(s + 1) * self.dims]
.iter()
.map(|&x| x as f32 * sc)
.collect(),
)
}
/// Top-`k` by cosine similarity; `query` must be normalised.
pub fn top_k(&self, query: &[f32], k: usize, page: Option<Uuid>) -> Vec<Neighbor> {
if query.len() != self.dims || self.ids.is_empty() || k == 0 {
return Vec::new();
}
let mut scored: Vec<(f32, usize)> = Vec::with_capacity(self.ids.len());
for s in 0..self.ids.len() {
if let Some(p) = page
&& self.pages[s] != p
{
continue;
}
let row = &self.data[s * self.dims..(s + 1) * self.dims];
scored.push((dot(row, query) * self.scales[s], s));
}
let cmp = |a: &(f32, usize), b: &(f32, usize)| b.0.total_cmp(&a.0);
if scored.len() > k {
scored.select_nth_unstable_by(k - 1, cmp);
scored.truncate(k);
}
scored.sort_by(cmp);
scored
.into_iter()
.map(|(score, s)| Neighbor {
id: self.ids[s],
page: self.pages[s],
stamp: self.stamps[s],
score,
})
.collect()
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Neighbor {
pub id: Uuid,
pub page: Uuid,
pub stamp: i64,
pub score: f32,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nearest_and_remove() {
let mut ix = VecIndex::default();
let ids: Vec<Uuid> = (0..3).map(|_| Uuid::now_v7()).collect();
let p = Uuid::now_v7();
for (i, v) in [[1.0, 0.0], [0.0, 1.0], [0.7, 0.7]].iter().enumerate() {
let (q, s) = quantize(&normalize(v));
ix.upsert_quantized(ids[i], p, 0, &q, s);
}
let r = ix.top_k(&normalize(&[1.0, 0.1]), 2, None);
assert_eq!(r[0].id, ids[0]);
assert_eq!(r[1].id, ids[2]);
ix.remove(ids[0]);
assert_eq!(ix.len(), 2);
let r = ix.top_k(&normalize(&[1.0, 0.1]), 1, None);
assert_eq!(r[0].id, ids[2]);
assert!(ix.get(ids[1]).is_some());
}
}
+294
View File
@@ -0,0 +1,294 @@
use synapse_core::{Graph, NewPage, Placement, journal_title};
use synapse_search::testing::HashEmbedder;
use synapse_search::{
Filter, HitKind, JournalFilter, LinkMatcher, Reason, Scope, Search, Stemming, apply_suggestion,
};
use tempfile::TempDir;
fn setup() -> (TempDir, Graph) {
let dir = TempDir::new().unwrap();
let g = Graph::open(dir.path()).unwrap();
(dir, g)
}
fn add(g: &Graph, page: &str, text: &str) -> synapse_core::Block {
let p = g.ensure_page(page, None).unwrap();
g.insert_block(p.id, Placement::LastChildOf(None), text)
.unwrap()
}
#[test]
fn fulltext_folding_prefix_fuzzy_and_incremental() {
let (_d, g) = setup();
let b = add(&g, "Music", "Mi canción favorita es de Ñandú");
add(&g, "Cooking", "Receta de paella valenciana");
let mut s = Search::open(&g).unwrap();
let st = s.sync(&g).unwrap();
assert!(st.blocks_indexed >= 2);
let f = Filter::default();
macro_rules! hit {
($q:expr) => {
s.search(&g, $q, &f, 10).unwrap()
};
}
assert_eq!(hit!("cancion")[0].id, b.id, "ascii folding");
assert_eq!(hit!("CANCIÓN")[0].id, b.id);
assert_eq!(hit!("nandu")[0].id, b.id);
assert_eq!(hit!("favo")[0].id, b.id, "prefix on last token");
assert_eq!(hit!("favorta")[0].id, b.id, "typo tolerance");
assert!(hit!("zzzz").is_empty());
// Incremental: edit, delete.
g.update_block(b.id, "Ahora hablo de guitarras").unwrap();
s.sync(&g).unwrap();
assert!(hit!("cancion").is_empty());
assert_eq!(hit!("guitarras")[0].id, b.id);
g.delete_block(b.id).unwrap();
s.sync(&g).unwrap();
assert!(hit!("guitarras").is_empty());
// Quick switcher over titles and aliases.
let p = g.page_by_title("Cooking").unwrap().unwrap();
g.set_alias("Cocina", Some(p.id)).unwrap();
s.sync(&g).unwrap();
let q = s.quick_switch(&g, "coc", 5).unwrap();
assert_eq!(q[0].kind, HitKind::Page);
assert_eq!(q[0].page_id, p.id);
g.rename_page(p.id, "Recetas").unwrap();
s.sync(&g).unwrap();
assert_eq!(s.quick_switch(&g, "rece", 5).unwrap()[0].page_id, p.id);
}
#[test]
fn state_persists_and_rebuild_works() {
let (d, g) = setup();
let b = add(&g, "A", "hello persistent world");
{
let mut s = Search::open(&g).unwrap();
s.sync(&g).unwrap();
}
let mut s = Search::open(&g).unwrap();
assert_eq!(s.sync(&g).unwrap().ops_processed, 0);
assert_eq!(
s.search(&g, "persistent", &Filter::default(), 5).unwrap()[0].id,
b.id
);
s.rebuild(&g).unwrap();
assert_eq!(
s.search(&g, "persistent", &Filter::default(), 5).unwrap()[0].id,
b.id
);
drop(s);
// Index directory wiped: reopening recovers from the op log.
std::fs::remove_dir_all(d.path().join("index")).unwrap();
let mut s = Search::open(&g).unwrap();
s.sync(&g).unwrap();
assert_eq!(
s.search(&g, "persistent", &Filter::default(), 5).unwrap()[0].id,
b.id
);
}
#[test]
fn stemming_and_filters() {
let (_d, g) = setup();
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2024, 3, 5).unwrap())
.unwrap();
let jb = g
.insert_block(
j.id,
Placement::LastChildOf(None),
"corriendo por el parque",
)
.unwrap();
let pb = add(&g, "Deporte", "correr es sano");
let mut s = Search::open_with(
&g,
synapse_search::Config {
stemming: Stemming::Spanish,
..Default::default()
},
)
.unwrap();
s.sync(&g).unwrap();
let all = s.search(&g, "correr", &Filter::default(), 10).unwrap();
assert_eq!(
all.len(),
2,
"stemmed: correr/corriendo share a stem? {all:?}"
);
let only_j = Filter {
journals: JournalFilter::Only,
..Default::default()
};
assert_eq!(s.search(&g, "correr", &only_j, 10).unwrap()[0].id, jb.id);
let no_j = Filter {
journals: JournalFilter::Exclude,
..Default::default()
};
assert_eq!(s.search(&g, "correr", &no_j, 10).unwrap()[0].id, pb.id);
let range = Filter {
from: chrono::NaiveDate::from_ymd_opt(2024, 3, 1),
to: chrono::NaiveDate::from_ymd_opt(2024, 3, 31),
..Default::default()
};
let r = s.search(&g, "correr", &range, 10).unwrap();
assert_eq!(r.len(), 1);
assert_eq!(r[0].id, jb.id);
let page = Filter {
page: Some(pb.page_id),
..Default::default()
};
assert_eq!(s.search(&g, "correr", &page, 10).unwrap()[0].id, pb.id);
let pages = Filter {
scope: Scope::Pages,
..Default::default()
};
assert!(s.search(&g, "correr", &pages, 10).unwrap().is_empty());
assert_eq!(
s.search(&g, &journal_title(j.journal_date.unwrap())[..4], &pages, 10)
.unwrap()
.len(),
1
);
}
#[test]
fn vectors_pending_store_and_hybrid() {
let (_d, g) = setup();
let rust = g.ensure_page("Rust", None).unwrap();
let cook = g.ensure_page("Cocina", None).unwrap();
let b1 = add(
&g,
"Notes",
"borrow checker lifetimes and ownership in rust code",
);
let b2 = add(&g, "Notes", "receta de cocina con arroz y verduras");
let mut s = Search::open(&g).unwrap();
s.sync(&g).unwrap();
let emb = HashEmbedder::new(256);
let model = "test/hash";
let pending = s.pending_embeddings(&g, model, 100).unwrap();
assert!(pending.len() >= 4);
let n = s.embed_pending(&g, &emb, 3, 1000).unwrap();
assert_eq!(n, pending.len());
assert!(s.pending_embeddings(&g, model, 100).unwrap().is_empty());
assert_eq!(s.vector_counts(&g, model).unwrap().1, 2);
// Persisted and reloaded by a fresh Search.
drop(s);
let mut s = Search::open(&g).unwrap();
s.sync(&g).unwrap();
assert_eq!(s.vector_counts(&g, model).unwrap().1, 2);
// Pure semantic hit with no shared full-text token (hash embedder shares words only).
let qv = emb.embed_one("rust ownership");
let v = s
.vector_search(
&g,
model,
&qv,
&Filter {
scope: Scope::Blocks,
..Default::default()
},
3,
)
.unwrap();
assert_eq!(v[0].id, b1.id);
// Hybrid: full-text finds "arroz", vectors find the rust block; both in results.
let h = s
.hybrid_search(&g, "arroz rust", Some(&emb), &Filter::default(), 5)
.unwrap();
let ids: Vec<_> = h.iter().map(|x| x.id).collect();
assert!(ids.contains(&b1.id) && ids.contains(&b2.id));
// Editing a block makes it pending again; deleting drops its vector.
g.update_block(b2.id, "cambio de tema total").unwrap();
assert_eq!(s.pending_embeddings(&g, model, 100).unwrap().len(), 1);
g.delete_block(b1.id).unwrap();
s.sync(&g).unwrap();
assert_eq!(s.vector_counts(&g, model).unwrap().1, 1);
// Semantic suggestion toward the Rust page.
let b3 = add(&g, "Notes", "learning rust ownership");
s.sync(&g).unwrap();
s.embed_pending(&g, &emb, 10, 100).unwrap();
let sg = s.semantic_suggestions(&g, model, b3.id, 3, 0.05).unwrap();
assert_eq!(sg[0].target_page, rust.id);
assert!(matches!(sg[0].reason, Reason::Semantic { .. }));
assert!(
sg.iter()
.all(|x| x.target_page != cook.id || x.score < sg[0].score)
);
let applied = apply_suggestion(&g, &sg[0]).unwrap();
assert_eq!(applied.content, "learning rust ownership [[Rust]]");
assert!(
s.semantic_suggestions(&g, model, b3.id, 3, 0.05)
.unwrap()
.iter()
.all(|x| x.target_page != rust.id)
);
assert_eq!(s.related_pages(&g, model, rust.id, 3).unwrap().len(), 2);
let _ = (cook,);
}
#[test]
fn unlinked_references_and_apply() {
let (_d, g) = setup();
let rust = g.create_page(NewPage::titled("Rust Lang")).unwrap();
g.set_alias("rustlang", Some(rust.id)).unwrap();
let b1 = add(
&g,
"Journal",
"Today I read about rust lang and its borrow checker",
);
let b2 = add(
&g,
"Journal",
"Already linked: [[Rust Lang]] and `rust lang` in code",
);
let b3 = add(&g, "Journal", "Ping RustLang folks");
let mut s = Search::open(&g).unwrap();
s.sync(&g).unwrap();
let m = LinkMatcher::new(&g).unwrap();
assert!(
m.suggest_block(&g.get_block(b2.id).unwrap().unwrap(), true)
.is_empty()
);
let sug = m.suggest_block(&g.get_block(b1.id).unwrap().unwrap(), true);
assert_eq!(sug.len(), 1);
assert_eq!(sug[0].reason, Reason::ExactTitle);
let un = s.unlinked_references(&g, rust.id, 10).unwrap();
let blocks: Vec<_> = un.iter().map(|x| x.block).collect();
assert!(blocks.contains(&b1.id) && blocks.contains(&b3.id) && !blocks.contains(&b2.id));
let alias = un.iter().find(|x| x.block == b3.id).unwrap();
assert_eq!(alias.reason, Reason::Alias);
let nb = apply_suggestion(&g, &sug[0]).unwrap();
assert_eq!(
nb.content,
"Today I read about [[Rust Lang]] and its borrow checker"
);
// The link is now registered as a backlink and the suggestion is gone.
assert_eq!(g.backlinks(rust.id).unwrap().len(), 2);
assert!(m.suggest_block(&nb, true).is_empty());
// Applying again fails: the text changed.
assert!(matches!(
apply_suggestion(&g, &sug[0]),
Err(synapse_search::Error::Stale(_))
));
assert_eq!(
m.suggest_page(&g, g.page_by_title("Journal").unwrap().unwrap().id)
.unwrap()
.len(),
1
);
}
+46
View File
@@ -0,0 +1,46 @@
# Search (`synapse-search`)
Search and auto-link suggestions over a `synapse_core::Graph`. All entry points are on
`Search` (one per open graph, not `Sync`), taking `&Graph` per call.
## Full-text
- tantivy index in `<graph_dir>/index/`: one doc per block and one per page (title + aliases).
Page titles shown in results are resolved from SQLite, so renames need no block reindex.
- Analyzer: simple tokenizer → lowercase → ASCII folding (`canción`≈`cancion`, `ñ`≈`n`) →
optional stemmer (`Config::stemming`: none/English/Spanish; changing it rebuilds the index).
- Query: every term must match (relaxed to any term if nothing matches); the last term is a
prefix; terms ≥ 5 chars tolerate one typo. `quick_switch` searches page titles/aliases only.
- Incremental: `Search::sync(&graph)` replays `Graph::ops_since(last_seq)`; the last indexed
seq lives in table `search_state` of the graph DB. Documents are re-read from the DB, so
replaying is idempotent. `rebuild` re-indexes from scratch; a missing index dir recovers
automatically on open.
## Vectors
- Table `search_vectors(id, model_id, kind, page_id, stamp, dims, scale, vec)`: L2-normalised
vectors quantised to int8 with a per-vector scale (4× smaller than f32, cosine error ≈ 1e-2).
- Search is an exact scan over the in-memory int8 matrix (loaded lazily per model), not HNSW:
pure Rust, no C++, O(1) updates/deletes, ~6 ms at 50k and ~12 ms at 100k vectors (384 dims).
Revisit with an ANN structure beyond ~500k vectors.
- The caller controls batching and network: `pending_embeddings(graph, model, limit)` returns
chunks (`page title\nblock text`; page vectors embed `title; aliases`), `store_embeddings`
saves `(pending, vector)` pairs, `embed_pending` is the loop for a given `&dyn Embedder`.
Blocks are stale when `updated_at` changes; deleted blocks/pages lose vectors on `sync`.
## Hybrid
`hybrid_search` / `hybrid_with_vector`: reciprocal rank fusion (k = 60) of full-text and vector
rankings. `Filter`: scope (all/pages/blocks), journals (any/only/exclude), date range (journal
date, else last-edit day), single page. Journal/date filters on vectors are applied after the
scan (over-fetched ×5).
## Auto-link suggestions
- `LinkMatcher` (Aho-Corasick over `all_titles()`): word-bounded, longest match, case-insensitive,
skips code spans/fences, `[[links]]`, `((refs))`, `#tags`, `[md](links)`, URLs, `{{macros}}` and
property lines; titles under 3 chars are ignored. `Search::unlinked_references(page)` finds
candidate blocks through a tantivy phrase query, then verifies with the matcher.
- `Search::semantic_suggestions(block)`: nearest page-title vectors not already linked.
- `Suggestion { block, span, matched, target_page, score, reason }`; `apply_suggestion` rewrites
the span to `[[Title]]` via `Graph::update_block` (semantic ones append ` [[Title]]`) and
returns `Error::Stale` if the block changed.
## Benchmark
`cargo run --release -p synapse-search --example bench -- 100000`