capsule_core/domain/model_identity.rs
1//! Model-identity vocabulary — the names a task, a model, and a vector space are identified by.
2//!
3//! These types are **shared vocabulary, not ML behaviour**. Two very different layers need them:
4//!
5//! - the [vector index](crate::ml::VectorIndex) names its `vec0` tables after a [`TaskKind`], sizes
6//! their columns with an [`EmbeddingDim`], ranks them by a [`DistanceMetric`], and partitions
7//! them by a [`ModelVersion`] — all before any model has run;
8//! - the [model registry](crate::ml::Registry) uses the same names to *describe* the models it
9//! declares.
10//!
11//! They used to live in `ml::registry`, which forced `db` to `use crate::ml` merely to spell its
12//! own column types — closing a `db -> ml -> db` module cycle. Hoisting them into `domain` (a leaf
13//! with no outgoing crate edges) turns that cycle into the DAG `domain <- db <- ml`. The behaviour
14//! that reads these names — the canonical inventory, the swap primitive, and the provenance gate —
15//! stays in [`crate::ml::Registry`]; only the vocabulary moved. Every name here is re-exported
16//! from [`crate::ml`], so `capsule_core::ml::TaskKind` and friends resolve unchanged.
17//!
18//! [`RegistryError`] rides along because it *is* vocabulary: it names a task and a model id and
19//! nothing else, and the vector index has to be able to spell it to carry a refusal outward.
20
21use std::fmt;
22
23use serde::{Deserialize, Serialize};
24use thiserror::Error;
25
26/// A canonical ML task — the v1-committed launch pipeline ([AI/ML — Pipeline Slots]).
27///
28/// Closed enum per protocol version: an unknown value is a **structural error**, never a
29/// "future value to ignore". Post-v1 candidate tasks each commit to a full inventory row (and a
30/// new variant here) when they ship.
31///
32/// [AI/ML — Pipeline Slots]: https://docs/design/ai/#pipeline-slots
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
34#[serde(rename_all = "kebab-case")]
35pub enum TaskKind {
36 /// Global image embedding for natural-language + similarity search (MobileCLIP-B).
37 SemanticSearch,
38 /// Object/background detection feeding dense tagging (YOLOv10).
39 ObjectDetection,
40 /// Face bounding-box + landmark detection (SCRFD).
41 FaceDetection,
42 /// Face embedding for matching/clustering (InsightFace AdaFace).
43 FaceRecognition,
44}
45
46impl TaskKind {
47 /// Every committed task, in inventory order.
48 pub const ALL: [TaskKind; 4] = [
49 TaskKind::SemanticSearch,
50 TaskKind::ObjectDetection,
51 TaskKind::FaceDetection,
52 TaskKind::FaceRecognition,
53 ];
54}
55
56/// A model identifier (stable across versions; e.g. `mobileclip-b`). Declared in exactly one
57/// [`ModelRow`](crate::ml::ModelRow). Serializes transparently as its string so it interoperates
58/// with the `model_id` fields on [`AiTag`](crate::sidecar::AiTag) and
59/// [`DerivativeCore`](crate::crypto::provenance::DerivativeCore).
60#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
61#[serde(transparent)]
62pub struct ModelId(pub String);
63
64/// A model version. Bumped on every model swap for a task; old embeddings at a prior version are
65/// flagged stale. Serializes transparently as its string (see [`ModelId`]).
66#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
67#[serde(transparent)]
68pub struct ModelVersion(pub String);
69
70macro_rules! str_newtype {
71 ($t:ty) => {
72 impl $t {
73 /// The underlying string.
74 pub fn as_str(&self) -> &str {
75 &self.0
76 }
77 }
78 impl From<&str> for $t {
79 fn from(s: &str) -> Self {
80 Self(s.to_string())
81 }
82 }
83 impl From<String> for $t {
84 fn from(s: String) -> Self {
85 Self(s)
86 }
87 }
88 impl fmt::Display for $t {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 f.write_str(&self.0)
91 }
92 }
93 };
94}
95str_newtype!(ModelId);
96str_newtype!(ModelVersion);
97
98/// The dimensionality of an embedding vector for an embedding-producing task.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
100pub struct EmbeddingDim(pub u32);
101
102impl EmbeddingDim {
103 /// The dimension as a `usize` (for buffer sizing).
104 pub fn get(self) -> usize {
105 self.0 as usize
106 }
107}
108
109impl fmt::Display for EmbeddingDim {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111 write!(f, "{}", self.0)
112 }
113}
114
115/// The distance metric a vector index ranks an embedding task by.
116///
117/// Embeddings are L2-normalized, so **cosine distance ranks identically to the inner product**
118/// — this is the design's inner-product ranking intent, expressed with the metric the SQLite
119/// `vec0` engine implements.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(rename_all = "kebab-case")]
122pub enum DistanceMetric {
123 /// Cosine distance over normalized vectors (== inner-product ranking).
124 Cosine,
125 /// Squared Euclidean (L2) distance.
126 L2,
127}
128
129/// Refusals from the embedding-provenance invariant — produced by the
130/// [gate](crate::ml::EmbeddingProvenance) the vector index calls on every insert, and
131/// carried outward by [`VectorIndexError`](crate::ml::VectorIndexError).
132#[derive(Debug, Clone, PartialEq, Eq, Error)]
133pub enum RegistryError {
134 /// The `model_id` is not a known inventory model for the task (an unknown model). A stale but
135 /// *known* version is **not** this error — it is admitted as a stale row.
136 #[error("model `{model_id}` is not known for task {task:?}")]
137 NonCanonical {
138 /// The task.
139 task: TaskKind,
140 /// The offending model id.
141 model_id: ModelId,
142 },
143 /// The task does not produce stored embeddings (e.g. a detection task).
144 #[error("task {task:?} does not produce stored embeddings")]
145 NotAnEmbeddingTask {
146 /// The task.
147 task: TaskKind,
148 },
149}
150
151#[cfg(test)]
152mod tests;