capsule_core/ml/registry.rs
1//! The known-models seam and the embedding-provenance invariant (SSoT: [AI/ML —
2//! Models and Algorithms] + [AI/ML — Embedding Provenance]).
3//!
4//! One [`ModelRow`] per task. Every embedding Capsule stores carries the tuple
5//! `(model_id, model_version)` identifying which row produced it, and:
6//!
7//! - the vector index **refuses inserts** whose `model_id` is **unknown to the inventory**
8//! ([`Registry::check_insert`]) — a buggy or new client producing embeddings from an
9//! unrecognized model is rejected at the insert API, never silently mixed in;
10//! - a *superseded-but-known* version (a canonical model at an older version) is **admitted as a
11//! stale-flagged row** ([`Registry::is_stale`]) — it is the regeneration queue and is excluded
12//! from queries until regenerated from the originals; the refusal targets unknown models, not
13//! known-but-old ones;
14//! - a model swap **increments `model_version`**; pre-swap entries become stale by the same rule;
15//! - cross-`(model_id, model_version)` comparison is forbidden — vector spaces differ.
16//!
17//! Every `model_id` is declared in **exactly one** row, so swapping a model is a one-row edit
18//! that propagates by `model_id` to every consumer. This module owns the *canonical inventory
19//! rows* (the v1-committed slots, enriched with the function and fallback the contract names) and
20//! the version-bump **swap primitive** ([`Registry::bump_version`]); the background per-asset
21//! **regeneration orchestration** that consumes the resulting staleness lives in
22//! [`crate::ml::regen`], and the provenance gate the [vector index](crate::ml::EmbeddingInsert) calls is
23//! [`Registry::check_insert`].
24//!
25//! [AI/ML — Models and Algorithms]: https://docs/design/ai/#models-and-algorithms
26//! [AI/ML — Embedding Provenance]: https://docs/design/ai/#embedding-provenance
27
28// The identity vocabulary these rows are written in lives in the `domain` leaf — `db` names its
29// `vec0` columns with the same types, and importing them from `ml` closed a `db -> ml -> db`
30// cycle. Re-exported so `crate::ml::TaskKind` (and every other spelling) still resolves.
31pub use crate::domain::model_identity::{
32 DistanceMetric, EmbeddingDim, ModelId, ModelVersion, RegistryError, TaskKind,
33};
34use crate::ml::index::{EmbeddingProvenance, VectorTableSpec};
35
36/// What a task produces: a stored embedding vector, or detections that feed downstream stages.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum TaskOutput {
39 /// A normalized embedding stored in the vector index.
40 Embedding {
41 /// Vector dimensionality.
42 dim: EmbeddingDim,
43 /// Ranking metric.
44 metric: DistanceMetric,
45 },
46 /// Bounding boxes / landmarks (not stored as vectors here).
47 Detection,
48}
49
50/// One inventory row: the canonical model for a [`TaskKind`] — a v1-committed slot from
51/// [AI/ML — Pipeline Slots], carrying the model, its function, and its named fallback.
52///
53/// [AI/ML — Pipeline Slots]: https://docs/design/ai/#pipeline-slots
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct ModelRow {
56 /// The task this row serves.
57 pub task: TaskKind,
58 /// The canonical model id (unique across the whole inventory).
59 pub model_id: ModelId,
60 /// The current canonical version. A swap bumps this and flags prior entries stale.
61 pub canonical_version: ModelVersion,
62 /// What the model produces.
63 pub output: TaskOutput,
64 /// Human-readable label (logging / demo only).
65 pub display_name: &'static str,
66 /// The slot's function — the contract's Function column for this row.
67 pub function: &'static str,
68 /// The named fallback model the contract keeps for this slot if the canonical choice proves
69 /// insufficient in field testing (`None` where the contract names none). Not a second live
70 /// model: swapping to it is a [version bump](Registry::bump_version) like any other.
71 pub fallback: Option<&'static str>,
72}
73
74impl ModelRow {
75 /// The embedding `(dim, metric)` if this row produces stored embeddings.
76 pub fn embedding_spec(&self) -> Option<(EmbeddingDim, DistanceMetric)> {
77 match self.output {
78 TaskOutput::Embedding { dim, metric } => Some((dim, metric)),
79 TaskOutput::Detection => None,
80 }
81 }
82
83 /// The derivative `format` string for this model's embeddings, e.g. `embedding/mobileclip-b`
84 /// — the value carried in [`DerivativeCore::format`](crate::crypto::provenance::DerivativeCore::format).
85 pub fn embedding_format(&self) -> String {
86 format!("embedding/{}", self.model_id)
87 }
88}
89
90/// The model inventory seam and the embedding-provenance gate.
91#[derive(Debug, Clone)]
92pub struct Registry {
93 rows: Vec<ModelRow>,
94}
95
96impl Registry {
97 /// The v1-committed inventory — the four launch slots of [AI/ML — Pipeline Slots]:
98 /// MobileCLIP-B, YOLOv10, SCRFD, AdaFace, each with the contract's function and named
99 /// fallback. This is the seam the vector index gates against and the regeneration loop walks.
100 ///
101 /// [AI/ML — Pipeline Slots]: https://docs/design/ai/#pipeline-slots
102 pub fn canonical() -> Self {
103 let rows = vec![
104 ModelRow {
105 task: TaskKind::SemanticSearch,
106 model_id: ModelId("mobileclip-b".into()),
107 canonical_version: ModelVersion("1".into()),
108 output: TaskOutput::Embedding {
109 dim: EmbeddingDim(512),
110 metric: DistanceMetric::Cosine,
111 },
112 display_name: "MobileCLIP-B",
113 function: "Global image embedding for natural-language + similarity search; \
114 sized for the lowest-end device.",
115 fallback: Some("quantized SigLIP-tiny"),
116 },
117 ModelRow {
118 task: TaskKind::ObjectDetection,
119 model_id: ModelId("yolov10".into()),
120 canonical_version: ModelVersion("1".into()),
121 output: TaskOutput::Detection,
122 display_name: "YOLOv10",
123 function: "Object/background detection feeding dense tagging; the backbone is \
124 reused for person detection.",
125 fallback: None,
126 },
127 ModelRow {
128 task: TaskKind::FaceDetection,
129 model_id: ModelId("scrfd".into()),
130 canonical_version: ModelVersion("1".into()),
131 output: TaskOutput::Detection,
132 display_name: "SCRFD",
133 function: "Efficient face bounding-box + landmark detection.",
134 fallback: None,
135 },
136 ModelRow {
137 task: TaskKind::FaceRecognition,
138 model_id: ModelId("adaface".into()),
139 canonical_version: ModelVersion("1".into()),
140 output: TaskOutput::Embedding {
141 dim: EmbeddingDim(512),
142 metric: DistanceMetric::Cosine,
143 },
144 display_name: "InsightFace (AdaFace)",
145 function: "Face embeddings; AdaFace handles low-quality/dark images well.",
146 fallback: None,
147 },
148 ];
149 // SSoT invariant: every model_id appears in exactly one row, and every task has a row.
150 debug_assert!(Self::ids_unique(&rows), "duplicate model_id in inventory");
151 debug_assert!(
152 TaskKind::ALL
153 .iter()
154 .all(|t| rows.iter().any(|r| r.task == *t)),
155 "every task must have a canonical row"
156 );
157 Self { rows }
158 }
159
160 fn ids_unique(rows: &[ModelRow]) -> bool {
161 let mut ids: Vec<&str> = rows.iter().map(|r| r.model_id.as_str()).collect();
162 ids.sort_unstable();
163 let n = ids.len();
164 ids.dedup();
165 ids.len() == n
166 }
167
168 /// Every inventory row.
169 pub fn rows(&self) -> &[ModelRow] {
170 &self.rows
171 }
172
173 /// The canonical row for `task`.
174 pub fn canonical_for(&self, task: TaskKind) -> Option<&ModelRow> {
175 self.rows.iter().find(|r| r.task == task)
176 }
177
178 /// Record a model swap for `task` — a one-row edit setting its canonical version. Embeddings
179 /// stored at the prior version become [stale](Self::is_stale) and are excluded from queries
180 /// until [regenerated](crate::ml::regenerate_stale) from the originals.
181 pub fn set_canonical_version(&mut self, task: TaskKind, version: ModelVersion) {
182 if let Some(row) = self.rows.iter_mut().find(|r| r.task == task) {
183 row.canonical_version = version;
184 }
185 }
186
187 /// Swap the model for `task` by **incrementing** its canonical `model_version` — the contract's
188 /// "a model swap increments `model_version` for that task" ([AI/ML — Embedding Provenance]).
189 /// A numeric version is treated as an integer generation and advanced by one; a non-numeric
190 /// version gets a `+1` suffix so the tuple still changes. Returns the new canonical version, or
191 /// `None` if `task` has no row. This is the swap half of the version-bump regeneration loop —
192 /// its regeneration half is [`regen::regenerate_stale`](crate::ml::regenerate_stale),
193 /// which walks the now-stale entries [`stale_embedding_assets`](crate::ml::VectorIndex::stale_embedding_assets)
194 /// reports and replaces each per-asset.
195 ///
196 /// [AI/ML — Embedding Provenance]: https://docs/design/ai/#embedding-provenance
197 pub fn bump_version(&mut self, task: TaskKind) -> Option<ModelVersion> {
198 let row = self.rows.iter_mut().find(|r| r.task == task)?;
199 let next = match row.canonical_version.as_str().parse::<u64>() {
200 Ok(n) => (n.wrapping_add(1)).to_string(),
201 Err(_) => format!("{}+1", row.canonical_version),
202 };
203 row.canonical_version = ModelVersion::from(next);
204 Some(row.canonical_version.clone())
205 }
206
207 /// The row a `model_id` belongs to, if any (each id is in at most one row).
208 pub fn row_for_id(&self, model_id: &ModelId) -> Option<&ModelRow> {
209 self.rows.iter().find(|r| &r.model_id == model_id)
210 }
211
212 /// Whether `model_id` is a known model of some task.
213 pub fn is_canonical(&self, model_id: &ModelId) -> bool {
214 self.row_for_id(model_id).is_some()
215 }
216
217 /// The embedding dimension for `task`, if it produces embeddings.
218 pub fn dim_for(&self, task: TaskKind) -> Option<EmbeddingDim> {
219 self.canonical_for(task)?.embedding_spec().map(|(d, _)| d)
220 }
221
222 /// The ranking metric for `task`, if it produces embeddings.
223 pub fn metric_for(&self, task: TaskKind) -> Option<DistanceMetric> {
224 self.canonical_for(task)?.embedding_spec().map(|(_, m)| m)
225 }
226
227 /// Whether `(model_id, version)` is the *current* canonical pair for `task`.
228 pub fn is_current(&self, task: TaskKind, model_id: &ModelId, version: &ModelVersion) -> bool {
229 self.canonical_for(task)
230 .is_some_and(|r| &r.model_id == model_id && &r.canonical_version == version)
231 }
232
233 /// Whether an entry tagged `(model_id, version)` for `task` is **stale** — i.e. the task has a
234 /// canonical row but the pair is not the current one. Stale entries are admitted but excluded
235 /// from queries until regenerated from the originals.
236 pub fn is_stale(&self, task: TaskKind, model_id: &ModelId, version: &ModelVersion) -> bool {
237 self.canonical_for(task).is_some() && !self.is_current(task, model_id, version)
238 }
239
240 /// The embedding-provenance gate the vector index calls on every insert: accept any version of
241 /// the **known** model for an embedding task, returning its `(dim, metric)`. An **unknown**
242 /// model or a non-embedding task is refused; a *superseded-but-known* version is **not**
243 /// refused here — it is admitted (and, being non-current, [stale](Self::is_stale)).
244 pub fn check_insert(
245 &self,
246 task: TaskKind,
247 model_id: &ModelId,
248 _version: &ModelVersion,
249 ) -> Result<(EmbeddingDim, DistanceMetric), RegistryError> {
250 let row = self
251 .canonical_for(task)
252 .ok_or_else(|| RegistryError::NonCanonical {
253 task,
254 model_id: model_id.clone(),
255 })?;
256 if &row.model_id != model_id {
257 return Err(RegistryError::NonCanonical {
258 task,
259 model_id: model_id.clone(),
260 });
261 }
262 row.embedding_spec()
263 .ok_or(RegistryError::NotAnEmbeddingTask { task })
264 }
265}
266
267/// The partition tables this inventory's embedding slots need — the `db`-side description of the
268/// `vec0` schema, with no `ml` type in sight. Hand it to
269/// `DatabaseDriver::create_vector_tables` to
270/// materialize the whole schema up front instead of on first use.
271impl Registry {
272 /// One [`VectorTableSpec`] per embedding-producing slot (detection slots store no vectors).
273 pub fn vector_tables(&self) -> Vec<VectorTableSpec> {
274 self.rows
275 .iter()
276 .filter_map(|r| {
277 r.embedding_spec().map(|(dim, metric)| VectorTableSpec {
278 task: r.task,
279 dim,
280 metric,
281 })
282 })
283 .collect()
284 }
285}
286
287/// The inventory seen through the vector index's eyes: the three questions `db` asks, answered by
288/// delegating to the inherent inventory methods. This impl **is** the inverted `db -> ml` edge —
289/// `db` names the trait, `ml` supplies the implementation, so the dependency now runs one way.
290impl EmbeddingProvenance for Registry {
291 fn check_insert(
292 &self,
293 task: TaskKind,
294 model_id: &ModelId,
295 version: &ModelVersion,
296 ) -> Result<(EmbeddingDim, DistanceMetric), RegistryError> {
297 Registry::check_insert(self, task, model_id, version)
298 }
299
300 fn embedding_spec(&self, task: TaskKind) -> Option<(EmbeddingDim, DistanceMetric)> {
301 self.canonical_for(task)?.embedding_spec()
302 }
303
304 fn canonical_version(&self, task: TaskKind) -> Option<ModelVersion> {
305 self.canonical_for(task)
306 .map(|r| r.canonical_version.clone())
307 }
308}
309
310impl Default for Registry {
311 fn default() -> Self {
312 Self::canonical()
313 }
314}
315
316#[cfg(test)]
317mod tests;