Skip to main content

capsule_core/ml/
index.rs

1//! The vector-index seam — the [`VectorIndex`] port the orchestration and the regeneration loop
2//! write embeddings through, and the value types that cross it (SSoT: [AI/ML — Database
3//! Indexing] + [AI/ML — Embedding Provenance]).
4//!
5//! `capsule-core` is stateless, so the index itself — SQLite plus `sqlite-vec`'s `vec0` tables —
6//! lives in `capsule-library`, which implements this trait for its catalog. Core names only the
7//! questions the ML layer asks of an index: insert a provenanced embedding, rank the nearest
8//! neighbours in the current canonical partition, and list the assets whose stored embedding is
9//! stale. Everything the index needs to answer them about the model inventory reaches it through
10//! the [`EmbeddingProvenance`] gate, implemented by the [`Registry`](crate::ml::Registry).
11//!
12//! [AI/ML — Database Indexing]: https://docs/design/ai/#database-indexing-and-view-generation
13//! [AI/ML — Embedding Provenance]: https://docs/design/ai/#embedding-provenance
14
15use thiserror::Error;
16
17use crate::domain::model_identity::{
18    DistanceMetric, EmbeddingDim, ModelId, ModelVersion, RegistryError, TaskKind,
19};
20
21/// A provenanced embedding to insert into the index: the subject asset, the producing model
22/// `(task, model_id, model_version)`, the `platform` partition discriminator, and the vector.
23#[derive(Debug, Clone, Copy)]
24pub struct EmbeddingInsert<'a> {
25    /// The asset the embedding was produced from.
26    pub asset_id: &'a str,
27    /// The task that produced it.
28    pub task: TaskKind,
29    /// The producing model id.
30    pub model_id: &'a ModelId,
31    /// The producing model version.
32    pub model_version: &'a ModelVersion,
33    /// The platform partition (incomparable across platforms; see the E2EE fallback in `ai.md`).
34    pub platform: &'a str,
35    /// The embedding vector (length must equal the task's registry-declared dimension).
36    pub vector: &'a [f32],
37}
38
39/// A single nearest-neighbour hit.
40#[derive(Debug, Clone, PartialEq)]
41pub struct KnnHit {
42    /// The matched asset id.
43    pub asset_id: String,
44    /// Distance under the task's metric (smaller = nearer; cosine over normalized vectors).
45    pub distance: f64,
46}
47
48/// A stored embedding's provenance (from the companion table; the vector itself stays in `vec0`).
49#[derive(Debug, Clone, PartialEq)]
50pub struct EmbeddingRecord {
51    /// Asset the embedding was produced from.
52    pub asset_id: String,
53    /// Task that produced it.
54    pub task: TaskKind,
55    /// Platform partition discriminator.
56    pub platform: String,
57    /// Producing model.
58    pub model_id: ModelId,
59    /// Producing model version.
60    pub model_version: ModelVersion,
61}
62
63/// Failures from the vector index.
64#[derive(Debug, Error)]
65pub enum VectorIndexError {
66    /// The embedding-provenance invariant rejected the insert (an unknown model or a
67    /// non-embedding task).
68    #[error(transparent)]
69    Registry(#[from] RegistryError),
70    /// The vector's length does not match the task's registry-declared dimension.
71    #[error("embedding dimension mismatch for {task:?}: expected {expected}, got {got}")]
72    DimMismatch {
73        /// The task.
74        task: TaskKind,
75        /// Registry-declared dimension.
76        expected: usize,
77        /// The supplied vector length.
78        got: usize,
79    },
80    /// The index's backing store failed (a SQLite error, for the library's catalog). Type-erased
81    /// so `capsule-core` never names a storage engine.
82    #[error("vector store: {0}")]
83    Store(#[source] Box<dyn std::error::Error + Send + Sync>),
84}
85
86/// The shape of one task's `vec0` partition table: which task it serves, and the `(dim, metric)`
87/// its vectors are sized and ranked by.
88///
89/// A vector table cannot be created before something declares that shape, and the shape is a
90/// property of the *model* that writes into it — so the index takes it from the writer rather than
91/// guessing at open time.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub struct VectorTableSpec {
94    /// The task whose partition table this describes.
95    pub task: TaskKind,
96    /// Vector dimensionality (the `vec0` `float[N]` column width).
97    pub dim: EmbeddingDim,
98    /// The metric the partition ranks by.
99    pub metric: DistanceMetric,
100}
101
102/// The embedding-provenance gate the vector index calls before it stores or ranks anything —
103/// the seam through which the model inventory reaches the index **without the index depending on
104/// `ml`**.
105///
106/// Implemented by the ML layer's `Registry`, which owns the canonical rows and the version-bump
107/// swap primitive. The index only ever asks the three questions below, so the rest of the
108/// inventory (display names, fallbacks, swap history) stays out of that layer entirely.
109pub trait EmbeddingProvenance {
110    /// The gate on every insert: accept any version of a **known** model for an embedding task,
111    /// returning the `(dim, metric)` its vectors must match. An **unknown** model or a
112    /// non-embedding task is refused; a *superseded-but-known* version is **not** refused — it is
113    /// admitted and lands as a stale-flagged row.
114    fn check_insert(
115        &self,
116        task: TaskKind,
117        model_id: &ModelId,
118        version: &ModelVersion,
119    ) -> Result<(EmbeddingDim, DistanceMetric), RegistryError>;
120
121    /// The `(dim, metric)` of `task`'s vector space, or `None` if `task` stores no embeddings.
122    fn embedding_spec(&self, task: TaskKind) -> Option<(EmbeddingDim, DistanceMetric)>;
123
124    /// The **current** canonical `model_version` for `task` — the partition queries are answered
125    /// from — or `None` if the task has no canonical model.
126    fn canonical_version(&self, task: TaskKind) -> Option<ModelVersion>;
127
128    /// The partition table shape for `task`, if it stores embeddings.
129    fn vector_table(&self, task: TaskKind) -> Option<VectorTableSpec> {
130        let (dim, metric) = self.embedding_spec(task)?;
131        Some(VectorTableSpec { task, dim, metric })
132    }
133}
134
135/// The store port the ML layer writes embeddings into and ranks them from.
136///
137/// Partitioned by `(platform, model_version)`: a query answers from the **current** canonical
138/// version only, so a stale embedding (an older version, left over after a model swap) is excluded
139/// structurally until [`regenerate_stale`](crate::ml::regenerate_stale) replaces it. The production
140/// implementor is the library catalog; an implementation must honour these laws:
141///
142/// - [`insert_embedding`](Self::insert_embedding) refuses what
143///   [`EmbeddingProvenance::check_insert`] refuses and a vector whose length is not the declared
144///   dimension, and **replaces** any prior embedding for the same `(asset, task, platform)`;
145/// - [`knn`](Self::knn) returns hits nearest-first from the `platform` partition at the
146///   registry's current canonical version only;
147/// - [`stale_embedding_assets`](Self::stale_embedding_assets) lists, sorted, the assets in the
148///   `platform` partition whose stored version trails the canonical one.
149pub trait VectorIndex {
150    /// Insert (or replace) one provenanced embedding.
151    fn insert_embedding<P: EmbeddingProvenance>(
152        &self,
153        registry: &P,
154        e: EmbeddingInsert<'_>,
155    ) -> Result<(), VectorIndexError>;
156
157    /// The `k` nearest neighbours of `query` in `task`'s current canonical `platform` partition.
158    fn knn<P: EmbeddingProvenance>(
159        &self,
160        registry: &P,
161        task: TaskKind,
162        query: &[f32],
163        k: usize,
164        platform: &str,
165    ) -> Result<Vec<KnnHit>, VectorIndexError>;
166
167    /// The regeneration work-list: assets in `task`'s `platform` partition whose embedding is
168    /// stale under `registry`, sorted by asset id.
169    fn stale_embedding_assets<P: EmbeddingProvenance>(
170        &self,
171        registry: &P,
172        task: TaskKind,
173        platform: &str,
174    ) -> Result<Vec<String>, VectorIndexError>;
175}