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::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 filters: crate::search::Filters<'_>,
52 limit: usize,
53 model: Option<&str>,
54 refresh: bool,
55) -> Vec<(f64, &'a SchemaRecord)> {
56 let embedder = default_embedder(model);
57 // On the good path (onnx) this is verbose-only noise; a fall back to the
58 // hash embedder means weaker results, so surface that unconditionally.
59 if embedder.kind() == "onnx" {
60 crate::detail!("semantic search via onnx embeddings");
61 } else {
62 crate::status!(
63 "embedding model unavailable — semantic results will be weaker (-v for why)"
64 );
65 }
66
67 // Per-record vectors are the expensive part; cache them keyed by schema
68 // content + embedder + model, so editing the schema (or switching model)
69 // changes the key and re-embeds automatically. `--refresh` forces a miss.
70 let cache_path = cache::path(records, embedder.kind(), model);
71 let cached = if refresh {
72 None
73 } else {
74 cache_path
75 .as_deref()
76 .and_then(|p| cache::load(p, records.len()))
77 };
78 let vectors = match cached {
79 Some(v) => {
80 if let Some(p) = cache_path.as_deref() {
81 crate::detail!("vector cache hit: {}", crate::paths::display(p));
82 cache::touch(p); // LRU: mark this schema as recently used
83 }
84 v
85 }
86 None => {
87 if let Some(p) = cache_path.as_deref() {
88 crate::detail!("vector cache miss: {}", crate::paths::display(p));
89 }
90 use rayon::prelude::*;
91 use std::io::IsTerminal;
92 use std::sync::atomic::{AtomicUsize, Ordering};
93
94 let total = records.len();
95 crate::status!("embedding {total} records (one-time; may take a minute)…");
96 let done = AtomicUsize::new(0);
97
98 // One embedder per worker thread, built on first use and reused for
99 // every record that thread handles. rayon's `map_init` rebuilt it per
100 // job-split (≈ once per record), reloading the ONNX session tens of
101 // thousands of times on a large schema; a `thread_local` caps it at
102 // one per worker. `model` is constant for the process, so the workers
103 // all resolve the same embedder kind (no mixed onnx/hash vectors), and
104 // caching on "already built?" alone is safe. Order-preserving
105 // `collect` keeps vectors index-aligned with `records`.
106 use std::cell::RefCell;
107 thread_local! {
108 static EMBEDDER: RefCell<Option<Box<dyn Embedder>>> = const { RefCell::new(None) };
109 }
110 let v: Vec<Vec<f32>> = std::thread::scope(|scope| {
111 let show_progress =
112 std::io::stderr().is_terminal() && total > 500 && !crate::logging::is_quiet();
113 if show_progress {
114 scope.spawn(|| loop {
115 std::thread::sleep(std::time::Duration::from_millis(300));
116 let d = done.load(Ordering::Relaxed);
117 eprint!("\rgqls: embedded {d}/{total}… ");
118 if d >= total {
119 eprintln!();
120 break;
121 }
122 });
123 }
124 records
125 .par_iter()
126 .map(|r| {
127 let out = EMBEDDER.with(|cell| {
128 let mut slot = cell.borrow_mut();
129 let emb = slot.get_or_insert_with(|| default_embedder(model));
130 compress_matryoshka_vector(&emb.embed(&record_text(r)))
131 });
132 done.fetch_add(1, Ordering::Relaxed);
133 out
134 })
135 .collect()
136 });
137 if let Some(p) = cache_path.as_deref() {
138 cache::store(p, &v);
139 cache::prune(cache::max_files()); // evict least-recently-used
140 }
141 v
142 }
143 };
144
145 // warm() calls with an empty query and limit 0 purely to populate the cache
146 // above — there's nothing to rank, so skip the query embed + cosine pass.
147 if query.is_empty() && limit == 0 {
148 return Vec::new();
149 }
150
151 let query_vec = compress_matryoshka_vector(&embedder.embed(query));
152 let predicate = filters.compile();
153 let mut hits: Vec<(f64, &SchemaRecord)> = records
154 .iter()
155 .zip(&vectors)
156 .filter(|(r, _)| predicate.accepts(r))
157 .map(|(r, v)| (cosine_similarity(&query_vec, v) as f64, r))
158 .collect();
159
160 hits.sort_by(|a, b| b.0.total_cmp(&a.0));
161 bound_tail(&mut hits);
162 hits.truncate(limit);
163 hits
164}
165
166/// The natural-language signal a semantic query matches against: the path plus
167/// the human description and the type.
168fn record_text(r: &SchemaRecord) -> String {
169 let mut s = r.path.clone();
170 if let Some(d) = &r.description {
171 s.push_str(" — ");
172 s.push_str(d);
173 }
174 if let Some(t) = &r.type_ref {
175 s.push_str(" : ");
176 s.push_str(t);
177 }
178 s
179}
180
181/// Delete all cached embedding vector files; returns how many were removed.
182pub fn clear_cache() -> usize {
183 cache::clear()
184}
185
186/// Whether the schema's real (ONNX) vectors are cached, so the default combine
187/// path can run without a foreground embed. Deliberately ignores hash-fallback
188/// vectors: a run re-selects the embedder and keys the cache on *its* kind, so
189/// treating a stale `hash` cache as "warm" while the run picks `onnx` would
190/// trigger exactly the surprise foreground embed this gate exists to avoid.
191/// Checked without loading a model.
192pub fn is_cached(records: &[SchemaRecord], model: Option<&str>) -> bool {
193 cache::exists(records, "onnx", model)
194}
195
196/// Embed + cache every record's vector without running a real query — pre-warms
197/// the cache so the first search is instant. Returns the record count.
198pub fn warm(records: &[SchemaRecord], model: Option<&str>, refresh: bool) -> usize {
199 let _ = search("", records, Default::default(), 0, model, refresh);
200 records.len()
201}
202
203#[cfg(test)]
204mod tests {
205 use super::bound_tail;
206
207 #[test]
208 fn bounds_the_weak_tail_relative_to_the_top() {
209 let mut hits = vec![(1.0, "a"), (0.8, "b"), (0.6, "c")];
210 bound_tail(&mut hits);
211 assert_eq!(hits.len(), 2);
212 }
213
214 #[test]
215 fn keeps_everything_when_the_top_is_not_positive() {
216 let mut hits = vec![(-0.1, "a"), (-0.5, "b")];
217 bound_tail(&mut hits);
218 assert_eq!(hits.len(), 2);
219 }
220}