diff --git a/Cargo.lock b/Cargo.lock index 4da5ab4..53da62b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,21 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + [[package]] name = "android_system_properties" version = "0.1.6" @@ -11,24 +26,59 @@ dependencies = [ "libc", ] +[[package]] +name = "arc-swap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" +dependencies = [ + "rustversion", +] + [[package]] name = "arrayvec" version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "bitpacking" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96a7139abd3d9cebf8cd6f920a389cf3dc9576172e32f4563f188cae3c3eb019" +dependencies = [ + "crunchy", +] + [[package]] name = "blake3" version = "1.8.7" @@ -42,12 +92,41 @@ dependencies = [ "cpufeatures", ] +[[package]] +name = "bon" +version = "3.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "214f5df094ce551a10a30ffb9c70243d61f121a3d985a6495933e181dee6a7d2" +dependencies = [ + "bon-macros", +] + +[[package]] +name = "bon-macros" +version = "3.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2706da6c749998cc555d04184909608956a69ad3f8ab1a076fbc867b4a3c3ce5" +dependencies = [ + "darling", + "ident_case", + "prettyplease", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "bumpalo" version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "cc" version = "1.9.0" @@ -58,6 +137,12 @@ dependencies = [ "shlex", ] +[[package]] +name = "census" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f4c707c6a209cbe82d10abd08e1ea8995e9ea937d2550646e02798948992be0" + [[package]] name = "cfg-if" version = "1.0.5" @@ -97,6 +182,116 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.9", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "downcast-rs" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" version = "0.3.14" @@ -104,7 +299,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -119,6 +314,12 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" +[[package]] +name = "fastdivide" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afc2bd4d5a73106dd53d10d73d3401c2f32730ba2c0b93ddb888a8983680471" + [[package]] name = "fastrand" version = "2.5.0" @@ -131,18 +332,45 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +[[package]] +name = "fs4" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4" +dependencies = [ + "rustix", + "windows-sys 0.59.0", +] + [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "futures-task" version = "0.3.34" @@ -156,11 +384,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-macro", "futures-task", "pin-project-lite", "slab", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -178,6 +418,8 @@ version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ + "allocator-api2", + "equivalent", "foldhash", ] @@ -190,6 +432,21 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "htmlescape" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9025058dae765dee5070ec375f591e2ba14638c63feff74f13805a72e523163" + +[[package]] +name = "hyperloglogplus" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "621debdf94dcac33e50475fdd76d34d5ea9c0362a834b9db08c3024696c1fbe3" +dependencies = [ + "serde", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -214,6 +471,21 @@ dependencies = [ "cc", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -231,12 +503,24 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "levenshtein_automata" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c2cdeb66e45e9f36bfad5bbdb4d2384e70936afbee843c6f6543f0c551ebb25" + [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libsqlite3-sys" version = "0.35.0" @@ -260,12 +544,73 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "lru" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "lz4_flex" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a" + +[[package]] +name = "measure_time" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51c55d61e72fc3ab704396c5fa16f4c184db37978ae4e94ca8959693a235fc0e" +dependencies = [ + "log", +] + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "murmurhash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-traits" version = "0.2.19" @@ -273,6 +618,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -281,6 +627,21 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "oneshot" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "269bca4c2591a28585d6bf10d9ed0332b7d76900a1b02bec41bdc3a2cdcda107" + +[[package]] +name = "ownedbytes" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fbd56f7631767e61784dc43f8580f403f4475bd4aaa4da003e6295e1bab4a7e" +dependencies = [ + "stable_deref_trait", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -293,6 +654,31 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn 3.0.9", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -317,6 +703,95 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_distr" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" +dependencies = [ + "num-traits", + "rand", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "rusqlite" version = "0.37.0" @@ -331,6 +806,22 @@ dependencies = [ "smallvec", ] +[[package]] +name = "rust-stemmers" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e46a2036019fdb888131db7a4c847a1063a7493f971ed94ea82c67eada63ca54" +dependencies = [ + "serde", + "serde_derive", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustix" version = "1.1.5" @@ -341,7 +832,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -405,6 +896,15 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "sketches-ddsketch" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6f73aeb92d671e0cc4dca167e59b2deb6387c375391bc99ee743f326994a2b" +dependencies = [ + "serde", +] + [[package]] name = "slab" version = "0.4.12" @@ -417,6 +917,18 @@ version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "syn" version = "2.0.119" @@ -453,6 +965,165 @@ dependencies = [ "uuid", ] +[[package]] +name = "synapse-search" +version = "0.1.0" +dependencies = [ + "aho-corasick", + "chrono", + "rusqlite", + "synapse-core", + "tantivy", + "tempfile", + "thiserror", + "uuid", +] + +[[package]] +name = "tantivy" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502915c7381c5cb2d2781503962610cb880ad8f1a0ca95df1bae645d5ebf2545" +dependencies = [ + "aho-corasick", + "arc-swap", + "base64", + "bitpacking", + "bon", + "byteorder", + "census", + "crc32fast", + "crossbeam-channel", + "downcast-rs", + "fastdivide", + "fnv", + "fs4", + "htmlescape", + "hyperloglogplus", + "itertools", + "levenshtein_automata", + "log", + "lru", + "lz4_flex", + "measure_time", + "memmap2", + "once_cell", + "oneshot", + "rayon", + "regex", + "rust-stemmers", + "rustc-hash", + "serde", + "serde_json", + "sketches-ddsketch", + "smallvec", + "tantivy-bitpacker", + "tantivy-columnar", + "tantivy-common", + "tantivy-fst", + "tantivy-query-grammar", + "tantivy-stacker", + "tantivy-tokenizer-api", + "tempfile", + "thiserror", + "time", + "uuid", + "winapi", +] + +[[package]] +name = "tantivy-bitpacker" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b04eed5108d8283607da6710fe17a7663523440eaf7ea5a1a440d19a1448b6" +dependencies = [ + "bitpacking", +] + +[[package]] +name = "tantivy-columnar" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b628488ae936c83e92b5c4056833054ca56f76c0e616aee8339e24ac89119cd" +dependencies = [ + "downcast-rs", + "fastdivide", + "itertools", + "serde", + "tantivy-bitpacker", + "tantivy-common", + "tantivy-sstable", + "tantivy-stacker", +] + +[[package]] +name = "tantivy-common" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f880aa7cab0c063a47b62596d10991cdd0b6e0e0575d9c5eeb298b307a25de55" +dependencies = [ + "async-trait", + "byteorder", + "ownedbytes", + "serde", + "time", +] + +[[package]] +name = "tantivy-fst" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d60769b80ad7953d8a7b2c70cdfe722bbcdcac6bccc8ac934c40c034d866fc18" +dependencies = [ + "byteorder", + "regex-syntax", + "utf8-ranges", +] + +[[package]] +name = "tantivy-query-grammar" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "768fccdc84d60d86235d42d7e4c33acf43c418258ff5952abf07bd7837fcd26b" +dependencies = [ + "nom", + "serde", + "serde_json", +] + +[[package]] +name = "tantivy-sstable" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8292095d1a8a2c2b36380ec455f910ab52dde516af36321af332c93f20ab7d5" +dependencies = [ + "futures-util", + "itertools", + "tantivy-bitpacker", + "tantivy-common", + "tantivy-fst", +] + +[[package]] +name = "tantivy-stacker" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d38a379411169f0b3002c9cba61cdfe315f757e9d4f239c00c282497a0749d" +dependencies = [ + "murmurhash32", + "rand_distr", + "tantivy-common", +] + +[[package]] +name = "tantivy-tokenizer-api" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23024f6aeb25ceb1a0e27740c84bdb0fae52626737b7e9a9de6ad5aa25c7b038" +dependencies = [ + "serde", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -460,10 +1131,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom", + "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -486,19 +1157,55 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "utf8-ranges" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcfc827f90e53a02eaef5e535ee14266c1d569214c6aa70133a624d8a3164ba" + [[package]] name = "uuid" version = "1.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" dependencies = [ - "getrandom", + "getrandom 0.4.3", "js-sys", "serde_core", "sha1_smol", @@ -511,6 +1218,12 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -556,6 +1269,28 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows-core" version = "0.62.2" @@ -615,6 +1350,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -624,6 +1368,90 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/crates/synapse-search/Cargo.toml b/crates/synapse-search/Cargo.toml new file mode 100644 index 0000000..41883a8 --- /dev/null +++ b/crates/synapse-search/Cargo.toml @@ -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" diff --git a/crates/synapse-search/examples/bench.rs b/crates/synapse-search/examples/bench.rs new file mode 100644 index 0000000..82d12a1 --- /dev/null +++ b/crates/synapse-search/examples/bench.rs @@ -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, p: f64) -> Duration { + v.sort(); + v[((v.len() as f64 * p) as usize).min(v.len() - 1)] +} + +fn timed(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 = (0..8000) + .map(|_| { + (0..2 + rng.below(3)) + .map(|_| syll[rng.below(syll.len())]) + .collect::() + + &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 = (0..300) + .map(|_| { + let w = &vocab[rng.below(vocab.len())]; + w.chars().take(2 + rng.below(5)).collect::() + }) + .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(); +} diff --git a/crates/synapse-search/src/autolink.rs b/crates/synapse-search/src/autolink.rs new file mode 100644 index 0000000..25662e5 --- /dev/null +++ b/crates/synapse-search/src/autolink.rs @@ -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>, + /// 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, + patterns: Vec, + min_chars: usize, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Match { + pub span: Range, + 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 { + let aliases: std::collections::HashSet = { + let mut st = graph.conn().prepare("SELECT alias FROM aliases")?; + st.query_map([], |r| r.get::<_, String>(0))? + .collect::>()? + }; + 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 = 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 { + 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 = 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 = 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 { + 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> { + 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 { + 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>) { + 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> { + 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>) { + 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) { + let ids: Vec = 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 { + 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::::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"); + } +} diff --git a/crates/synapse-search/src/error.rs b/crates/synapse-search/src/error.rs new file mode 100644 index 0000000..b232bab --- /dev/null +++ b/crates/synapse-search/src/error.rs @@ -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 = std::result::Result; diff --git a/crates/synapse-search/src/fulltext.rs b/crates/synapse-search/src/fulltext.rs new file mode 100644 index 0000000..9786c38 --- /dev/null +++ b/crates/synapse-search/src/fulltext.rs @@ -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 { + 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 { + 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 { + 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, + ), + ( + 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 { + 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, + ) + }) + .collect(); + ( + occur, + Box::new(BooleanQuery::new(per_field)) as Box, + ) + }) + .collect(); + Box::new(BooleanQuery::new(clauses)) + } + + fn filter_clauses(&self, filter: &Filter) -> Vec<(Occur, Box)> { + let mut c: Vec<(Occur, Box)> = Vec::new(); + let term = |f: Field, v: &str| -> Box { + 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| 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, limit: usize) -> Result> { + 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> { + 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> { + 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, + ), + ( + 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> { + let toks = self.tokens(text); + let q: Box = 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, + ), + (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> { + 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 + } +} diff --git a/crates/synapse-search/src/lib.rs b/crates/synapse-search/src/lib.rs new file mode 100644 index 0000000..f4d7a93 --- /dev/null +++ b/crates/synapse-search/src/lib.rs @@ -0,0 +1,911 @@ +//! Search and auto-link suggestions over a [`synapse_core::Graph`]. +//! +//! * Full-text: tantivy index in `/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, + pub to: Option, + /// Restrict to one page (its blocks, or the page itself). + pub page: Option, +} + +#[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>, +} + +fn state_get(graph: &Graph, key: &str) -> Result> { + 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 `/index/`, creating it if needed. Call [`Search::sync`] + /// afterwards to catch up with the op log. + pub fn open(graph: &Graph) -> Result { + Self::open_with(graph, Config::default()) + } + + pub fn open_with(graph: &Graph, config: Config) -> Result { + 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 { + 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 = HashSet::new(); + let mut pages: HashSet = 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, 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 { + 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> = 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> { + 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> { + 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> { + let mut out = Vec::new(); + // Pages: embed "title; alias; alias". Stale when that text's hash changes. + let mut aliases: HashMap> = 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>(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)], + ) -> 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 = 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 { + 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 = 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>(5)?, + )) + })?; + for r in rows { + let (id, kind, page, stamp, scale, bytes) = r?; + let q: Vec = 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> { + 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> { + 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>> = 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> { + 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> { + 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> { + 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> { + 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 = 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> { + 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 = 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> { + 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 { + Ok(state_get(graph, "last_seq")? + .and_then(|s| s.parse().ok()) + .unwrap_or(0)) +} + +fn parse_uuid(s: &str) -> Result { + Uuid::parse_str(s).map_err(|e| Error::Invalid(e.to_string())) +} + +fn hydrate(graph: &Graph, raw: impl Iterator) -> Result> { + let mut titles: HashMap> = 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) +} diff --git a/crates/synapse-search/src/testing.rs b/crates/synapse-search/src/testing.rs new file mode 100644 index 0000000..c5079b0 --- /dev/null +++ b/crates/synapse-search/src/testing.rs @@ -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 { + 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>, EmbedError> { + Ok(texts.iter().map(|t| self.embed_one(t)).collect()) + } +} diff --git a/crates/synapse-search/src/vectors.rs b/crates/synapse-search/src/vectors.rs new file mode 100644 index 0000000..0f6ba2e --- /dev/null +++ b/crates/synapse-search/src/vectors.rs @@ -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, + pages: Vec, + stamps: Vec, + scales: Vec, + data: Vec, + slot: HashMap, +} + +pub(crate) fn normalize(v: &[f32]) -> Vec { + let n = v.iter().map(|x| x * x).sum::().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, 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> { + 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) -> Vec { + 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 = (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()); + } +} diff --git a/crates/synapse-search/tests/search.rs b/crates/synapse-search/tests/search.rs new file mode 100644 index 0000000..3713515 --- /dev/null +++ b/crates/synapse-search/tests/search.rs @@ -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 + ); +} diff --git a/docs/search.md b/docs/search.md new file mode 100644 index 0000000..152e12c --- /dev/null +++ b/docs/search.md @@ -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 `/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`