Skip to main content

capsule_core/ml/
regen.rs

1//! Version-bump regeneration — the background work-loop that rebuilds stale embeddings (SSoT:
2//! [AI/ML — Embedding Provenance]).
3//!
4//! A model swap [increments](crate::ml::Registry::bump_version) a task's canonical `model_version`;
5//! every embedding stored at the prior version is left **stale-flagged** and excluded from queries
6//! ([`stale_embedding_assets`](crate::ml::VectorIndex::stale_embedding_assets) is the resulting
7//! work-list). This module walks that list and re-embeds each asset at the new canonical version,
8//! **replacing** the old vector per-asset — never a global truncate-and-rebuild — so
9//! already-regenerated assets stay queryable throughout and the not-yet-done ones stay excluded
10//! (the contract's "old entries are removed only after new ones persist").
11//!
12//! The loop is **resumable by construction**: it holds no cursor. The work-list is *derived* from
13//! current staleness, so a run killed mid-loop simply re-derives the remaining stale assets on the
14//! next call — a completed asset is no longer stale and never reappears; a not-yet-started one
15//! still does. Passing a `budget` bounds each invocation (the background-task shape: call until
16//! `remaining == 0`, yielding between chunks for the [thermal-throttle
17//! pause](crate::ml) and micro-batch ceiling).
18//!
19//! Real per-platform inference is deferred behind the [`Embedder`] seam exactly as live MLS state
20//! is deferred behind [`AlbumAuthority`](crate::crypto::authority::AlbumAuthority): the
21//! deterministic [`DeterministicEmbedder`] reference double drives the loop end-to-end with no
22//! model weights, and a later slice supplies the on-device runner.
23//!
24//! [AI/ML — Embedding Provenance]: https://docs/design/ai/#embedding-provenance
25
26use thiserror::Error;
27use uuid::Uuid;
28
29use crate::ml::index::{EmbeddingInsert, VectorIndex, VectorIndexError};
30use crate::ml::{AssetSource, Frame, ModelId, ModelRunner, ModelVersion, Registry, TaskKind};
31
32/// The embedder seam the regeneration loop drives: "produce the canonical embedding for an asset
33/// under a task". Abstracting it keeps the orchestration testable with a deterministic double and
34/// independent of any real model runtime.
35pub trait Embedder {
36    /// The `(model_id, model_version)` this embedder produces for `task`, or `None` if it does not
37    /// serve that task (e.g. a non-embedding task). The loop refuses an embedder whose declared
38    /// pair is not the registry canonical — its outputs would otherwise be stored under a tuple
39    /// they did not produce.
40    fn model(&self, task: TaskKind) -> Option<(ModelId, ModelVersion)>;
41
42    /// The `platform` partition discriminator for this embedder's outputs (incomparable across
43    /// platforms; see the E2EE fallback in `ai.md`).
44    fn platform(&self) -> &str;
45
46    /// Produce the embedding vector for `asset_id` under `task`. Its length must equal the task's
47    /// registry-declared dimension (the vector index re-checks this on insert).
48    fn embed(&self, asset_id: &str, task: TaskKind) -> Result<Vec<f32>, EmbedError>;
49}
50
51/// A failure producing an embedding for an asset.
52#[derive(Debug, Clone, PartialEq, Eq, Error)]
53#[error("embedding asset `{asset_id}` for {task:?} failed: {reason}")]
54pub struct EmbedError {
55    /// The asset that failed to embed.
56    pub asset_id: String,
57    /// The task being embedded.
58    pub task: TaskKind,
59    /// A human-readable reason (logging / diagnostics).
60    pub reason: String,
61}
62
63/// Failures from the regeneration loop.
64#[derive(Debug, Error)]
65pub enum RegenError {
66    /// The task has no canonical embedding model (unknown task, or a detection task with no stored
67    /// vectors to regenerate).
68    #[error("task {task:?} has no canonical embedding model to regenerate")]
69    NotAnEmbeddingTask {
70        /// The task.
71        task: TaskKind,
72    },
73    /// The embedder does not produce the registry's canonical `(model_id, model_version)` for the
74    /// task — regeneration is refused before any output is stored, so the index never gains a
75    /// vector tagged with a tuple the embedder did not produce.
76    #[error(
77        "embedder model `{declared_id}` v`{declared_version}` is not canonical for task {task:?} \
78         (canonical `{canonical_id}` v`{canonical_version}`)"
79    )]
80    NonCanonicalEmbedder {
81        /// The task.
82        task: TaskKind,
83        /// The embedder's declared model id.
84        declared_id: ModelId,
85        /// The embedder's declared model version.
86        declared_version: ModelVersion,
87        /// The registry's canonical model id.
88        canonical_id: ModelId,
89        /// The registry's canonical model version.
90        canonical_version: ModelVersion,
91    },
92    /// Producing an embedding failed.
93    #[error(transparent)]
94    Embed(#[from] EmbedError),
95    /// Writing the fresh embedding to the vector index failed.
96    #[error(transparent)]
97    Vector(#[from] VectorIndexError),
98}
99
100/// The outcome of one regeneration invocation.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub struct RegenReport {
103    /// The task regenerated.
104    pub task: TaskKind,
105    /// How many stale embeddings were rebuilt in this invocation.
106    pub regenerated: usize,
107    /// How many stale embeddings remain in the partition after this invocation (`0` when drained).
108    pub remaining: usize,
109}
110
111impl RegenReport {
112    /// Whether the partition is fully regenerated (no stale entries remain).
113    pub fn is_complete(&self) -> bool {
114        self.remaining == 0
115    }
116}
117
118/// Regenerate stale embeddings for `task` in `embedder`'s platform partition, re-deriving the
119/// work-list from [`stale_embedding_assets`](VectorIndex::stale_embedding_assets) on each call.
120///
121/// `budget` bounds the invocation: `Some(n)` rebuilds up to `n` assets (the background chunk;
122/// call again until [`RegenReport::is_complete`]); `None` drains the whole partition. Assets are
123/// processed in the work-list's sorted order, so a bounded run is deterministic and its remainder
124/// is exactly the tail. Each asset's fresh vector is inserted with a per-asset replace before the
125/// next is processed, so the run is safe to interrupt at any point.
126///
127/// Refuses a `NonCanonicalEmbedder` (an embedder not producing the current canonical tuple) before
128/// touching the index.
129pub fn regenerate_stale<I: VectorIndex, E: Embedder>(
130    db: &I,
131    registry: &Registry,
132    embedder: &E,
133    task: TaskKind,
134    budget: Option<usize>,
135) -> Result<RegenReport, RegenError> {
136    let canon = registry
137        .canonical_for(task)
138        .filter(|r| r.embedding_spec().is_some())
139        .ok_or(RegenError::NotAnEmbeddingTask { task })?;
140
141    // The embedder must declare the current canonical tuple, or its outputs are refused wholesale.
142    match embedder.model(task) {
143        Some((id, version)) if id == canon.model_id && version == canon.canonical_version => {}
144        other => {
145            let (declared_id, declared_version) =
146                other.unwrap_or_else(|| (ModelId::from(""), ModelVersion::from("")));
147            return Err(RegenError::NonCanonicalEmbedder {
148                task,
149                declared_id,
150                declared_version,
151                canonical_id: canon.model_id.clone(),
152                canonical_version: canon.canonical_version.clone(),
153            });
154        }
155    }
156
157    let platform = embedder.platform().to_string();
158    let worklist = db.stale_embedding_assets(registry, task, &platform)?;
159    let total = worklist.len();
160    let take = budget.unwrap_or(total);
161    tracing::info!(
162        ?task,
163        platform = %platform,
164        model_id = %canon.model_id,
165        model_version = %canon.canonical_version,
166        stale = total,
167        chunk = take,
168        "ml regen: starting a regeneration chunk"
169    );
170
171    let mut regenerated = 0;
172    for asset_id in worklist.iter().take(take) {
173        tracing::trace!(?task, asset_id, "ml regen: re-embedding a stale asset");
174        let vector = embedder.embed(asset_id, task)?;
175        db.insert_embedding(
176            registry,
177            EmbeddingInsert {
178                asset_id,
179                task,
180                model_id: &canon.model_id,
181                model_version: &canon.canonical_version,
182                platform: &platform,
183                vector: &vector,
184            },
185        )?;
186        regenerated += 1;
187        tracing::debug!(
188            ?task,
189            asset_id,
190            model_version = %canon.canonical_version,
191            "ml regen: stale embedding replaced at the canonical version"
192        );
193    }
194
195    let remaining = total - regenerated;
196    tracing::info!(
197        ?task,
198        platform = %platform,
199        regenerated,
200        remaining,
201        "ml regen: chunk complete"
202    );
203    Ok(RegenReport {
204        task,
205        regenerated,
206        remaining,
207    })
208}
209
210/// The production [`Embedder`]: regeneration **re-runs inference over the originals**.
211///
212/// This is the adapter that makes regeneration mean what [AI/ML — Embedding
213/// Provenance](https://docs/design/ai/#embedding-provenance) says it means. The vector index is
214/// derived state: a version bump invalidates it, and it is rebuilt by re-reading each asset's
215/// original plaintext through the [`AssetSource`] seam and re-running the canonical model through
216/// the [`ModelRunner`] seam — never by copying, re-labelling, or restoring the stale vector. It is
217/// the same pair of seams [`embed_and_store`](crate::ml::embed_and_store) uses for first-time
218/// indexing, so the regenerated vector is byte-identical to what a fresh import would produce.
219///
220/// `partition` is the `vec0` partition the outputs belong to — resolve it with
221/// [`resolve_partition`](crate::ml::resolve_partition) rather than assuming
222/// [`CANONICAL_PARTITION`](crate::ml::CANONICAL_PARTITION), so a device that failed the
223/// known-answer check regenerates within its own partition instead of polluting the shared one.
224#[derive(Debug, Clone, Copy)]
225pub struct RunnerEmbedder<'a, R, S> {
226    /// Where the originals come from (and whose catalog holds the index).
227    source: &'a S,
228    /// The inference seam the canonical model runs behind.
229    runner: &'a R,
230    /// The `vec0` partition these outputs belong to.
231    partition: &'a str,
232}
233
234impl<'a, R: ModelRunner, S: AssetSource> RunnerEmbedder<'a, R, S> {
235    /// An embedder that reads `source`'s originals and re-runs `runner` over them, writing into
236    /// `partition`.
237    pub fn new(source: &'a S, runner: &'a R, partition: &'a str) -> Self {
238        Self {
239            source,
240            runner,
241            partition,
242        }
243    }
244
245    /// The catalog holding the vector index these embeddings are regenerated into — pass it to
246    /// [`regenerate_stale`] so the work-list and the writes address one index.
247    pub fn index(&self) -> &'a S::Index {
248        self.source.vector_index()
249    }
250}
251
252impl<R: ModelRunner, S: AssetSource> Embedder for RunnerEmbedder<'_, R, S> {
253    fn model(&self, task: TaskKind) -> Option<(ModelId, ModelVersion)> {
254        self.runner.model(task)
255    }
256
257    fn platform(&self) -> &str {
258        self.partition
259    }
260
261    fn embed(&self, asset_id: &str, task: TaskKind) -> Result<Vec<f32>, EmbedError> {
262        let fail = |reason: String| EmbedError {
263            asset_id: asset_id.to_string(),
264            task,
265            reason,
266        };
267        // Index rows key assets by their string form; the store keys them by UUID.
268        let uuid =
269            Uuid::parse_str(asset_id).map_err(|e| fail(format!("asset id is not a UUID: {e}")))?;
270        // The originals are the source of truth the derived index is rebuilt from.
271        let bytes = self
272            .source
273            .read_plaintext(&uuid)
274            .map_err(|e| fail(format!("reading the original failed: {e}")))?;
275        self.runner
276            .embed_image(task, &[Frame::new(&bytes)])
277            .map_err(|e| fail(e.to_string()))?
278            .into_iter()
279            .next()
280            .ok_or_else(|| fail("runner returned no embedding".to_string()))
281    }
282}
283
284/// A deterministic reference embedder — **no real inference**, no model weights. It maps
285/// `(asset_id, canonical_version)` to a stable L2-normalized vector, so:
286///
287/// - the same asset re-embeds identically within a version (idempotent inserts);
288/// - a version bump yields a *different* vector — a genuine re-embed, not a copy of the old one;
289/// - a query is reproduced by [embedding the same key](Self::embed_key), giving an exact match.
290///
291/// It stands in for the on-device model runner the way
292/// [`ReferenceAuthority`](crate::crypto::authority::ReferenceAuthority) stands in for live MLS
293/// state: enough to exercise the regeneration orchestration end-to-end and deterministically.
294#[derive(Debug, Clone)]
295pub struct DeterministicEmbedder {
296    registry: Registry,
297    platform: String,
298}
299
300impl DeterministicEmbedder {
301    /// A reference embedder for `platform` producing the current canonical inventory.
302    pub fn new(platform: impl Into<String>) -> Self {
303        Self {
304            registry: Registry::canonical(),
305            platform: platform.into(),
306        }
307    }
308
309    /// A reference embedder pinned to a specific `registry` — use a version-bumped registry to
310    /// model the post-swap model that produces the new canonical version.
311    pub fn with_registry(platform: impl Into<String>, registry: Registry) -> Self {
312        Self {
313            registry,
314            platform: platform.into(),
315        }
316    }
317
318    /// Embed an arbitrary `key` (an asset id, or a query concept) at `task`'s canonical version —
319    /// the query side of the reference vector space. Returns an empty vector for a non-embedding
320    /// task.
321    pub fn embed_key(&self, key: &str, task: TaskKind) -> Vec<f32> {
322        match self.registry.canonical_for(task).and_then(|r| {
323            r.embedding_spec()
324                .map(|(dim, _)| (dim.get(), r.canonical_version.clone()))
325        }) {
326            Some((dim, version)) => seeded_unit_vector(key, version.as_str(), dim),
327            None => Vec::new(),
328        }
329    }
330}
331
332impl Embedder for DeterministicEmbedder {
333    fn model(&self, task: TaskKind) -> Option<(ModelId, ModelVersion)> {
334        let row = self.registry.canonical_for(task)?;
335        // Only embedding tasks produce stored vectors.
336        row.embedding_spec()?;
337        Some((row.model_id.clone(), row.canonical_version.clone()))
338    }
339
340    fn platform(&self) -> &str {
341        &self.platform
342    }
343
344    fn embed(&self, asset_id: &str, task: TaskKind) -> Result<Vec<f32>, EmbedError> {
345        let row = self
346            .registry
347            .canonical_for(task)
348            .ok_or_else(|| EmbedError {
349                asset_id: asset_id.to_string(),
350                task,
351                reason: "no canonical model for task".into(),
352            })?;
353        let (dim, _) = row.embedding_spec().ok_or_else(|| EmbedError {
354            asset_id: asset_id.to_string(),
355            task,
356            reason: "task does not produce stored embeddings".into(),
357        })?;
358        Ok(seeded_unit_vector(
359            asset_id,
360            row.canonical_version.as_str(),
361            dim.get(),
362        ))
363    }
364}
365
366/// FNV-1a 64-bit hash — a small, dependency-free, deterministic mixer for seeding.
367fn fnv1a64(bytes: &[u8]) -> u64 {
368    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
369    for &b in bytes {
370        h ^= b as u64;
371        h = h.wrapping_mul(0x0000_0100_0000_01b3);
372    }
373    h
374}
375
376/// SplitMix64 — a deterministic PRNG step for filling a vector from a seed.
377fn splitmix64(state: &mut u64) -> u64 {
378    *state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
379    let mut z = *state;
380    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
381    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
382    z ^ (z >> 31)
383}
384
385/// A deterministic L2-normalized vector of length `dim`, seeded by `(key, version)`. Distinct keys
386/// give distinct directions; the same key at a different version gives a distinct vector (so a
387/// version bump is a genuine re-embed). Embeddings are normalized, so cosine ranks as the inner
388/// product — matching the vector index's metric.
389fn seeded_unit_vector(key: &str, version: &str, dim: usize) -> Vec<f32> {
390    let mut state = fnv1a64(key.as_bytes()) ^ fnv1a64(version.as_bytes()).rotate_left(32);
391    let mut v = Vec::with_capacity(dim);
392    for _ in 0..dim {
393        // Top 53 bits → a double in [0, 1); map to [-1, 1).
394        let unit = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
395        v.push((unit * 2.0 - 1.0) as f32);
396    }
397    let norm: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
398    if norm > 0.0 {
399        for x in &mut v {
400            *x /= norm;
401        }
402    } else if dim > 0 {
403        v[0] = 1.0;
404    }
405    v
406}