Skip to main content

smriti/services/
semantic.rs

1//! Semantic image search over local CLIP-style embeddings.
2//!
3//! The database stores only indexing state and vector offsets. The
4//! high-volume embedding payload lives in `.photovault/semantic/...`
5//! beside thumbnails and other per-library cache data.
6
7use std::collections::HashSet;
8use std::fs::{File, OpenOptions};
9use std::io::{Read, Seek, SeekFrom, Write};
10use std::path::{Path, PathBuf};
11use std::sync::atomic::{AtomicBool, Ordering};
12
13use image::{DynamicImage, ImageBuffer, Rgb};
14use rusqlite::{params, Connection};
15use serde::{Deserialize, Serialize};
16use tokenizers::Tokenizer;
17
18use crate::db::connection::library_metadata_dir;
19use crate::ml::OnnxRuntime;
20use crate::services::image_io;
21use crate::services::path_util::safe_join_relative;
22
23pub const SEMANTIC_MODEL_KEY: &str = "immich-app/ViT-B-32-SigLIP2-256__webli";
24pub const SEMANTIC_MODEL_DISPLAY: &str = "ViT-B-32 SigLIP2 256";
25pub const SEMANTIC_MODEL_REVISION: &str = "762c736d366fc253e9453021144f9fe71789b075";
26pub const SEMANTIC_DIM: usize = 768;
27pub const SEMANTIC_CONTEXT_LEN: usize = 64;
28pub const SEMANTIC_TEXT_SEARCH_LIMIT: usize = 250;
29pub const SEMANTIC_TEXT_RESULT_CAP: usize = 80;
30
31const SEMANTIC_TEXT_MIN_SCORE: f32 = 0.06;
32const SEMANTIC_TEXT_MAX_SCORE_DROP: f32 = 0.02;
33const SEMANTIC_TEXT_MIN_SCORE_RATIO: f32 = 0.75;
34
35const MODEL_DIR_NAME: &str = "vit-b-32-siglip2-256-webli";
36const VECTOR_FILE: &str = "vectors.f32";
37const MANIFEST_FILE: &str = "manifest.json";
38
39/// Files are fetched from the pinned revision (the literal must match
40/// `SEMANTIC_MODEL_REVISION`; a test enforces it) and checked against the
41/// SHA-256 digests below, so an upstream change can never silently swap
42/// the model Smriti loads.
43macro_rules! semantic_model_url {
44    ($path:literal) => {
45        concat!(
46            "https://huggingface.co/immich-app/ViT-B-32-SigLIP2-256__webli/resolve/",
47            "762c736d366fc253e9453021144f9fe71789b075/",
48            $path
49        )
50    };
51}
52const VISUAL_MODEL_URL: &str = semantic_model_url!("visual/model.onnx");
53const TEXTUAL_MODEL_URL: &str = semantic_model_url!("textual/model.onnx");
54const TOKENIZER_URL: &str = semantic_model_url!("textual/tokenizer.json");
55const PREPROCESS_URL: &str = semantic_model_url!("visual/preprocess_cfg.json");
56const CONFIG_URL: &str = semantic_model_url!("config.json");
57
58const VISUAL_MODEL_SHA256: &str =
59    "e96b8a3d32ab1b683aa12c45312342b4a10d4befef5f195f5cf84eadf1938696";
60const TEXTUAL_MODEL_SHA256: &str =
61    "ba6e09d2dbb3d7ac0f9e2935676db92dceebddfd06c1462b67019caa90eeea20";
62const TOKENIZER_SHA256: &str = "220c63d496e0c14e63eb656c91e0215e926202e4c74b1f089e09f1920d779b04";
63const PREPROCESS_SHA256: &str = "05d19a2078cf0e1a23807f96d4c2ca4efdda6e95846b87ae2e66dbf554fabf02";
64const CONFIG_SHA256: &str = "13fcc60dc967de86aa8dd831f3d9c65b92ccfa87997f448fad08b0d1fad2b11f";
65
66const VISUAL_MODEL_BYTES: u64 = 378_359_772;
67const TEXTUAL_MODEL_BYTES: u64 = 1_129_435_819;
68const TOKENIZER_BYTES: u64 = 34_362_885;
69const PREPROCESS_BYTES: u64 = 154;
70const CONFIG_BYTES: u64 = 551;
71
72/// Total network payload for the optional local visual-search model pack.
73/// Exposed so setup surfaces can accurately disclose the one-time download.
74pub const SEMANTIC_MODEL_DOWNLOAD_BYTES: u64 =
75    VISUAL_MODEL_BYTES + TEXTUAL_MODEL_BYTES + TOKENIZER_BYTES + PREPROCESS_BYTES + CONFIG_BYTES;
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct SemanticStatus {
79    pub model_key: String,
80    pub display_name: String,
81    pub model_dir: String,
82    pub assets_installed: bool,
83    pub onnx_runtime_installed: bool,
84    pub indexed_photos: u64,
85    pub pending_photos: u64,
86    pub failed_photos: u64,
87    pub vector_bytes: u64,
88}
89
90#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
91pub struct SemanticIndexStats {
92    pub indexed: u64,
93    pub pending: u64,
94    pub failed: u64,
95}
96
97#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
98pub struct SemanticIndexBatchOutcome {
99    pub processed: u64,
100    pub indexed: u64,
101    pub failed: u64,
102    pub done: bool,
103}
104
105#[derive(Debug, Clone)]
106pub struct SemanticCandidate {
107    pub photo_id: i64,
108    pub score: f32,
109}
110
111#[derive(Debug, Clone, Serialize, Deserialize)]
112struct VectorManifest {
113    model_key: String,
114    revision: String,
115    dim: usize,
116    vector_count: u64,
117}
118
119#[derive(Debug, Clone)]
120struct SemanticAssetPaths {
121    root: PathBuf,
122    visual_model: PathBuf,
123    textual_model: PathBuf,
124    tokenizer: PathBuf,
125    preprocess: PathBuf,
126    config: PathBuf,
127}
128
129impl SemanticAssetPaths {
130    fn in_root(root: PathBuf) -> Self {
131        let model_root = root.join("models").join("semantic").join(MODEL_DIR_NAME);
132        Self {
133            visual_model: model_root.join("visual").join("model.onnx"),
134            textual_model: model_root.join("textual").join("model.onnx"),
135            tokenizer: model_root.join("textual").join("tokenizer.json"),
136            preprocess: model_root.join("visual").join("preprocess_cfg.json"),
137            config: model_root.join("config.json"),
138            root: model_root,
139        }
140    }
141
142    fn installed(&self) -> bool {
143        self.download_bytes_remaining() == 0
144    }
145
146    fn download_bytes_remaining(&self) -> u64 {
147        [
148            (&self.visual_model, VISUAL_MODEL_BYTES),
149            (&self.textual_model, TEXTUAL_MODEL_BYTES),
150            (&self.tokenizer, TOKENIZER_BYTES),
151            (&self.preprocess, PREPROCESS_BYTES),
152            (&self.config, CONFIG_BYTES),
153        ]
154        .into_iter()
155        .filter_map(|(path, size)| {
156            (!std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() == size)).then_some(size)
157        })
158        .sum()
159    }
160}
161
162pub struct SemanticSearchService {
163    drive_root: PathBuf,
164}
165
166#[derive(Default)]
167pub struct SemanticIndexCache {
168    revision: i64,
169    index: Option<SemanticVectorIndex>,
170}
171
172struct SemanticVectorIndex {
173    photo_ids: Vec<i64>,
174    vectors: Vec<Vec<f32>>,
175}
176
177impl SemanticVectorIndex {
178    /// The `limit` closest photos to `query`, only among `within` if given.
179    fn search(
180        &self,
181        query: &[f32],
182        limit: usize,
183        within: Option<&HashSet<i64>>,
184    ) -> Vec<SemanticCandidate> {
185        if self.photo_ids.is_empty() || limit == 0 {
186            return Vec::new();
187        }
188        let mut candidates: Vec<_> = self
189            .vectors
190            .iter()
191            .zip(&self.photo_ids)
192            .filter(|(_, photo_id)| within.is_none_or(|w| w.contains(photo_id)))
193            .map(|(vector, photo_id)| SemanticCandidate {
194                photo_id: *photo_id,
195                score: cosine(query, vector).clamp(-1.0, 1.0),
196            })
197            .collect();
198        let keep = limit.min(candidates.len());
199        if keep == 0 {
200            return Vec::new();
201        }
202        candidates.select_nth_unstable_by(keep - 1, |a, b| {
203            b.score
204                .total_cmp(&a.score)
205                .then_with(|| a.photo_id.cmp(&b.photo_id))
206        });
207        candidates.truncate(keep);
208        candidates.sort_by(|a, b| {
209            b.score
210                .total_cmp(&a.score)
211                .then_with(|| a.photo_id.cmp(&b.photo_id))
212        });
213        candidates
214    }
215}
216
217impl SemanticSearchService {
218    pub fn new(drive_root: impl Into<PathBuf>) -> Self {
219        Self {
220            drive_root: drive_root.into(),
221        }
222    }
223
224    pub fn status(&self, conn: &Connection) -> rusqlite::Result<SemanticStatus> {
225        let stats = self.index_stats(conn)?;
226        let store = VectorStore::new(&self.drive_root)?;
227        let assets = Self::find_assets();
228        Ok(SemanticStatus {
229            model_key: SEMANTIC_MODEL_KEY.to_string(),
230            display_name: SEMANTIC_MODEL_DISPLAY.to_string(),
231            model_dir: assets
232                .as_ref()
233                .map(|a| a.root.display().to_string())
234                .unwrap_or_else(|| Self::default_asset_paths().root.display().to_string()),
235            assets_installed: assets.as_ref().is_some_and(SemanticAssetPaths::installed),
236            onnx_runtime_installed: crate::bootstrap::onnx_runtime_exists(),
237            indexed_photos: stats.indexed,
238            pending_photos: stats.pending,
239            failed_photos: stats.failed,
240            vector_bytes: std::fs::metadata(store.vector_path())
241                .map(|m| m.len())
242                .unwrap_or(0),
243        })
244    }
245
246    /// Whether every file needed for local visual search is present.
247    pub fn model_assets_installed() -> bool {
248        Self::find_assets().is_some_and(|paths| paths.installed())
249    }
250
251    pub fn model_download_bytes_remaining() -> u64 {
252        if Self::model_assets_installed() {
253            return 0;
254        }
255        Self::default_asset_paths().download_bytes_remaining()
256    }
257
258    pub async fn install_model_assets<F>(
259        cancel: Option<&AtomicBool>,
260        mut progress: F,
261    ) -> Result<(), String>
262    where
263        F: FnMut(&str, u64, Option<u64>) + Send,
264    {
265        if Self::model_assets_installed() {
266            return Ok(());
267        }
268        let paths = Self::default_asset_paths();
269        let assets = [
270            SemanticDownload {
271                url: VISUAL_MODEL_URL,
272                destination: paths.visual_model,
273                stage: "visual-model",
274                expected_size: VISUAL_MODEL_BYTES,
275                sha256: VISUAL_MODEL_SHA256,
276            },
277            SemanticDownload {
278                url: TEXTUAL_MODEL_URL,
279                destination: paths.textual_model,
280                stage: "text-model",
281                expected_size: TEXTUAL_MODEL_BYTES,
282                sha256: TEXTUAL_MODEL_SHA256,
283            },
284            SemanticDownload {
285                url: TOKENIZER_URL,
286                destination: paths.tokenizer,
287                stage: "tokenizer",
288                expected_size: TOKENIZER_BYTES,
289                sha256: TOKENIZER_SHA256,
290            },
291            SemanticDownload {
292                url: PREPROCESS_URL,
293                destination: paths.preprocess,
294                stage: "preprocess",
295                expected_size: PREPROCESS_BYTES,
296                sha256: PREPROCESS_SHA256,
297            },
298            SemanticDownload {
299                url: CONFIG_URL,
300                destination: paths.config,
301                stage: "config",
302                expected_size: CONFIG_BYTES,
303                sha256: CONFIG_SHA256,
304            },
305        ];
306        let total = SEMANTIC_MODEL_DOWNLOAD_BYTES;
307        let mut completed = 0;
308        for asset in assets {
309            completed = download_asset(asset, completed, total, cancel, &mut progress).await?;
310        }
311        Ok(())
312    }
313
314    pub fn index_stats(&self, conn: &Connection) -> rusqlite::Result<SemanticIndexStats> {
315        let indexed = count_state(conn, "indexed")?;
316        let failed = count_state(conn, "failed")?;
317        let total_active: u64 = conn.query_row(
318            "SELECT COUNT(*) FROM photos WHERE is_trashed = FALSE",
319            [],
320            |r| r.get::<_, i64>(0),
321        )? as u64;
322        let pending = total_active.saturating_sub(indexed + failed);
323        Ok(SemanticIndexStats {
324            indexed,
325            pending,
326            failed,
327        })
328    }
329
330    pub fn next_pending_batch(
331        &self,
332        conn: &Connection,
333        limit: usize,
334    ) -> rusqlite::Result<Vec<SemanticPhotoInput>> {
335        let mut stmt = conn.prepare(
336            "SELECT p.id, p.file_path, p.thumbnail_path, p.media_type
337             FROM photos p
338             LEFT JOIN semantic_index_state s
339               ON s.photo_id = p.id AND s.model_key = ?1
340             WHERE p.is_trashed = FALSE
341               AND COALESCE(s.status, 'pending') = 'pending'
342             ORDER BY p.date_taken IS NULL ASC, p.date_taken DESC, p.id DESC
343             LIMIT ?2",
344        )?;
345        let rows = stmt.query_map(params![SEMANTIC_MODEL_KEY, limit as i64], |row| {
346            Ok(SemanticPhotoInput {
347                photo_id: row.get(0)?,
348                file_path: row.get(1)?,
349                thumbnail_path: row.get(2)?,
350                media_type: row.get(3)?,
351            })
352        })?;
353        rows.collect()
354    }
355
356    pub fn mark_failed(conn: &Connection, photo_id: i64, error: &str) -> rusqlite::Result<()> {
357        conn.execute(
358            "INSERT INTO semantic_index_state
359                (photo_id, model_key, status, attempts, last_error)
360             VALUES (?1, ?2, 'failed', 1, ?3)
361             ON CONFLICT(photo_id, model_key) DO UPDATE SET
362                status = 'failed',
363                attempts = attempts + 1,
364                last_error = excluded.last_error,
365                updated_at = CURRENT_TIMESTAMP",
366            params![photo_id, SEMANTIC_MODEL_KEY, truncate_error(error)],
367        )?;
368        Ok(())
369    }
370
371    pub fn index_next_batch(
372        &self,
373        conn: &mut Connection,
374        runner: &mut SemanticImageRunner,
375        limit: usize,
376        cancel: &AtomicBool,
377    ) -> Result<SemanticIndexBatchOutcome, String> {
378        let batch = self
379            .next_pending_batch(conn, limit)
380            .map_err(|e| e.to_string())?;
381        if batch.is_empty() {
382            return Ok(SemanticIndexBatchOutcome {
383                done: true,
384                ..Default::default()
385            });
386        }
387
388        let mut indexed = Vec::new();
389        let mut failed = Vec::new();
390        for photo in &batch {
391            if cancel.load(Ordering::Relaxed) {
392                return Err("Semantic indexing cancelled".into());
393            }
394            match photo
395                .source_path(&self.drive_root)
396                .and_then(|path| runner.embed_image_path(&path))
397            {
398                Ok(vector) => indexed.push((photo.photo_id, vector)),
399                Err(err) => failed.push((photo.photo_id, err)),
400            }
401        }
402
403        self.record_index_batch(conn, &indexed, &failed)
404            .map_err(|e| e.to_string())?;
405
406        Ok(SemanticIndexBatchOutcome {
407            processed: batch.len() as u64,
408            indexed: indexed.len() as u64,
409            failed: failed.len() as u64,
410            done: false,
411        })
412    }
413
414    fn record_index_batch(
415        &self,
416        conn: &mut Connection,
417        indexed: &[(i64, Vec<f32>)],
418        failed: &[(i64, String)],
419    ) -> rusqlite::Result<()> {
420        let offsets = if indexed.is_empty() {
421            Vec::new()
422        } else {
423            let mut store = VectorStore::new(&self.drive_root)?;
424            store.append_many(indexed.iter().map(|(_, vector)| vector.as_slice()))?
425        };
426
427        let tx = conn.transaction()?;
428        for ((photo_id, vector), offset) in indexed.iter().zip(offsets.iter()) {
429            tx.execute(
430                "INSERT INTO semantic_index_state
431                    (photo_id, model_key, status, vector_offset, vector_dim, attempts, last_error, indexed_at)
432                 VALUES (?1, ?2, 'indexed', ?3, ?4, 0, NULL, CURRENT_TIMESTAMP)
433                 ON CONFLICT(photo_id, model_key) DO UPDATE SET
434                    status = 'indexed',
435                    vector_offset = excluded.vector_offset,
436                    vector_dim = excluded.vector_dim,
437                    attempts = 0,
438                    last_error = NULL,
439                    indexed_at = CURRENT_TIMESTAMP,
440                    updated_at = CURRENT_TIMESTAMP",
441                params![
442                    photo_id,
443                    SEMANTIC_MODEL_KEY,
444                    *offset as i64,
445                    vector.len() as i64
446                ],
447            )?;
448        }
449        for (photo_id, err) in failed {
450            tx.execute(
451                "INSERT INTO semantic_index_state
452                    (photo_id, model_key, status, attempts, last_error)
453                 VALUES (?1, ?2, 'failed', 1, ?3)
454                 ON CONFLICT(photo_id, model_key) DO UPDATE SET
455                    status = 'failed',
456                    attempts = attempts + 1,
457                    last_error = excluded.last_error,
458                    updated_at = CURRENT_TIMESTAMP",
459                params![photo_id, SEMANTIC_MODEL_KEY, truncate_error(err)],
460            )?;
461        }
462        tx.commit()
463    }
464
465    pub fn search_text_cached(
466        &self,
467        conn: &Connection,
468        cache: &mut SemanticIndexCache,
469        runner: &mut SemanticModelRunner,
470        query: &str,
471        limit: usize,
472    ) -> Result<Vec<SemanticCandidate>, String> {
473        let vector = runner.embed_text(query)?;
474        self.search_vector_cached(conn, cache, &vector, limit)
475    }
476
477    pub fn search_vector_cached(
478        &self,
479        conn: &Connection,
480        cache: &mut SemanticIndexCache,
481        query: &[f32],
482        limit: usize,
483    ) -> Result<Vec<SemanticCandidate>, String> {
484        self.search_vector_cached_within(conn, cache, query, limit, None)
485    }
486
487    /// [`Self::search_vector_cached`], scored only among `within` when given:
488    /// a search with people or dates looks for the best matches among
489    /// those photos, not for those photos among the library's best.
490    pub fn search_vector_cached_within(
491        &self,
492        conn: &Connection,
493        cache: &mut SemanticIndexCache,
494        query: &[f32],
495        limit: usize,
496        within: Option<&HashSet<i64>>,
497    ) -> Result<Vec<SemanticCandidate>, String> {
498        if query.len() != SEMANTIC_DIM {
499            return Ok(Vec::new());
500        }
501        let revision = conn
502            .query_row(
503                "SELECT revision FROM semantic_revision WHERE id = 1",
504                [],
505                |row| row.get(0),
506            )
507            .map_err(|e| e.to_string())?;
508        if cache.index.is_none() || cache.revision != revision {
509            cache.index = Some(self.build_vector_index(conn)?);
510            cache.revision = revision;
511        }
512        Ok(cache
513            .index
514            .as_ref()
515            .map(|idx| idx.search(query, limit, within))
516            .unwrap_or_default())
517    }
518
519    #[cfg(test)]
520    fn search_vector(
521        &self,
522        conn: &Connection,
523        query: &[f32],
524        limit: usize,
525    ) -> Result<Vec<SemanticCandidate>, String> {
526        Ok(self.build_vector_index(conn)?.search(query, limit, None))
527    }
528
529    fn build_vector_index(&self, conn: &Connection) -> Result<SemanticVectorIndex, String> {
530        // Keep normalized vectors directly. Building an approximate graph on
531        // every library open cost tens of seconds for only a few thousand
532        // photos; a flat cosine scan is exact and immediately usable.
533        let rows = self.load_index_rows(conn).map_err(|e| e.to_string())?;
534        let mut photo_ids = Vec::with_capacity(rows.len());
535        let mut vectors = Vec::with_capacity(rows.len());
536        for row in rows {
537            photo_ids.push(row.photo_id);
538            vectors.push(row.vector);
539        }
540        Ok(SemanticVectorIndex { photo_ids, vectors })
541    }
542
543    #[cfg(test)]
544    fn vector_for_photo(
545        &self,
546        conn: &Connection,
547        photo_id: i64,
548    ) -> Result<Option<Vec<f32>>, String> {
549        use rusqlite::OptionalExtension;
550        let row: Option<(i64, i64)> = conn
551            .query_row(
552                "SELECT vector_offset, vector_dim
553                 FROM semantic_index_state
554                 WHERE photo_id = ?1 AND model_key = ?2 AND status = 'indexed'",
555                params![photo_id, SEMANTIC_MODEL_KEY],
556                |r| Ok((r.get(0)?, r.get(1)?)),
557            )
558            .optional()
559            .map_err(|e| e.to_string())?;
560        let Some((offset, dim)) = row else {
561            return Ok(None);
562        };
563        if dim != SEMANTIC_DIM as i64 || offset < 0 {
564            return Ok(None);
565        }
566        let store = VectorStore::new(&self.drive_root).map_err(|e| e.to_string())?;
567        store
568            .read(offset as u64, dim as usize)
569            .map(Some)
570            .map_err(|e| e.to_string())
571    }
572
573    fn load_index_rows(&self, conn: &Connection) -> rusqlite::Result<Vec<IndexRow>> {
574        let mut stmt = conn.prepare(
575            "SELECT s.photo_id, s.vector_offset, s.vector_dim
576             FROM semantic_index_state s
577             JOIN photos p ON p.id = s.photo_id
578             WHERE s.model_key = ?1
579               AND s.status = 'indexed'
580               AND s.vector_dim = ?2
581               AND p.is_trashed = FALSE
582             ORDER BY s.vector_offset",
583        )?;
584        let rows = stmt.query_map(params![SEMANTIC_MODEL_KEY, SEMANTIC_DIM as i64], |row| {
585            Ok((
586                row.get::<_, i64>(0)?,
587                row.get::<_, i64>(1)?,
588                row.get::<_, i64>(2)?,
589            ))
590        })?;
591        let store = VectorStore::new(&self.drive_root)?;
592        let mut file = match File::open(store.vector_path()) {
593            Ok(file) => std::io::BufReader::new(file),
594            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
595            Err(error) => return Err(rusqlite::Error::ToSqlConversionFailure(Box::new(error))),
596        };
597        let mut out = Vec::new();
598        for row in rows {
599            let (photo_id, offset, dim) = row?;
600            if let Ok(vector) = VectorStore::read_from(&mut file, offset as u64, dim as usize) {
601                out.push(IndexRow { photo_id, vector });
602            }
603        }
604        Ok(out)
605    }
606
607    fn find_assets() -> Option<SemanticAssetPaths> {
608        crate::bootstrap::asset_roots()
609            .into_iter()
610            .map(SemanticAssetPaths::in_root)
611            .find(SemanticAssetPaths::installed)
612    }
613
614    pub fn image_runner() -> Result<SemanticImageRunner, String> {
615        let paths = Self::find_assets().ok_or_else(|| {
616            format!(
617                "Semantic search model is not installed. Install {} from Settings.",
618                SEMANTIC_MODEL_DISPLAY
619            )
620        })?;
621        if !crate::bootstrap::onnx_runtime_exists() {
622            return Err(
623                "ONNX Runtime is missing. Enable visual search in Search or Settings before indexing."
624                    .into(),
625            );
626        }
627        let rt = OnnxRuntime::init().map_err(|e| e.to_string())?;
628        SemanticImageRunner::new(&rt, paths)
629    }
630
631    pub fn model_runner() -> Result<SemanticModelRunner, String> {
632        let paths = Self::find_assets().ok_or_else(|| {
633            format!(
634                "Semantic search model is not installed. Install {} from Settings.",
635                SEMANTIC_MODEL_DISPLAY
636            )
637        })?;
638        if !crate::bootstrap::onnx_runtime_exists() {
639            return Err(
640                "ONNX Runtime is missing. Enable visual search in Search or Settings before indexing."
641                    .into(),
642            );
643        }
644        let rt = OnnxRuntime::init().map_err(|e| e.to_string())?;
645        SemanticModelRunner::new(&rt, paths)
646    }
647
648    fn default_asset_paths() -> SemanticAssetPaths {
649        SemanticAssetPaths::in_root(crate::bootstrap::default_asset_install_dir())
650    }
651}
652
653#[derive(Debug, Clone)]
654pub struct SemanticPhotoInput {
655    pub photo_id: i64,
656    pub file_path: String,
657    pub thumbnail_path: Option<String>,
658    pub media_type: String,
659}
660
661impl SemanticPhotoInput {
662    pub fn source_path(&self, drive_root: &Path) -> Result<PathBuf, String> {
663        if let Some(thumbnail) = &self.thumbnail_path {
664            match safe_join_relative(drive_root, thumbnail) {
665                Ok(path) if path.exists() => return Ok(path),
666                Ok(_) if self.media_type == "video" => {
667                    return Err("video poster thumbnail is not ready".into());
668                }
669                Err(e) if self.media_type == "video" => {
670                    return Err(format!("invalid video thumbnail path: {e}"));
671                }
672                _ => {}
673            }
674        }
675        if self.media_type == "video" {
676            return Err("video poster thumbnail is not ready".into());
677        }
678        safe_join_relative(drive_root, &self.file_path)
679            .map_err(|e| format!("invalid photo path: {e}"))
680    }
681}
682
683struct IndexRow {
684    photo_id: i64,
685    vector: Vec<f32>,
686}
687
688pub struct SemanticImageRunner {
689    visual: ort::session::Session,
690}
691
692impl SemanticImageRunner {
693    fn new(rt: &OnnxRuntime, paths: SemanticAssetPaths) -> Result<Self, String> {
694        let visual = rt
695            .load_model_with_threads(&paths.visual_model, 1)
696            .map_err(|e| format!("visual model load failed: {e}"))?;
697        Ok(Self { visual })
698    }
699
700    pub fn embed_image_path(&mut self, path: &Path) -> Result<Vec<f32>, String> {
701        let img = image_io::open_image(path)?;
702        self.embed_image(&img)
703    }
704
705    pub fn embed_image(&mut self, img: &DynamicImage) -> Result<Vec<f32>, String> {
706        let tensor = preprocess_image(img);
707        let input = ort::value::TensorRef::<f32>::from_array_view((
708            vec![1, 3, 256, 256],
709            tensor.as_slice(),
710        ))
711        .map_err(|e| e.to_string())?;
712        let outputs = self
713            .visual
714            .run(ort::inputs![input])
715            .map_err(|e| format!("visual inference failed: {e}"))?;
716        extract_normalized_output(outputs)
717    }
718}
719
720pub struct SemanticModelRunner {
721    textual: ort::session::Session,
722    tokenizer: Tokenizer,
723}
724
725impl SemanticModelRunner {
726    fn new(_rt: &OnnxRuntime, paths: SemanticAssetPaths) -> Result<Self, String> {
727        // Text search is a latency-sensitive, single-input workload.  Trying
728        // DirectML first made Windows compile a ~1.1 GB graph every launch;
729        // on ordinary machines that kept Search metadata-only for close to a
730        // minute and also competed with the UI.  CPU session creation is much
731        // cheaper here and one query does not benefit from GPU setup.
732        let textual = OnnxRuntime::load_cpu_model_for_interactive(&paths.textual_model)
733            .map_err(|e| format!("text model load failed: {e}"))?;
734        let tokenizer = Tokenizer::from_file(&paths.tokenizer)
735            .map_err(|e| format!("tokenizer load failed: {e}"))?;
736        Ok(Self { textual, tokenizer })
737    }
738
739    pub fn embed_text(&mut self, text: &str) -> Result<Vec<f32>, String> {
740        let encoding = self
741            .tokenizer
742            .encode(text, true)
743            .map_err(|e| format!("tokenization failed: {e}"))?;
744        let ids = padded_text_context(encoding.get_ids());
745        let input_ids = ort::value::TensorRef::<i32>::from_array_view((
746            vec![1, SEMANTIC_CONTEXT_LEN as i64],
747            ids.as_slice(),
748        ))
749        .map_err(|e| e.to_string())?;
750        let outputs = self
751            .textual
752            .run(ort::inputs![input_ids])
753            .map_err(|e| format!("text inference failed: {e}"))?;
754        extract_normalized_output(outputs)
755    }
756}
757
758fn padded_text_context(token_ids: &[u32]) -> Vec<i32> {
759    let mut ids = vec![0i32; SEMANTIC_CONTEXT_LEN];
760    for (idx, id) in token_ids.iter().take(SEMANTIC_CONTEXT_LEN).enumerate() {
761        ids[idx] = *id as i32;
762    }
763    ids
764}
765
766fn preprocess_image(img: &DynamicImage) -> Vec<f32> {
767    let resized = img.resize_exact(256, 256, image::imageops::FilterType::CatmullRom);
768    let rgb: ImageBuffer<Rgb<u8>, Vec<u8>> = resized.to_rgb8();
769    let mut out = vec![0.0f32; 3 * 256 * 256];
770    let hw = 256 * 256;
771    for y in 0..256u32 {
772        for x in 0..256u32 {
773            let p = rgb.get_pixel(x, y);
774            let idx = (y * 256 + x) as usize;
775            out[idx] = (p[0] as f32 / 255.0 - 0.5) / 0.5;
776            out[hw + idx] = (p[1] as f32 / 255.0 - 0.5) / 0.5;
777            out[2 * hw + idx] = (p[2] as f32 / 255.0 - 0.5) / 0.5;
778        }
779    }
780    out
781}
782
783fn extract_normalized_output(outputs: ort::session::SessionOutputs) -> Result<Vec<f32>, String> {
784    let (_name, output) = outputs
785        .iter()
786        .next()
787        .ok_or_else(|| "model produced no output tensor".to_string())?;
788    let (_shape, data) = output
789        .try_extract_tensor::<f32>()
790        .map_err(|e| e.to_string())?;
791    let mut vector = data.to_vec();
792    if vector.len() != SEMANTIC_DIM {
793        return Err(format!(
794            "unexpected semantic embedding dimension: expected {}, got {}",
795            SEMANTIC_DIM,
796            vector.len()
797        ));
798    }
799    normalize_in_place(&mut vector);
800    Ok(vector)
801}
802
803fn normalize_in_place(v: &mut [f32]) {
804    let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
805    if norm > 0.0 {
806        for x in v {
807            *x /= norm;
808        }
809    }
810}
811
812struct VectorStore {
813    root: PathBuf,
814}
815
816impl VectorStore {
817    fn new(drive_root: &Path) -> rusqlite::Result<Self> {
818        let root = library_metadata_dir(drive_root)
819            .join("semantic")
820            .join(MODEL_DIR_NAME);
821        std::fs::create_dir_all(&root)
822            .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
823        let manifest = root.join(MANIFEST_FILE);
824        if !manifest.exists() {
825            let data = serde_json::to_vec_pretty(&VectorManifest {
826                model_key: SEMANTIC_MODEL_KEY.to_string(),
827                revision: SEMANTIC_MODEL_REVISION.to_string(),
828                dim: SEMANTIC_DIM,
829                vector_count: 0,
830            })
831            .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
832            std::fs::write(&manifest, data)
833                .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
834        }
835        Ok(Self { root })
836    }
837
838    fn vector_path(&self) -> PathBuf {
839        self.root.join(VECTOR_FILE)
840    }
841
842    fn append_many<'a, I>(&mut self, vectors: I) -> rusqlite::Result<Vec<u64>>
843    where
844        I: IntoIterator<Item = &'a [f32]>,
845    {
846        let vectors = vectors.into_iter().collect::<Vec<_>>();
847        if vectors.is_empty() {
848            return Ok(Vec::new());
849        }
850        for vector in &vectors {
851            if vector.len() != SEMANTIC_DIM {
852                return Err(rusqlite::Error::InvalidParameterName(format!(
853                    "semantic vector dimension {} != {}",
854                    vector.len(),
855                    SEMANTIC_DIM
856                )));
857            }
858        }
859        let path = self.vector_path();
860        let mut file = OpenOptions::new()
861            .create(true)
862            .append(true)
863            .read(true)
864            .open(&path)
865            .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
866        let mut offset = file
867            .seek(SeekFrom::End(0))
868            .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
869        let mut offsets = Vec::with_capacity(vectors.len());
870        let mut bytes = Vec::with_capacity(SEMANTIC_DIM * 4);
871        for vector in vectors {
872            offsets.push(offset);
873            bytes.clear();
874            for value in vector {
875                bytes.extend_from_slice(&value.to_le_bytes());
876            }
877            file.write_all(&bytes)
878                .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
879            offset += (SEMANTIC_DIM * 4) as u64;
880        }
881        file.sync_data()
882            .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
883        self.bump_manifest_by(offsets.len() as u64)?;
884        Ok(offsets)
885    }
886
887    #[cfg(test)]
888    fn read(&self, offset: u64, dim: usize) -> std::io::Result<Vec<f32>> {
889        let mut file = File::open(self.vector_path())?;
890        Self::read_from(&mut file, offset, dim)
891    }
892
893    fn read_from(
894        file: &mut (impl Read + Seek),
895        offset: u64,
896        dim: usize,
897    ) -> std::io::Result<Vec<f32>> {
898        if file.stream_position()? != offset {
899            file.seek(SeekFrom::Start(offset))?;
900        }
901        let mut bytes = vec![0u8; dim * 4];
902        file.read_exact(&mut bytes)?;
903        Ok(bytes
904            .as_chunks::<4>()
905            .0
906            .iter()
907            .map(|c| f32::from_le_bytes(*c))
908            .collect())
909    }
910
911    fn bump_manifest_by(&self, count: u64) -> rusqlite::Result<()> {
912        let path = self.root.join(MANIFEST_FILE);
913        let mut manifest: VectorManifest = std::fs::read(&path)
914            .ok()
915            .and_then(|b| serde_json::from_slice(&b).ok())
916            .unwrap_or(VectorManifest {
917                model_key: SEMANTIC_MODEL_KEY.to_string(),
918                revision: SEMANTIC_MODEL_REVISION.to_string(),
919                dim: SEMANTIC_DIM,
920                vector_count: 0,
921            });
922        manifest.vector_count += count;
923        let data = serde_json::to_vec_pretty(&manifest)
924            .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
925        std::fs::write(path, data)
926            .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
927        Ok(())
928    }
929}
930
931fn count_state(conn: &Connection, status: &str) -> rusqlite::Result<u64> {
932    conn.query_row(
933        "SELECT COUNT(*)
934         FROM semantic_index_state s
935         JOIN photos p ON p.id = s.photo_id
936         WHERE s.model_key = ?1
937           AND s.status = ?2
938           AND p.is_trashed = FALSE",
939        params![SEMANTIC_MODEL_KEY, status],
940        |r| r.get::<_, i64>(0),
941    )
942    .map(|v| v as u64)
943}
944
945fn truncate_error(error: &str) -> String {
946    error.chars().take(500).collect()
947}
948
949struct SemanticDownload {
950    url: &'static str,
951    stage: &'static str,
952    destination: PathBuf,
953    expected_size: u64,
954    sha256: &'static str,
955}
956
957async fn download_asset<F>(
958    asset: SemanticDownload,
959    completed_before: u64,
960    total_bytes: u64,
961    cancel: Option<&AtomicBool>,
962    progress: &mut F,
963) -> Result<u64, String>
964where
965    F: FnMut(&str, u64, Option<u64>) + Send,
966{
967    if asset
968        .destination
969        .metadata()
970        .is_ok_and(|metadata| metadata.is_file() && metadata.len() == asset.expected_size)
971    {
972        let completed = completed_before + asset.expected_size;
973        progress(asset.stage, completed, Some(total_bytes));
974        return Ok(completed);
975    }
976    if asset.destination.exists() {
977        tokio::fs::remove_file(&asset.destination)
978            .await
979            .map_err(|e| format!("failed replacing {}: {e}", asset.destination.display()))?;
980    }
981    if let Some(parent) = asset.destination.parent() {
982        tokio::fs::create_dir_all(parent)
983            .await
984            .map_err(|e| format!("failed creating {}: {e}", parent.display()))?;
985    }
986    if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
987        return Err("Semantic model install cancelled".into());
988    }
989
990    let response = reqwest::get(asset.url)
991        .await
992        .map_err(|e| format!("download request failed for {}: {e}", asset.url))?;
993    if !response.status().is_success() {
994        return Err(format!(
995            "download failed for {}: HTTP {}",
996            asset.url,
997            response.status()
998        ));
999    }
1000    let expected = response.content_length().unwrap_or(asset.expected_size);
1001    let tmp = asset.destination.with_extension("tmp");
1002    let mut file = tokio::fs::File::create(&tmp)
1003        .await
1004        .map_err(|e| format!("failed writing {}: {e}", tmp.display()))?;
1005    let mut downloaded = 0u64;
1006    let mut last_emit = 0u64;
1007    let mut stream = response.bytes_stream();
1008    let mut hasher = <sha2::Sha256 as sha2::Digest>::new();
1009
1010    use futures::StreamExt;
1011    while let Some(chunk) = stream.next().await {
1012        if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
1013            let _ = tokio::fs::remove_file(&tmp).await;
1014            return Err("Semantic model install cancelled".into());
1015        }
1016        let chunk = chunk.map_err(|e| format!("download body failed for {}: {e}", asset.url))?;
1017        tokio::io::AsyncWriteExt::write_all(&mut file, &chunk)
1018            .await
1019            .map_err(|e| format!("failed writing {}: {e}", tmp.display()))?;
1020        sha2::Digest::update(&mut hasher, &chunk);
1021        downloaded += chunk.len() as u64;
1022        if downloaded.saturating_sub(last_emit) >= 1_048_576 || downloaded >= expected {
1023            last_emit = downloaded;
1024            progress(
1025                asset.stage,
1026                completed_before + downloaded.min(asset.expected_size),
1027                Some(total_bytes),
1028            );
1029        }
1030    }
1031    tokio::io::AsyncWriteExt::flush(&mut file)
1032        .await
1033        .map_err(|e| format!("failed flushing {}: {e}", tmp.display()))?;
1034    drop(file);
1035    if downloaded != asset.expected_size {
1036        let _ = tokio::fs::remove_file(&tmp).await;
1037        return Err(format!(
1038            "download size mismatch for {}: expected {} bytes, got {}",
1039            asset.url, asset.expected_size, downloaded
1040        ));
1041    }
1042    let actual = format!("{:x}", sha2::Digest::finalize(hasher));
1043    if !actual.eq_ignore_ascii_case(asset.sha256) {
1044        let _ = tokio::fs::remove_file(&tmp).await;
1045        return Err(format!(
1046            "checksum mismatch for {}: expected {}, got {actual}",
1047            asset.url, asset.sha256
1048        ));
1049    }
1050    tokio::fs::rename(&tmp, &asset.destination)
1051        .await
1052        .map_err(|e| format!("failed moving {}: {e}", asset.destination.display()))?;
1053    let completed = completed_before + asset.expected_size;
1054    progress(asset.stage, completed, Some(total_bytes));
1055    Ok(completed)
1056}
1057
1058pub fn relevant_text_search_candidates(
1059    candidates: Vec<SemanticCandidate>,
1060) -> Vec<SemanticCandidate> {
1061    relevant_candidates_up_to(candidates, SEMANTIC_TEXT_RESULT_CAP)
1062}
1063
1064/// [`relevant_text_search_candidates`] with a chosen cap. Searches within
1065/// a filtered set keep more: every match there is already one of the
1066/// user's people or dates. The absolute floor still applies, so a set with
1067/// nothing like the query returns nothing rather than its least-bad photos.
1068pub fn relevant_candidates_up_to(
1069    mut candidates: Vec<SemanticCandidate>,
1070    cap: usize,
1071) -> Vec<SemanticCandidate> {
1072    candidates.sort_by(|a, b| {
1073        b.score
1074            .partial_cmp(&a.score)
1075            .unwrap_or(std::cmp::Ordering::Equal)
1076    });
1077    let Some(top) = candidates.first().map(|c| c.score) else {
1078        return Vec::new();
1079    };
1080    if top < SEMANTIC_TEXT_MIN_SCORE {
1081        return Vec::new();
1082    }
1083
1084    let threshold = SEMANTIC_TEXT_MIN_SCORE
1085        .max(top - SEMANTIC_TEXT_MAX_SCORE_DROP)
1086        .max(top * SEMANTIC_TEXT_MIN_SCORE_RATIO);
1087    candidates
1088        .into_iter()
1089        .filter(|c| c.score >= threshold)
1090        .take(cap)
1091        .collect()
1092}
1093
1094pub fn cosine(a: &[f32], b: &[f32]) -> f32 {
1095    if a.len() != b.len() {
1096        return 0.0;
1097    }
1098    let (mut dot, mut aa, mut bb) = (0.0_f32, 0.0_f32, 0.0_f32);
1099    for (&x, &y) in a.iter().zip(b) {
1100        dot += x * y;
1101        aa += x * x;
1102        bb += y * y;
1103    }
1104    let na = aa.sqrt();
1105    let nb = bb.sqrt();
1106    if na > 0.0 && nb > 0.0 {
1107        dot / (na * nb)
1108    } else {
1109        0.0
1110    }
1111}
1112
1113#[cfg(test)]
1114mod tests {
1115    use super::*;
1116    use tempfile::tempdir;
1117
1118    #[test]
1119    fn model_downloads_are_pinned_to_the_reviewed_revision() {
1120        for url in [
1121            VISUAL_MODEL_URL,
1122            TEXTUAL_MODEL_URL,
1123            TOKENIZER_URL,
1124            PREPROCESS_URL,
1125            CONFIG_URL,
1126        ] {
1127            assert!(
1128                url.contains(&format!("/resolve/{SEMANTIC_MODEL_REVISION}/")),
1129                "{url} must use the pinned revision"
1130            );
1131        }
1132        for digest in [
1133            VISUAL_MODEL_SHA256,
1134            TEXTUAL_MODEL_SHA256,
1135            TOKENIZER_SHA256,
1136            PREPROCESS_SHA256,
1137            CONFIG_SHA256,
1138        ] {
1139            assert_eq!(digest.len(), 64);
1140            assert!(digest.bytes().all(|b| b.is_ascii_hexdigit()));
1141        }
1142    }
1143
1144    #[test]
1145    fn truncated_models_are_not_reported_as_installed() {
1146        let temp = tempdir().unwrap();
1147        let paths = SemanticAssetPaths::in_root(temp.path().to_path_buf());
1148        for path in [
1149            &paths.visual_model,
1150            &paths.textual_model,
1151            &paths.tokenizer,
1152            &paths.preprocess,
1153            &paths.config,
1154        ] {
1155            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1156            std::fs::write(path, b"bad download").unwrap();
1157        }
1158        assert!(!paths.installed());
1159        assert_eq!(
1160            paths.download_bytes_remaining(),
1161            SEMANTIC_MODEL_DOWNLOAD_BYTES
1162        );
1163        std::fs::write(&paths.preprocess, vec![0_u8; PREPROCESS_BYTES as usize]).unwrap();
1164        assert_eq!(
1165            paths.download_bytes_remaining(),
1166            SEMANTIC_MODEL_DOWNLOAD_BYTES - PREPROCESS_BYTES
1167        );
1168    }
1169
1170    fn setup_semantic_test_conn() -> Connection {
1171        let conn = Connection::open_in_memory().unwrap();
1172        conn.execute_batch(
1173            "CREATE TABLE photos (
1174                id INTEGER PRIMARY KEY,
1175                file_path TEXT NOT NULL,
1176                thumbnail_path TEXT,
1177                media_type TEXT NOT NULL DEFAULT 'photo',
1178                date_taken TEXT,
1179                is_trashed BOOLEAN NOT NULL DEFAULT FALSE
1180            );
1181            CREATE TABLE semantic_index_state (
1182                photo_id INTEGER NOT NULL,
1183                model_key TEXT NOT NULL,
1184                status TEXT NOT NULL DEFAULT 'pending',
1185                vector_offset INTEGER,
1186                vector_dim INTEGER,
1187                attempts INTEGER NOT NULL DEFAULT 0,
1188                last_error TEXT,
1189                indexed_at TEXT,
1190                updated_at TEXT,
1191                PRIMARY KEY(photo_id, model_key)
1192            );",
1193        )
1194        .unwrap();
1195        conn
1196    }
1197
1198    #[test]
1199    fn vector_store_round_trips_fixed_width_vectors() {
1200        let dir = tempdir().unwrap();
1201        let mut store = VectorStore::new(dir.path()).unwrap();
1202        let mut first = vec![0.0f32; SEMANTIC_DIM];
1203        first[3] = 1.0;
1204        let mut second = vec![0.0f32; SEMANTIC_DIM];
1205        second[9] = 1.0;
1206
1207        let offsets = store
1208            .append_many([first.as_slice(), second.as_slice()])
1209            .unwrap();
1210        let off_a = offsets[0];
1211        let off_b = offsets[1];
1212
1213        assert_eq!(off_a, 0);
1214        assert_eq!(off_b, (SEMANTIC_DIM * 4) as u64);
1215        assert_eq!(store.read(off_a, SEMANTIC_DIM).unwrap(), first);
1216        assert_eq!(store.read(off_b, SEMANTIC_DIM).unwrap(), second);
1217    }
1218
1219    #[test]
1220    #[cfg(feature = "hnsw_clustering")]
1221    fn cached_search_refreshes_replaced_vectors_without_count_change() {
1222        let dir = tempdir().unwrap();
1223        let conn = Connection::open_in_memory().unwrap();
1224        crate::db::create_schema(&conn).unwrap();
1225        conn.execute("INSERT INTO photos(id,file_path,file_name,file_hash,file_size) VALUES(1,'one.jpg','one.jpg','hash',1)", []).unwrap();
1226        let mut first = vec![0.0; SEMANTIC_DIM];
1227        let mut second = first.clone();
1228        first[0] = 1.0;
1229        second[1] = 1.0;
1230        let mut store = VectorStore::new(dir.path()).unwrap();
1231        let offsets = store
1232            .append_many([first.as_slice(), second.as_slice()])
1233            .unwrap();
1234        conn.execute("INSERT INTO semantic_index_state(photo_id,model_key,status,vector_offset,vector_dim) VALUES(1,?1,'indexed',?2,?3)", params![SEMANTIC_MODEL_KEY, offsets[0] as i64, SEMANTIC_DIM as i64]).unwrap();
1235        let service = SemanticSearchService::new(dir.path());
1236        let mut cache = SemanticIndexCache::default();
1237        assert!(
1238            service
1239                .search_vector_cached(&conn, &mut cache, &first, 1)
1240                .unwrap()[0]
1241                .score
1242                > 0.99
1243        );
1244        conn.execute(
1245            "UPDATE semantic_index_state SET vector_offset=?1",
1246            [offsets[1] as i64],
1247        )
1248        .unwrap();
1249        assert!(
1250            service
1251                .search_vector_cached(&conn, &mut cache, &first, 1)
1252                .unwrap()[0]
1253                .score
1254                .abs()
1255                < 0.01
1256        );
1257        conn.execute("UPDATE photos SET is_trashed=TRUE", [])
1258            .unwrap();
1259        assert!(service
1260            .search_vector_cached(&conn, &mut cache, &first, 1)
1261            .unwrap()
1262            .is_empty());
1263    }
1264
1265    #[test]
1266    fn vector_for_photo_ignores_corrupt_vector_dimension() {
1267        let conn = setup_semantic_test_conn();
1268        conn.execute(
1269            "INSERT INTO photos (id, file_path, media_type, is_trashed) VALUES
1270                (1, 'a.jpg', 'photo', FALSE)",
1271            [],
1272        )
1273        .unwrap();
1274        conn.execute(
1275            "INSERT INTO semantic_index_state
1276                (photo_id, model_key, status, vector_offset, vector_dim)
1277             VALUES (?1, ?2, 'indexed', 0, 999999999)",
1278            rusqlite::params![1_i64, SEMANTIC_MODEL_KEY],
1279        )
1280        .unwrap();
1281        let svc = SemanticSearchService::new(tempdir().unwrap().path());
1282
1283        assert!(svc.vector_for_photo(&conn, 1).unwrap().is_none());
1284    }
1285
1286    #[test]
1287    fn pending_batch_does_not_retry_failed_rows() {
1288        let conn = setup_semantic_test_conn();
1289        conn.execute(
1290            "INSERT INTO photos (id, file_path, media_type, is_trashed) VALUES
1291                (1, 'a.jpg', 'photo', FALSE),
1292                (2, 'b.jpg', 'photo', FALSE)",
1293            [],
1294        )
1295        .unwrap();
1296        SemanticSearchService::mark_failed(&conn, 1, "bad image").unwrap();
1297
1298        let svc = SemanticSearchService::new(tempdir().unwrap().path());
1299        let batch = svc.next_pending_batch(&conn, 10).unwrap();
1300
1301        assert_eq!(
1302            batch.iter().map(|p| p.photo_id).collect::<Vec<_>>(),
1303            vec![2]
1304        );
1305    }
1306
1307    #[test]
1308    fn index_stats_ignore_trashed_index_state_rows() {
1309        let conn = setup_semantic_test_conn();
1310        conn.execute(
1311            "INSERT INTO photos (id, file_path, media_type, is_trashed) VALUES
1312                (1, 'a.jpg', 'photo', FALSE),
1313                (2, 'b.jpg', 'photo', TRUE),
1314                (3, 'c.jpg', 'photo', FALSE)",
1315            [],
1316        )
1317        .unwrap();
1318        conn.execute(
1319            "INSERT INTO semantic_index_state
1320                (photo_id, model_key, status, vector_offset, vector_dim)
1321             VALUES
1322                (1, ?1, 'indexed', 0, ?2),
1323                (2, ?1, 'indexed', 0, ?2),
1324                (3, ?1, 'failed', NULL, NULL)",
1325            params![SEMANTIC_MODEL_KEY, SEMANTIC_DIM as i64],
1326        )
1327        .unwrap();
1328
1329        let svc = SemanticSearchService::new(tempdir().unwrap().path());
1330        let stats = svc.index_stats(&conn).unwrap();
1331
1332        assert_eq!(stats.indexed, 1);
1333        assert_eq!(stats.failed, 1);
1334        assert_eq!(stats.pending, 0);
1335    }
1336
1337    #[test]
1338    fn record_index_batch_persists_vectors_and_failures_once() {
1339        let mut conn = setup_semantic_test_conn();
1340        conn.execute(
1341            "INSERT INTO photos (id, file_path, media_type, is_trashed) VALUES
1342                (1, 'a.jpg', 'photo', FALSE),
1343                (2, 'b.jpg', 'photo', FALSE),
1344                (3, 'c.jpg', 'photo', FALSE)",
1345            [],
1346        )
1347        .unwrap();
1348        let dir = tempdir().unwrap();
1349        let svc = SemanticSearchService::new(dir.path());
1350        let mut first = vec![0.0f32; SEMANTIC_DIM];
1351        first[0] = 1.0;
1352        let mut second = vec![0.0f32; SEMANTIC_DIM];
1353        second[1] = 1.0;
1354
1355        svc.record_index_batch(
1356            &mut conn,
1357            &[(1, first.clone()), (2, second.clone())],
1358            &[(3, "decode failed".into())],
1359        )
1360        .unwrap();
1361
1362        let rows = conn
1363            .prepare(
1364                "SELECT photo_id, status, vector_offset, vector_dim, attempts, COALESCE(last_error, '')
1365                 FROM semantic_index_state
1366                 ORDER BY photo_id",
1367            )
1368            .unwrap()
1369            .query_map([], |row| {
1370                Ok((
1371                    row.get::<_, i64>(0)?,
1372                    row.get::<_, String>(1)?,
1373                    row.get::<_, Option<i64>>(2)?,
1374                    row.get::<_, Option<i64>>(3)?,
1375                    row.get::<_, i64>(4)?,
1376                    row.get::<_, String>(5)?,
1377                ))
1378            })
1379            .unwrap()
1380            .collect::<rusqlite::Result<Vec<_>>>()
1381            .unwrap();
1382
1383        assert_eq!(rows.len(), 3);
1384        assert_eq!(rows[0].0, 1);
1385        assert_eq!(rows[0].1, "indexed");
1386        assert_eq!(rows[0].2, Some(0));
1387        assert_eq!(rows[0].3, Some(SEMANTIC_DIM as i64));
1388        assert_eq!(rows[1].0, 2);
1389        assert_eq!(rows[1].1, "indexed");
1390        assert_eq!(rows[1].2, Some((SEMANTIC_DIM * 4) as i64));
1391        assert_eq!(rows[2].0, 3);
1392        assert_eq!(rows[2].1, "failed");
1393        assert_eq!(rows[2].4, 1);
1394        assert_eq!(rows[2].5, "decode failed");
1395
1396        let store = VectorStore::new(dir.path()).unwrap();
1397        assert_eq!(store.read(0, SEMANTIC_DIM).unwrap(), first);
1398        assert_eq!(
1399            store.read((SEMANTIC_DIM * 4) as u64, SEMANTIC_DIM).unwrap(),
1400            second
1401        );
1402        assert_eq!(
1403            std::fs::metadata(store.vector_path()).unwrap().len(),
1404            (2 * SEMANTIC_DIM * 4) as u64
1405        );
1406    }
1407
1408    #[test]
1409    fn photo_source_prefers_existing_thumbnail() {
1410        let dir = tempdir().unwrap();
1411        std::fs::create_dir_all(dir.path().join(".photovault/thumbs")).unwrap();
1412        std::fs::write(dir.path().join("photo.jpg"), b"original").unwrap();
1413        std::fs::write(dir.path().join(".photovault/thumbs/photo.jpg"), b"thumb").unwrap();
1414        let input = SemanticPhotoInput {
1415            photo_id: 1,
1416            file_path: "photo.jpg".into(),
1417            thumbnail_path: Some(".photovault/thumbs/photo.jpg".into()),
1418            media_type: "photo".into(),
1419        };
1420
1421        assert_eq!(
1422            input.source_path(dir.path()).unwrap(),
1423            dir.path().join(".photovault/thumbs/photo.jpg")
1424        );
1425    }
1426
1427    #[test]
1428    fn search_vector_returns_indexed_candidates() {
1429        let mut conn = setup_semantic_test_conn();
1430        conn.execute(
1431            "INSERT INTO photos (id, file_path, media_type, is_trashed) VALUES
1432                (1, 'a.jpg', 'photo', FALSE),
1433                (2, 'b.jpg', 'photo', FALSE),
1434                (3, 'c.jpg', 'photo', TRUE)",
1435            [],
1436        )
1437        .unwrap();
1438        let dir = tempdir().unwrap();
1439        let svc = SemanticSearchService::new(dir.path());
1440        let mut first = vec![0.0f32; SEMANTIC_DIM];
1441        first[0] = 1.0;
1442        let mut second = vec![0.0f32; SEMANTIC_DIM];
1443        second[1] = 1.0;
1444        let mut trashed = vec![0.0f32; SEMANTIC_DIM];
1445        trashed[0] = 1.0;
1446
1447        svc.record_index_batch(
1448            &mut conn,
1449            &[(1, first.clone()), (2, second), (3, trashed)],
1450            &[],
1451        )
1452        .unwrap();
1453
1454        let matches = svc.search_vector(&conn, &first, 5).unwrap();
1455
1456        assert_eq!(matches.first().map(|c| c.photo_id), Some(1));
1457        assert!(!matches.iter().any(|c| c.photo_id == 3));
1458    }
1459
1460    #[test]
1461    fn cosine_handles_normal_vectors() {
1462        assert!((cosine(&[1.0, 0.0], &[1.0, 0.0]) - 1.0).abs() < 0.001);
1463        assert!(cosine(&[1.0, 0.0], &[0.0, 1.0]).abs() < 0.001);
1464    }
1465
1466    #[test]
1467    fn text_context_is_fixed_width_int32_and_padded() {
1468        let ids = padded_text_context(&[2, 101, 102, 1]);
1469
1470        assert_eq!(ids.len(), SEMANTIC_CONTEXT_LEN);
1471        assert_eq!(&ids[..5], &[2, 101, 102, 1, 0]);
1472
1473        let long = (0..(SEMANTIC_CONTEXT_LEN as u32 + 10)).collect::<Vec<_>>();
1474        let truncated = padded_text_context(&long);
1475        assert_eq!(truncated.len(), SEMANTIC_CONTEXT_LEN);
1476        assert_eq!(truncated[0], 0);
1477        assert_eq!(
1478            truncated[SEMANTIC_CONTEXT_LEN - 1],
1479            (SEMANTIC_CONTEXT_LEN - 1) as i32
1480        );
1481    }
1482
1483    #[test]
1484    fn text_search_gate_rejects_weak_absent_queries() {
1485        let kept = relevant_text_search_candidates(vec![
1486            SemanticCandidate {
1487                photo_id: 1,
1488                score: 0.035,
1489            },
1490            SemanticCandidate {
1491                photo_id: 2,
1492                score: 0.030,
1493            },
1494        ]);
1495
1496        assert!(kept.is_empty());
1497    }
1498
1499    #[test]
1500    fn text_search_gate_keeps_only_standout_matches() {
1501        let kept = relevant_text_search_candidates(vec![
1502            SemanticCandidate {
1503                photo_id: 1,
1504                score: 0.095,
1505            },
1506            SemanticCandidate {
1507                photo_id: 2,
1508                score: 0.070,
1509            },
1510            SemanticCandidate {
1511                photo_id: 3,
1512                score: 0.040,
1513            },
1514        ]);
1515
1516        assert_eq!(kept.iter().map(|c| c.photo_id).collect::<Vec<_>>(), vec![1]);
1517    }
1518
1519    #[test]
1520    fn text_search_gate_keeps_dense_relevant_clusters() {
1521        let kept = relevant_text_search_candidates(vec![
1522            SemanticCandidate {
1523                photo_id: 1,
1524                score: 0.078,
1525            },
1526            SemanticCandidate {
1527                photo_id: 2,
1528                score: 0.074,
1529            },
1530            SemanticCandidate {
1531                photo_id: 3,
1532                score: 0.048,
1533            },
1534        ]);
1535
1536        assert_eq!(
1537            kept.iter().map(|c| c.photo_id).collect::<Vec<_>>(),
1538            vec![1, 2]
1539        );
1540    }
1541}