capsule_core/ml/orchestrator.rs
1//! Inference orchestration — the deterministic execution path for the v1-committed slots (SSoT:
2//! [AI/ML Integrations]).
3//!
4//! Ties a [`ModelRunner`] to an asset store: run the canonical model over an asset's decoded
5//! pixels, then land the results —
6//!
7//! - **embeddings** (semantic-search + face-recognition vectors) into the right `vec0` partition of
8//! the [vector index](crate::ml::EmbeddingInsert), tagged with the runner's resolved partition
9//! discriminator ([`resolve_partition`]);
10//! - **zero-shot AI tags** into the asset's `tags_ai` OR-set as a **signed metadata update** through
11//! the lifecycle ([`AiTagSink::add_ai_tags`]) — structurally separate from user tags, mirroring
12//! `Workspace::set_cull`'s write-through. The semantic embeddings are reused for classification,
13//! so there is no separate classifier ([AI/ML — Image Categorization & Tagging]).
14//!
15//! The store reaches this module through the [`AssetSource`] / [`AiTagSink`] seams rather than as a
16//! concrete type. The one production implementor is
17//! `Workspace` — but naming it here would make `ml` depend on
18//! `lifecycle`, which already depends on `ml` (`lifecycle::metadata` reads the registry to filter
19//! stale AI tags). Inverting the edge leaves the dependency running one way, and lets the
20//! orchestration be driven by any store that can hand over plaintext bytes and accept AI tags.
21//!
22//! Two invariants are enforced at this boundary:
23//!
24//! - **Provenance.** A runner whose declared model is not the registry canonical for a task is
25//! refused before any output is stored (`require_canonical_runner`).
26//! - **Platform partition.** Comparable embeddings need byte-identical inference output across
27//! NPUs/CPUs. A device that reproduces the pinned known-answer bit-exactly shares the
28//! [`CANONICAL_PARTITION`]; a device that cannot is **not merged** into another platform's index —
29//! its embeddings land under its own [`platform`](ModelRunner::platform) tag and are compared only
30//! within that partition ([AI/ML — Embedding Provenance], the E2EE constraint's explicit
31//! fallback). The worst case is duplicated per-platform regeneration, never wrong results.
32//!
33//! Real per-platform runners ride the default-off `inference` feature; here the deterministic
34//! [`FixtureRunner`](crate::ml::FixtureRunner) drives every path end-to-end with no model weights.
35//!
36//! [AI/ML Integrations]: https://docs/design/ai/
37//! [AI/ML — Image Categorization & Tagging]: https://docs/design/ai/#image-categorization--tagging
38//! [AI/ML — Embedding Provenance]: https://docs/design/ai/#embedding-provenance
39
40use thiserror::Error;
41use uuid::Uuid;
42
43use crate::ml::index::{EmbeddingInsert, KnnHit, VectorIndex, VectorIndexError};
44use crate::ml::{Embedding, Frame, ModelId, ModelRunner, Registry, RunnerError, TaskKind};
45use crate::sidecar::AiTag;
46
47/// The store the orchestrator reads asset pixels from and indexes vectors into.
48///
49/// Implemented by `Workspace`; a test double only has to produce
50/// bytes for an id and hand back a catalog. Keeping it a trait is what removes the
51/// `ml -> lifecycle` import (see the module docs).
52pub trait AssetSource {
53 /// How this store reports a failed read. Type-erased into [`StoreError`] on the way out, so
54 /// `ml` never names a concrete store error.
55 type Error: std::error::Error + Send + Sync + 'static;
56
57 /// The decoded-asset plaintext bytes inference runs over.
58 fn read_plaintext(&self, asset_id: &Uuid) -> Result<Vec<u8>, Self::Error>;
59
60 /// The vector index this store's embeddings live in.
61 type Index: VectorIndex;
62
63 /// The catalog holding this store's vector index.
64 fn vector_index(&self) -> &Self::Index;
65}
66
67/// The write side: an asset store that accepts AI tags for an asset.
68///
69/// Separate from [`AssetSource`] because only [`auto_tag`] writes — embedding and search need a
70/// shared reference, and the split keeps them from demanding `&mut`.
71pub trait AiTagSink: AssetSource {
72 /// Add `tags` to the asset's `tags_ai` namespace (never `tags_user`), as one signed
73 /// metadata update. An empty `tags` is a no-op.
74 fn add_ai_tags(&mut self, asset_id: &Uuid, tags: Vec<AiTag>) -> Result<(), Self::Error>;
75}
76
77/// A failure from the asset store behind the [`AssetSource`] / [`AiTagSink`] seam, type-erased.
78///
79/// For the `Workspace` implementation this wraps a
80/// `LifecycleError`; `ml` cannot name that type without re-creating the cycle this seam broke, so
81/// the concrete error is boxed and its message preserved.
82#[derive(Debug, Error)]
83#[error("asset store: {0}")]
84pub struct StoreError(pub Box<dyn std::error::Error + Send + Sync>);
85
86/// Box a store error into an [`OrchestratorError`].
87fn store_err<E: std::error::Error + Send + Sync + 'static>(e: E) -> OrchestratorError {
88 OrchestratorError::Store(StoreError(Box::new(e)))
89}
90
91/// Failures from orchestrating inference.
92#[derive(Debug, Error)]
93pub enum OrchestratorError {
94 /// A read or a tag write against the asset store failed.
95 #[error(transparent)]
96 Store(#[from] StoreError),
97 /// The runner failed.
98 #[error(transparent)]
99 Runner(#[from] RunnerError),
100 /// A vector-index insert / query failed.
101 #[error(transparent)]
102 Vector(#[from] VectorIndexError),
103 /// The task has no canonical model (or is not an embedding task where one is required).
104 #[error("task {task:?} has no canonical embedding model")]
105 NoCanonical {
106 /// The task.
107 task: TaskKind,
108 },
109 /// The runner's declared model is not the registry canonical for the task — its outputs are
110 /// refused rather than stored under a canonical tuple they did not produce.
111 #[error("runner model `{declared}` is not canonical for task {task:?}")]
112 NonCanonicalRunner {
113 /// The task.
114 task: TaskKind,
115 /// The runner's declared model id.
116 declared: ModelId,
117 },
118}
119
120/// Confirm `runner` produces the registry's canonical `(model_id, model_version)` for `task` — the
121/// embedding-provenance gate at the orchestration boundary (before any output is stored).
122fn require_canonical_runner<R: ModelRunner>(
123 runner: &R,
124 registry: &Registry,
125 task: TaskKind,
126) -> Result<(), OrchestratorError> {
127 let canon = registry
128 .canonical_for(task)
129 .ok_or(OrchestratorError::NoCanonical { task })?;
130 let (declared_id, declared_ver) = runner.model(task).ok_or(RunnerError::Unsupported(task))?;
131 if declared_id != canon.model_id || declared_ver != canon.canonical_version {
132 return Err(OrchestratorError::NonCanonicalRunner {
133 task,
134 declared: declared_id,
135 });
136 }
137 Ok(())
138}
139
140fn first_embedding(embeddings: Vec<Embedding>) -> Result<Embedding, RunnerError> {
141 embeddings
142 .into_iter()
143 .next()
144 .ok_or_else(|| RunnerError::Inference("runner returned no embedding".into()))
145}
146
147// ── Platform-partition fallback (ai.md § Embedding Provenance — the E2EE constraint) ─────────────
148
149/// The shared partition every device that reaches bit-exactness on the deterministic execution
150/// path writes into. Devices that cannot fall back to their own [`platform`](ModelRunner::platform)
151/// tag and are never merged into this partition.
152pub const CANONICAL_PARTITION: &str = "canonical";
153
154/// A known-answer probe pinning the deterministic execution path for a task: a fixed input and the
155/// exact embedding a bit-exact device must reproduce. Comparing a runner's output to `expected`
156/// **bit-for-bit** is the byte-identical known-answer check the contract requires.
157#[derive(Debug, Clone, PartialEq)]
158pub struct KnownAnswer {
159 /// The embedding task the probe pins.
160 pub task: TaskKind,
161 /// The fixed probe input bytes.
162 pub input: Vec<u8>,
163 /// The exact embedding a device on the canonical path must reproduce.
164 pub expected: Embedding,
165}
166
167impl KnownAnswer {
168 /// Capture the known-answer for `task` from a reference runner (the canonical device that
169 /// defines the shared vector space). A later device compares against this via
170 /// [`resolve_partition`].
171 pub fn capture<R: ModelRunner>(
172 runner: &R,
173 registry: &Registry,
174 task: TaskKind,
175 input: &[u8],
176 ) -> Result<Self, OrchestratorError> {
177 require_canonical_runner(runner, registry, task)?;
178 let expected = first_embedding(runner.embed_image(task, &[Frame::new(input)])?)?;
179 Ok(Self {
180 task,
181 input: input.to_vec(),
182 expected,
183 })
184 }
185}
186
187/// Resolve the `vec0` partition `runner`'s embeddings for `ka.task` must land in.
188///
189/// If `runner` reproduces `ka.expected` **bit-exactly** the deterministic-execution-path check
190/// passed and its vectors are comparable with every other canonical device — it writes into the
191/// shared [`CANONICAL_PARTITION`]. Otherwise the fallback is explicit, never silent: the runner's
192/// own [`platform`](ModelRunner::platform) tag, a partition its incomparable vectors are confined to
193/// and regenerated within (never merged into another platform's index).
194pub fn resolve_partition<R: ModelRunner>(
195 runner: &R,
196 ka: &KnownAnswer,
197) -> Result<String, OrchestratorError> {
198 let got = first_embedding(runner.embed_image(ka.task, &[Frame::new(&ka.input)])?)?;
199 Ok(if got == ka.expected {
200 CANONICAL_PARTITION.to_string()
201 } else {
202 runner.platform().to_string()
203 })
204}
205
206// ── Embedding + tagging (the deterministic execution path) ───────────────────────────────────────
207
208/// Embed `asset_id` under `task`'s canonical model over its decoded pixels and store the vector in
209/// the task's `vec0` partition under `partition` (resolve it with [`resolve_partition`]). Serves
210/// both embedding slots — [`SemanticSearch`](TaskKind::SemanticSearch) and
211/// [`FaceRecognition`](TaskKind::FaceRecognition). Refuses a non-canonical runner before touching
212/// the index. The index is derived state, so no signed manifest is minted (recovery-first: it is
213/// rebuilt by re-running inference).
214pub fn embed_and_store<R: ModelRunner, S: AssetSource>(
215 ws: &S,
216 runner: &R,
217 registry: &Registry,
218 asset_id: &Uuid,
219 task: TaskKind,
220 partition: &str,
221) -> Result<(), OrchestratorError> {
222 require_canonical_runner(runner, registry, task)?;
223 let (model_id, model_version) = runner.model(task).ok_or(RunnerError::Unsupported(task))?;
224 let bytes = ws.read_plaintext(asset_id).map_err(store_err)?;
225 let embedding = first_embedding(runner.embed_image(task, &[Frame::new(&bytes)])?)?;
226 ws.vector_index().insert_embedding(
227 registry,
228 EmbeddingInsert {
229 asset_id: &asset_id.to_string(),
230 task,
231 model_id: &model_id,
232 model_version: &model_version,
233 platform: partition,
234 vector: &embedding,
235 },
236 )?;
237 Ok(())
238}
239
240/// Zero-shot tag `asset_id`: embed the image and each candidate label with the semantic-search
241/// embedder, then add as AI tags every label whose cosine similarity to the image clears
242/// `threshold`. The tags land in the asset's `tags_ai` OR-set as one **signed metadata update**
243/// (never in `tags_user`), each carrying the canonical `(model_id, model_version)`. Returns the
244/// labels assigned. No separate classifier — the semantic embeddings are reused.
245pub fn auto_tag<R: ModelRunner, S: AiTagSink>(
246 ws: &mut S,
247 runner: &R,
248 registry: &Registry,
249 asset_id: &Uuid,
250 vocabulary: &[&str],
251 threshold: f32,
252) -> Result<Vec<String>, OrchestratorError> {
253 let task = TaskKind::SemanticSearch;
254 require_canonical_runner(runner, registry, task)?;
255 let canon = registry
256 .canonical_for(task)
257 .ok_or(OrchestratorError::NoCanonical { task })?;
258
259 let bytes = ws.read_plaintext(asset_id).map_err(store_err)?;
260 let image = first_embedding(runner.embed_image(task, &[Frame::new(&bytes)])?)?;
261 let label_vecs = runner.embed_text(vocabulary)?;
262
263 let mut assigned = Vec::new();
264 let mut ai_tags = Vec::new();
265 for (label, lv) in vocabulary.iter().zip(label_vecs) {
266 if cosine_sim(&image, &lv) >= threshold {
267 assigned.push((*label).to_string());
268 ai_tags.push(AiTag {
269 tag: (*label).to_string(),
270 model_id: canon.model_id.to_string(),
271 model_version: canon.canonical_version.to_string(),
272 });
273 }
274 }
275 ws.add_ai_tags(asset_id, ai_tags).map_err(store_err)?;
276 Ok(assigned)
277}
278
279/// Natural-language search: embed `query` with the semantic-search embedder and return the `k`
280/// nearest assets in `partition`'s **current canonical** version (stale/other-partition vectors are
281/// excluded structurally).
282pub fn semantic_search<R: ModelRunner, S: AssetSource>(
283 ws: &S,
284 runner: &R,
285 registry: &Registry,
286 query: &str,
287 k: usize,
288 partition: &str,
289) -> Result<Vec<KnnHit>, OrchestratorError> {
290 require_canonical_runner(runner, registry, TaskKind::SemanticSearch)?;
291 let qv = first_embedding(runner.embed_text(&[query])?)?;
292 Ok(ws
293 .vector_index()
294 .knn(registry, TaskKind::SemanticSearch, &qv, k, partition)?)
295}
296
297/// Cosine similarity of two equal-length vectors (`0.0` if either is zero or lengths differ). The
298/// embedders normalize their outputs, so this equals the inner product the index ranks by.
299fn cosine_sim(a: &[f32], b: &[f32]) -> f32 {
300 if a.len() != b.len() {
301 return 0.0;
302 }
303 let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
304 let na = a.iter().map(|x| x * x).sum::<f32>().sqrt();
305 let nb = b.iter().map(|x| x * x).sum::<f32>().sqrt();
306 if na == 0.0 || nb == 0.0 {
307 0.0
308 } else {
309 dot / (na * nb)
310 }
311}
312
313// ── Device-bound execution policy (ai.md § Model Batching) ───────────────────────────────────
314
315/// Per-asset execution mode, chosen from available memory at task start.
316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
317pub enum BatchMode {
318 /// One model resident at a time — minimizes peak VRAM at the cost of re-reading assets.
319 Horizontal,
320 /// All models resident per asset — minimizes I/O but risks OOM on mobile.
321 Vertical,
322}
323
324/// Pick the execution mode: go vertical only when the estimated resident set fits the RAM budget;
325/// otherwise stay horizontal to bound peak memory.
326pub fn choose_batch_mode(ram_budget_mb: u64, models_resident_mb: u64) -> BatchMode {
327 if models_resident_mb <= ram_budget_mb {
328 BatchMode::Vertical
329 } else {
330 BatchMode::Horizontal
331 }
332}
333
334/// The micro-batch sizes that keep the NPU cache hot.
335pub const MICRO_BATCH_SIZES: [usize; 3] = [8, 4, 1];
336
337/// The largest micro-batch size (from [`MICRO_BATCH_SIZES`]) that fits both the pending count and
338/// the device `ceiling`. Always at least 1.
339pub fn micro_batch_size(pending: usize, ceiling: usize) -> usize {
340 let cap = pending.min(ceiling);
341 MICRO_BATCH_SIZES
342 .into_iter()
343 .find(|&s| s <= cap)
344 .unwrap_or(1)
345}
346
347/// Whether to pause the pipeline for heat: at or above `threshold_c` the OS may kill the app, so
348/// the pipeline pauses until cooldown.
349pub fn should_pause_for_heat(temp_c: f32, threshold_c: f32) -> bool {
350 temp_c >= threshold_c
351}
352
353#[cfg(test)]
354mod tests;