Skip to main content

datumesh_store/
catalogue.rs

1//! The catalogue (0.5.0): entries that describe functions and classes, dictionaries of key
2//! values, embeddings of their text (PostgreSQL with the `vector` extension) and the log of
3//! find misses. This module is what both backends share: the types, the bounds, the text
4//! search's matching and scores, and the canonical JSON of the stored columns. The SQL is in
5//! `pg.rs` and `sqlite.rs`.
6//!
7//! Text search ([`Store::text_find`](crate::Store::text_find)): the query is split on white
8//! space, each word (lower-cased) must be found in the entry or value, in any of its fields;
9//! a word is found in a field as the whole field (score 1.0), as one of the field's words
10//! (0.8) or inside it (0.5). An entry's score is the mean over the words of the best field's
11//! score, so it lies in (0, 1]. Words match literally (`%`, `_` and `\` are characters).
12//! The backends prefilter rows in SQL with LIKE and rank them here, so both give the same
13//! answers (see [`Words::pattern`] for the words the SQL cannot match exactly).
14
15use std::collections::BTreeMap;
16
17use datumesh_core::json;
18use datumesh_core::lexical::{check_function_name, check_hex, check_name};
19use datumesh_core::{Error as CoreError, ErrorCode};
20
21use crate::error::{Error, Result};
22
23/// The most rows `find_misses` keeps; the oldest are pruned.
24pub const FIND_MISSES_CAP: usize = 100_000;
25
26/// Bytes of a find miss's query text kept (cut on a character boundary).
27pub(crate) const MISS_BYTES: usize = 512;
28
29/// The dimension of the embeddings (`intfloat/multilingual-e5-small`).
30pub(crate) const EMBED_DIM: usize = 384;
31
32/// The most values of a dictionary a summary shows.
33pub(crate) const SUMMARY_VALUES: usize = 50;
34
35/// The kind of a catalogue entry.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub enum CatalogKind {
38    /// A class.
39    Class,
40    /// A method of a class (a function named `<class name>/<method>`).
41    Method,
42    /// A function.
43    Function,
44}
45
46impl CatalogKind {
47    /// The name the store keeps: `class`, `method` or `function`.
48    pub fn as_str(self) -> &'static str {
49        match self {
50            CatalogKind::Class => "class",
51            CatalogKind::Method => "method",
52            CatalogKind::Function => "function",
53        }
54    }
55
56    pub(crate) fn parse(s: &str) -> Option<CatalogKind> {
57        Some(match s {
58            "class" => CatalogKind::Class,
59            "method" => CatalogKind::Method,
60            "function" => CatalogKind::Function,
61            _ => return None,
62        })
63    }
64}
65
66/// Who published an entry: the publisher (its signed document) or the operator (a local
67/// file). An operator's entry never replaces a publisher's.
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
69pub enum CatalogSource {
70    /// The publisher's own text.
71    Publisher,
72    /// The operator's text.
73    Operator,
74}
75
76impl CatalogSource {
77    /// `publisher` or `operator`.
78    pub fn as_str(self) -> &'static str {
79        match self {
80            CatalogSource::Publisher => "publisher",
81            CatalogSource::Operator => "operator",
82        }
83    }
84
85    pub(crate) fn parse(s: &str) -> Option<CatalogSource> {
86        Some(match s {
87            "publisher" => CatalogSource::Publisher,
88            "operator" => CatalogSource::Operator,
89            _ => return None,
90        })
91    }
92}
93
94/// A catalogue entry, keyed by (kind, name).
95///
96/// `label` is at most 120 bytes (it may be empty), `description` 1 to 1024 bytes; `args` maps
97/// each argument's name to its text; `examples` is a JSON array (kept in canonical form).
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct CatalogEntry {
100    /// Class, method or function.
101    pub kind: CatalogKind,
102    /// The full name (SPEC 2.3).
103    pub name: String,
104    /// The function hash (a function) or the class hash (a class), when it has one.
105    pub hash: Option<String>,
106    /// A short human label.
107    pub label: String,
108    /// What it does, in words.
109    pub description: String,
110    /// The text of each argument, by name.
111    pub args: BTreeMap<String, String>,
112    /// A JSON array of `{call, expected}` examples.
113    pub examples: String,
114    /// Who published it.
115    pub source: CatalogSource,
116    /// The key reference of the signer, when signed.
117    pub signed_by: Option<String>,
118}
119
120/// One value of a dictionary: its label and aliases (the publisher's dictionary only).
121#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct KeyValue {
123    /// The canonical lexical form of the value (as a cell argument has it).
124    pub value: String,
125    /// Its human text, for example `2 Chronicles` for `2Chr`; may be empty.
126    pub label: String,
127    /// Other words for it (`1Mo` for `Gen`).
128    pub aliases: Vec<String>,
129}
130
131/// What an embedding is of: a catalogue entry or a dictionary value.
132#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
133pub enum EmbedRef {
134    /// A catalogue entry (its id is the entry's id).
135    Entry,
136    /// A dictionary value (its id is the value's id).
137    Value,
138}
139
140impl EmbedRef {
141    /// `entry` or `value`.
142    pub fn as_str(self) -> &'static str {
143        match self {
144            EmbedRef::Entry => "entry",
145            EmbedRef::Value => "value",
146        }
147    }
148}
149
150/// An embedding of an entry or a value, for one model.
151#[derive(Clone, Debug, PartialEq)]
152pub struct Embedding {
153    /// What it is of.
154    pub ref_kind: EmbedRef,
155    /// The id of the entry or value.
156    pub ref_id: i64,
157    /// 384 finite values, not all zero (normalised by the caller, when cosine is the measure).
158    pub vec: Vec<f32>,
159}
160
161/// An entry or value with no embedding for a model, and the text to embed.
162#[non_exhaustive]
163#[derive(Clone, Debug, PartialEq, Eq)]
164pub struct PendingEmbedding {
165    /// Entry or value.
166    pub ref_kind: EmbedRef,
167    /// Its id.
168    pub ref_id: i64,
169    /// The text: `<label>. <description>` for an entry (the description alone when the label
170    /// is empty), the label for a value (the value when the label is empty).
171    pub text: String,
172}
173
174/// A text-search hit: an entry, or a dictionary value.
175#[non_exhaustive]
176#[derive(Clone, Debug, PartialEq)]
177pub enum Hit {
178    /// A catalogue entry.
179    Entry {
180        /// Its id.
181        id: i64,
182        /// The entry.
183        entry: CatalogEntry,
184        /// How well it matches, in (0, 1] for text and [-1, 1] for vectors (cosine).
185        score: f64,
186    },
187    /// A dictionary value.
188    Value {
189        /// Its id.
190        id: i64,
191        /// The owner (a function or class name).
192        owner: String,
193        /// The key.
194        key: String,
195        /// The canonical lexical form of the value.
196        value: String,
197        /// Its label (may be empty).
198        label: String,
199        /// Its aliases.
200        aliases: Vec<String>,
201        /// How well it matches (as for entries).
202        score: f64,
203    },
204}
205
206/// The catalogue as an operator sees it ([`Store::catalog_summary`](crate::Store::catalog_summary)).
207#[non_exhaustive]
208#[derive(Clone, Debug, PartialEq, Eq)]
209pub struct Summary {
210    /// Every entry, by kind then name.
211    pub entries: Vec<SummaryEntry>,
212    /// Every dictionary, by owner then key.
213    pub dictionaries: Vec<Dictionary>,
214}
215
216/// An entry of a [`Summary`].
217#[non_exhaustive]
218#[derive(Clone, Debug, PartialEq, Eq)]
219pub struct SummaryEntry {
220    /// Class, method or function.
221    pub kind: CatalogKind,
222    /// The full name.
223    pub name: String,
224    /// Its label.
225    pub label: String,
226    /// The cells of the function that are stored (0 for a class or a method).
227    pub n_cells: i64,
228}
229
230/// A dictionary of a [`Summary`]: the values of one key of one owner.
231#[non_exhaustive]
232#[derive(Clone, Debug, PartialEq, Eq)]
233pub struct Dictionary {
234    /// The owner: a function or class name.
235    pub owner: String,
236    /// The key.
237    pub key: String,
238    /// How many values the dictionary has.
239    pub n_values: i64,
240    /// Its first values by value, at most 50.
241    pub values: Vec<DictionaryValue>,
242}
243
244/// A value of a [`Dictionary`].
245#[non_exhaustive]
246#[derive(Clone, Debug, PartialEq, Eq)]
247pub struct DictionaryValue {
248    /// The canonical lexical form.
249    pub value: String,
250    /// Its label.
251    pub label: String,
252    /// The cells of the owner's function that have this value for the key (refreshed by
253    /// `refresh_value_counts`).
254    pub n_cells: i64,
255}
256
257// ---- Validation -------------------------------------------------------------------------
258
259pub(crate) fn invalid(path: &str, detail: impl Into<String>) -> Error {
260    Error::Invalid(CoreError::new(ErrorCode::Schema, path, detail))
261}
262
263/// A catalogue entry's bounds and forms (the store refuses an entry that breaks them).
264pub(crate) fn check_catalog_entry(e: &CatalogEntry) -> Result<()> {
265    check_function_name(&e.name, "name")?;
266    if let Some(h) = &e.hash {
267        check_hex(h, 64, "hash")?;
268    }
269    if e.label.len() > 120 {
270        return Err(invalid("label", "a label has at most 120 bytes"));
271    }
272    if e.description.is_empty() || e.description.len() > 1024 {
273        return Err(invalid("description", "a description has 1 to 1024 bytes"));
274    }
275    for (k, v) in &e.args {
276        check_name(k, "args")?;
277        if v.len() > 1024 {
278            return Err(invalid("args", "an argument's text has at most 1024 bytes"));
279        }
280    }
281    if args_json(&e.args).len() > 65536 {
282        return Err(invalid("args", "the arguments have at most 65536 bytes of JSON"));
283    }
284    let examples = canonical_examples(&e.examples)?;
285    if examples.len() > 65536 {
286        return Err(invalid("examples", "the examples have at most 65536 bytes of JSON"));
287    }
288    if let Some(s) = &e.signed_by {
289        if s.is_empty() || s.len() > 256 {
290            return Err(invalid("signed_by", "a key reference has 1 to 256 bytes"));
291        }
292    }
293    Ok(())
294}
295
296/// A dictionary's bounds (owner, key, values, labels, aliases).
297pub(crate) fn check_key_values(owner: &str, key: &str, values: &[KeyValue]) -> Result<()> {
298    check_function_name(owner, "owner")?;
299    check_name(key, "key")?;
300    for v in values {
301        if v.value.is_empty() || v.value.len() > 1024 {
302            return Err(invalid("value", "a value has 1 to 1024 bytes"));
303        }
304        if v.label.len() > 120 {
305            return Err(invalid("label", "a label has at most 120 bytes"));
306        }
307        for a in &v.aliases {
308            if a.is_empty() || a.len() > 120 {
309                return Err(invalid("aliases", "an alias has 1 to 120 bytes"));
310            }
311        }
312    }
313    Ok(())
314}
315
316pub(crate) fn check_model(model: &str) -> Result<()> {
317    if model.is_empty() || model.len() > 200 {
318        return Err(invalid("model", "a model name has 1 to 200 bytes"));
319    }
320    Ok(())
321}
322
323/// A vector's form for `vector`: 384 finite values, not all zero. Its text literal.
324pub(crate) fn vector_literal(v: &[f32]) -> Result<String> {
325    if v.len() != EMBED_DIM {
326        return Err(invalid("vec", format!("a vector has {EMBED_DIM} values, not {}", v.len())));
327    }
328    if v.iter().any(|x| !x.is_finite()) {
329        return Err(invalid("vec", "a vector's values are finite"));
330    }
331    if v.iter().all(|x| *x == 0.0) {
332        return Err(invalid("vec", "a vector is not all zero"));
333    }
334    let parts: Vec<String> = v.iter().map(|x| x.to_string()).collect();
335    Ok(format!("[{}]", parts.join(",")))
336}
337
338/// The text of a find miss as stored: trimmed, cut to 512 bytes on a character boundary;
339/// `None` when nothing is left.
340pub(crate) fn miss_text(query: &str) -> Option<&str> {
341    let q = query.trim();
342    if q.is_empty() {
343        return None;
344    }
345    let mut end = 0;
346    for (i, c) in q.char_indices() {
347        if i + c.len_utf8() > MISS_BYTES {
348            break;
349        }
350        end = i + c.len_utf8();
351    }
352    Some(&q[..end])
353}
354
355// ---- Canonical JSON of the stored columns -----------------------------------------------
356
357/// The arguments as canonical JSON (an object of strings).
358pub(crate) fn args_json(args: &BTreeMap<String, String>) -> String {
359    let members: Vec<(String, json::Value)> =
360        args.iter().map(|(k, v)| (k.clone(), json::Value::String(v.clone()))).collect();
361    String::from_utf8(json::Value::Object(members).to_jcs()).unwrap_or_default()
362}
363
364/// The arguments from their stored JSON.
365pub(crate) fn parse_args(text: &str) -> Result<BTreeMap<String, String>> {
366    let v = json::parse(text.as_bytes())?;
367    let members = v.as_object().ok_or_else(|| invalid("args", "stored arguments are not an object"))?;
368    let mut out = BTreeMap::new();
369    for (k, v) in members {
370        let s = v.as_str().ok_or_else(|| invalid("args", "stored argument text is not a string"))?;
371        out.insert(k.clone(), s.to_string());
372    }
373    Ok(out)
374}
375
376/// The examples in canonical form; they must be a JSON array.
377pub(crate) fn canonical_examples(text: &str) -> Result<String> {
378    let v = json::parse(text.as_bytes())?;
379    if !matches!(v, json::Value::Array(_)) {
380        return Err(invalid("examples", "examples are a JSON array"));
381    }
382    Ok(String::from_utf8(v.to_jcs()).unwrap_or_default())
383}
384
385/// The aliases as canonical JSON (an array of strings), for SQLite.
386#[cfg(feature = "sqlite")]
387pub(crate) fn aliases_json(aliases: &[String]) -> String {
388    let items: Vec<json::Value> = aliases.iter().map(|a| json::Value::String(a.clone())).collect();
389    String::from_utf8(json::Value::Array(items).to_jcs()).unwrap_or_default()
390}
391
392/// The aliases from their stored JSON, for SQLite.
393#[cfg(feature = "sqlite")]
394pub(crate) fn parse_aliases(text: &str) -> Result<Vec<String>> {
395    let v = json::parse(text.as_bytes())?;
396    let items = match &v {
397        json::Value::Array(items) => items,
398        _ => return Err(invalid("aliases", "stored aliases are not an array")),
399    };
400    items
401        .iter()
402        .map(|i| i.as_str().map(str::to_string).ok_or_else(|| invalid("aliases", "a stored alias is not a string")))
403        .collect()
404}
405
406/// An entry from its stored columns.
407#[allow(clippy::too_many_arguments)]
408pub(crate) fn entry_from_columns(
409    kind: &str,
410    name: String,
411    hash: Option<String>,
412    label: String,
413    description: String,
414    args: &str,
415    examples: &str,
416    source: &str,
417    signed_by: Option<String>,
418) -> Result<CatalogEntry> {
419    let corrupt = |what: &str| invalid("catalog", format!("a stored entry has a bad {what}"));
420    Ok(CatalogEntry {
421        kind: CatalogKind::parse(kind).ok_or_else(|| corrupt("kind"))?,
422        name,
423        hash,
424        label,
425        description,
426        args: parse_args(args)?,
427        examples: examples.to_string(),
428        source: CatalogSource::parse(source).ok_or_else(|| corrupt("source"))?,
429        signed_by,
430    })
431}
432
433// ---- The text of embeddings -------------------------------------------------------------
434
435/// The text of an entry to embed.
436pub(crate) fn entry_text(label: &str, description: &str) -> String {
437    if label.is_empty() {
438        description.to_string()
439    } else {
440        format!("{label}. {description}")
441    }
442}
443
444/// The text of a value to embed.
445pub(crate) fn value_text(label: &str, value: &str) -> String {
446    if label.is_empty() {
447        value.to_string()
448    } else {
449        label.to_string()
450    }
451}
452
453// ---- Text search -----------------------------------------------------------------------
454
455/// The words of a text query, lower-cased; `None` when there are none (a blank query finds
456/// nothing).
457pub(crate) struct Words {
458    words: Vec<String>,
459}
460
461impl Words {
462    pub(crate) fn new(query: &str) -> Option<Words> {
463        let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
464        if words.is_empty() {
465            None
466        } else {
467            Some(Words { words })
468        }
469    }
470
471    /// The LIKE pattern of word `i` for an SQL prefilter, or `None` when the SQL cannot
472    /// match it exactly, and the rows are read and matched here instead. `sql_exact` says
473    /// whether a word is safe for the backend's LIKE: no `"` or `\` (JSON text escapes them),
474    /// no control characters, and (SQLite, whose LIKE folds ASCII only) ASCII letters only.
475    pub(crate) fn pattern(&self, i: usize, sql_exact: impl Fn(&str) -> bool) -> Option<String> {
476        let w = &self.words[i];
477        if !sql_exact(w) {
478            return None;
479        }
480        let mut escaped = String::with_capacity(w.len() + 2);
481        escaped.push('%');
482        for c in w.chars() {
483            if matches!(c, '!' | '%' | '_') {
484                escaped.push('!');
485            }
486            escaped.push(c);
487        }
488        escaped.push('%');
489        Some(escaped)
490    }
491
492    pub(crate) fn len(&self) -> usize {
493        self.words.len()
494    }
495
496    /// The score of a row with these fields, or `None` when a word is in none of them.
497    pub(crate) fn score(&self, fields: &[&str]) -> Option<f64> {
498        let fields: Vec<String> = fields.iter().map(|f| f.to_lowercase()).collect();
499        let mut total = 0.0;
500        for w in &self.words {
501            let best = fields.iter().map(|f| field_score(f, w)).fold(0.0_f64, f64::max);
502            if best == 0.0 {
503                return None;
504            }
505            total += best;
506        }
507        Some(total / self.words.len() as f64)
508    }
509}
510
511/// How well a lower-cased field matches a lower-cased word: the whole field, one of its words
512/// (split on anything but letters and digits), inside it, or not at all.
513fn field_score(field: &str, word: &str) -> f64 {
514    if field == word {
515        1.0
516    } else if field.split(|c: char| !c.is_alphanumeric()).any(|p| p == word) {
517        0.8
518    } else if field.contains(word) {
519        0.5
520    } else {
521        0.0
522    }
523}
524
525/// The fields of an entry the text search matches.
526pub(crate) fn entry_fields(e: &CatalogEntry) -> Vec<&str> {
527    let mut f = vec![e.name.as_str(), e.label.as_str(), e.description.as_str()];
528    for (k, v) in &e.args {
529        f.push(k);
530        f.push(v);
531    }
532    f
533}
534
535/// Hits in rank order: by score (highest first), then by name (entries) or owner, key and
536/// value (values), so equal scores always come in the same order; at most `limit`.
537pub(crate) fn rank(mut hits: Vec<Hit>, limit: usize) -> Vec<Hit> {
538    fn key(h: &Hit) -> String {
539        match h {
540            Hit::Entry { entry, .. } => entry.name.clone(),
541            Hit::Value { owner, key, value, .. } => format!("{owner}\u{1}{key}\u{1}{value}"),
542        }
543    }
544    fn score(h: &Hit) -> f64 {
545        match h {
546            Hit::Entry { score, .. } | Hit::Value { score, .. } => *score,
547        }
548    }
549    hits.sort_by(|a, b| {
550        score(b).partial_cmp(&score(a)).unwrap_or(std::cmp::Ordering::Equal).then_with(|| key(a).cmp(&key(b)))
551    });
552    hits.truncate(limit);
553    hits
554}
555
556/// A count or limit as the database's integer.
557pub(crate) fn as_i64(n: usize) -> i64 {
558    i64::try_from(n).unwrap_or(i64::MAX)
559}