gqls/semantic/mod.rs
1//! Semantic (embedding) search over schema records.
2//!
3//! Embeds `path + description + type` per record and the query with a local
4//! `all-MiniLM-L6-v2` model (pipeline borrowed from ae), compresses to 64-d
5//! Matryoshka vectors, and ranks by cosine. Falls back to a deterministic hash
6//! embedder when the model can't be fetched, so it always runs.
7//!
8//! v0 embeds every record per invocation (fine at schema scale). A persistent
9//! embedding cache keyed by schema hash — like ae's SQLite store — is the
10//! follow-up for very large / federated schemas; the embed and rank steps are
11//! kept separable here so that cache drops in cleanly.
12
13mod cache;
14mod embed;
15mod mrl;
16
17use crate::model::{Kind, SchemaRecord};
18use embed::{default_embedder, Embedder};
19use mrl::{compress_matryoshka_vector, cosine_similarity};
20
21/// Drop hits below this fraction of the top cosine. Deliberately mild:
22/// measured cosine curves decay smoothly (no tiers, no cliff), and near the
23/// noise floor relevant and irrelevant records interleave — so this bounds
24/// the deep tail (`-l 500` returning 500 rows of monotonic noise), it does
25/// not judge relevance.
26const TAIL_CUTOFF: f64 = 0.7;
27
28/// Apply [`TAIL_CUTOFF`] relative to the best hit. Skipped when the top score
29/// isn't positive — a floor computed from a negative top would drop even the
30/// top itself.
31fn bound_tail<T>(hits: &mut Vec<(f64, T)>) {
32 let Some(top) = hits.first().map(|h| h.0).filter(|t| *t > 0.0) else {
33 return;
34 };
35 let floor = top * TAIL_CUTOFF;
36 hits.retain(|(s, _)| *s >= floor);
37}
38
39/// Embed the query and each record, rank by cosine. Returns `(score, record)`
40/// pairs, best first — the caller formats them exactly like fuzzy hits, so
41/// `--json` / `--ndjson` work identically in both modes.
42///
43/// The model load is deliberately synchronous, not overlapped on a thread:
44/// ONNX Runtime's C++ one-time init segfaults if the process exits mid-load
45/// (a thread dropped on a fuzzy-only exit), and joining always would erase
46/// the overlap. The exact-match skip in the CLI avoids the cost where it
47/// matters instead.
48pub fn search<'a>(
49 query: &str,
50 records: &'a [SchemaRecord],
51 kind: Option<Kind>,
52 parent: Option<&str>,
53 limit: usize,
54 model: Option<&str>,
55 refresh: bool,
56) -> Vec<(f64, &'a SchemaRecord)> {
57 let embedder = default_embedder(model);
58 // On the good path (onnx) this is verbose-only noise; a fall back to the
59 // hash embedder means weaker results, so surface that unconditionally.
60 if embedder.kind() == "onnx" {
61 crate::detail!("semantic search via onnx embeddings");
62 } else {
63 crate::status!(
64 "embedding model unavailable — semantic results will be weaker (-v for why)"
65 );
66 }
67
68 // Per-record vectors are the expensive part; cache them keyed by schema
69 // content + embedder + model, so editing the schema (or switching model)
70 // changes the key and re-embeds automatically. `--refresh` forces a miss.
71 let cache_path = cache::path(records, embedder.kind(), model);
72 let cached = if refresh {
73 None
74 } else {
75 cache_path
76 .as_deref()
77 .and_then(|p| cache::load(p, records.len()))
78 };
79 let vectors = match cached {
80 Some(v) => {
81 if let Some(p) = cache_path.as_deref() {
82 crate::detail!("vector cache hit: {}", crate::paths::display(p));
83 cache::touch(p); // LRU: mark this schema as recently used
84 }
85 v
86 }
87 None => {
88 if let Some(p) = cache_path.as_deref() {
89 crate::detail!("vector cache miss: {}", crate::paths::display(p));
90 }
91 use rayon::prelude::*;
92 use std::io::IsTerminal;
93 use std::sync::atomic::{AtomicUsize, Ordering};
94
95 let total = records.len();
96 crate::status!("embedding {total} records (one-time; may take a minute)…");
97 let done = AtomicUsize::new(0);
98
99 // One embedder per worker thread, built on first use and reused for
100 // every record that thread handles. rayon's `map_init` rebuilt it per
101 // job-split (≈ once per record), reloading the ONNX session tens of
102 // thousands of times on a large schema; a `thread_local` caps it at
103 // one per worker. `model` is constant for the process, so the workers
104 // all resolve the same embedder kind (no mixed onnx/hash vectors), and
105 // caching on "already built?" alone is safe. Order-preserving
106 // `collect` keeps vectors index-aligned with `records`.
107 use std::cell::RefCell;
108 thread_local! {
109 static EMBEDDER: RefCell<Option<Box<dyn Embedder>>> = const { RefCell::new(None) };
110 }
111 let v: Vec<Vec<f32>> = std::thread::scope(|scope| {
112 let show_progress =
113 std::io::stderr().is_terminal() && total > 500 && !crate::logging::is_quiet();
114 if show_progress {
115 scope.spawn(|| loop {
116 std::thread::sleep(std::time::Duration::from_millis(300));
117 let d = done.load(Ordering::Relaxed);
118 eprint!("\rgqls: embedded {d}/{total}… ");
119 if d >= total {
120 eprintln!();
121 break;
122 }
123 });
124 }
125 records
126 .par_iter()
127 .map(|r| {
128 let out = EMBEDDER.with(|cell| {
129 let mut slot = cell.borrow_mut();
130 let emb = slot.get_or_insert_with(|| default_embedder(model));
131 compress_matryoshka_vector(&emb.embed(&record_text(r)))
132 });
133 done.fetch_add(1, Ordering::Relaxed);
134 out
135 })
136 .collect()
137 });
138 if let Some(p) = cache_path.as_deref() {
139 cache::store(p, &v);
140 cache::prune(cache::max_files()); // evict least-recently-used
141 }
142 v
143 }
144 };
145
146 // warm() calls with an empty query and limit 0 purely to populate the cache
147 // above — there's nothing to rank, so skip the query embed + cosine pass.
148 if query.is_empty() && limit == 0 {
149 return Vec::new();
150 }
151
152 let query_vec = compress_matryoshka_vector(&embedder.embed(query));
153 let mut hits: Vec<(f64, &SchemaRecord)> = records
154 .iter()
155 .zip(&vectors)
156 .filter(|(r, _)| kind.is_none_or(|k| r.kind == k))
157 .filter(|(r, _)| {
158 parent.is_none_or(|p| {
159 r.parent
160 .as_deref()
161 .is_some_and(|rp| rp.eq_ignore_ascii_case(p))
162 })
163 })
164 .map(|(r, v)| (cosine_similarity(&query_vec, v) as f64, r))
165 .collect();
166
167 hits.sort_by(|a, b| b.0.total_cmp(&a.0));
168 bound_tail(&mut hits);
169 hits.truncate(limit);
170 hits
171}
172
173/// The natural-language signal a semantic query matches against: the path plus
174/// the human description and the type.
175fn record_text(r: &SchemaRecord) -> String {
176 let mut s = r.path.clone();
177 if let Some(d) = &r.description {
178 s.push_str(" — ");
179 s.push_str(d);
180 }
181 if let Some(t) = &r.type_ref {
182 s.push_str(" : ");
183 s.push_str(t);
184 }
185 s
186}
187
188/// Delete all cached embedding vector files; returns how many were removed.
189pub fn clear_cache() -> usize {
190 cache::clear()
191}
192
193/// Whether the schema's real (ONNX) vectors are cached, so the default combine
194/// path can run without a foreground embed. Deliberately ignores hash-fallback
195/// vectors: a run re-selects the embedder and keys the cache on *its* kind, so
196/// treating a stale `hash` cache as "warm" while the run picks `onnx` would
197/// trigger exactly the surprise foreground embed this gate exists to avoid.
198/// Checked without loading a model.
199pub fn is_cached(records: &[SchemaRecord], model: Option<&str>) -> bool {
200 cache::exists(records, "onnx", model)
201}
202
203/// Embed + cache every record's vector without running a real query — pre-warms
204/// the cache so the first search is instant. Returns the record count.
205pub fn warm(records: &[SchemaRecord], model: Option<&str>, refresh: bool) -> usize {
206 let _ = search("", records, None, None, 0, model, refresh);
207 records.len()
208}
209
210#[cfg(test)]
211mod tests {
212 use super::bound_tail;
213
214 #[test]
215 fn bounds_the_weak_tail_relative_to_the_top() {
216 let mut hits = vec![(1.0, "a"), (0.8, "b"), (0.6, "c")];
217 bound_tail(&mut hits);
218 assert_eq!(hits.len(), 2);
219 }
220
221 #[test]
222 fn keeps_everything_when_the_top_is_not_positive() {
223 let mut hits = vec![(-0.1, "a"), (-0.5, "b")];
224 bound_tail(&mut hits);
225 assert_eq!(hits.len(), 2);
226 }
227}