Skip to main content

smriti/db/face_repo/
read.rs

1//! Read/query methods for FaceRepo.
2
3use rusqlite::{params, params_from_iter, Result as SqliteResult};
4
5use crate::ml::FaceEmbedding;
6
7use super::{FaceClusterRecord, FaceDetail, FaceRepo, FaceStatus, GalleryEmbedding, PhotoFace};
8
9/// (photo_id, x, y, width, height), normalised.
10type FaceBoxRow = (i64, f32, f32, f32, f32);
11/// (id, file_path, orientation, taken_ts, file_hash)
12///
13/// `file_hash` is plumbed through so the face worker can locate the
14/// pre-generated Large thumbnail on disk and decode that instead of the
15/// full image — typically a 5-10× speedup on libraries that have
16/// already been thumbnailed.
17type UnprocessedPhotoRow = (i64, String, i32, Option<i64>, String);
18
19/// Faces the user skipped in review, kept in `library_meta` as a JSON list
20/// of face ids (see `FaceRepo::skip_review_face`).
21const NOT_SKIPPED: &str = "id NOT IN (SELECT value FROM json_each(COALESCE((SELECT value FROM library_meta WHERE key = 'people.review_skipped'), '[]')))";
22
23impl<'a> FaceRepo<'a> {
24    /// A live preview is a newest-first snapshot, not the oldest review page.
25    pub fn get_recent_faces(&self, limit: usize) -> SqliteResult<Vec<FaceDetail>> {
26        let mut stmt = self.conn.prepare(
27            "SELECT f.id, f.photo_id, f.cluster_id, f.confidence, f.user_confirmed
28             FROM faces f JOIN photos p ON p.id = f.photo_id
29             WHERE p.is_trashed = FALSE AND f.user_confirmed >= 0
30             ORDER BY f.id DESC LIMIT ?1",
31        )?;
32        let rows = stmt.query_map([limit.min(100) as i64], |row| {
33            Ok(FaceDetail {
34                face_id: row.get(0)?,
35                photo_id: row.get(1)?,
36                cluster_id: row.get(2)?,
37                confidence: row.get(3)?,
38                user_confirmed: row.get(4)?,
39            })
40        })?;
41        rows.collect()
42    }
43
44    /// Count of photos that haven't yet had face detection run. Drives
45    /// the "Resume face detection" banner on the People page.
46    pub fn count_pending_face_processing(&self) -> SqliteResult<i64> {
47        self.conn.query_row(
48            "SELECT COUNT(*) FROM photos WHERE faces_processed = FALSE AND is_trashed = FALSE",
49            [],
50            |row| row.get(0),
51        )
52    }
53
54    /// Get unclustered faces with photo_id and embeddings.
55    pub fn get_unclustered_faces_with_photo_embeddings(
56        &self,
57    ) -> SqliteResult<Vec<(i64, i64, FaceEmbedding)>> {
58        self.get_unclustered_embeddings_after(0)
59    }
60
61    /// Streaming assignment considers only newly committed faces.
62    pub fn get_unclustered_embeddings_after(
63        &self,
64        after_id: i64,
65    ) -> SqliteResult<Vec<(i64, i64, FaceEmbedding)>> {
66        let mut stmt = self.conn.prepare(
67            "SELECT f.id, f.photo_id, f.embedding
68                 FROM faces f
69                 JOIN photos p ON p.id = f.photo_id
70                 WHERE f.cluster_id IS NULL
71                   AND f.user_confirmed >= 0
72                   AND p.is_trashed = FALSE AND f.id > ?1",
73        )?;
74
75        let rows = stmt.query_map([after_id], |row| {
76            let id: i64 = row.get(0)?;
77            let photo_id: i64 = row.get(1)?;
78            let bytes: Vec<u8> = row.get(2)?;
79            Ok((id, photo_id, bytes))
80        })?;
81
82        let mut faces = Vec::new();
83        for row in rows {
84            let (id, photo_id, bytes) = row?;
85            match FaceEmbedding::from_bytes(&bytes) {
86                Some(emb) => faces.push((id, photo_id, emb)),
87                None => tracing::warn!(
88                    "Corrupted face embedding for face_id={}: {} bytes",
89                    id,
90                    bytes.len()
91                ),
92            }
93        }
94
95        Ok(faces)
96    }
97
98    /// Get all clusters, ordered by photo count descending
99    pub fn get_all_clusters(&self) -> SqliteResult<Vec<FaceClusterRecord>> {
100        let mut stmt = self.conn.prepare(
101            r#"
102            SELECT id, name, representative_face_id, photo_count
103            FROM face_clusters
104            ORDER BY photo_count DESC, face_count DESC
105            "#,
106        )?;
107
108        let rows = stmt.query_map([], |row| {
109            Ok(FaceClusterRecord {
110                id: row.get(0)?,
111                name: row.get(1)?,
112                representative_face_id: row.get(2)?,
113                photo_count: row.get(3)?,
114                face_thumbnail_path: None, // Set after query using drive path
115            })
116        })?;
117
118        let mut clusters = Vec::new();
119        for row in rows {
120            clusters.push(row?);
121        }
122
123        Ok(clusters)
124    }
125
126    pub fn get_gallery_embeddings(&self) -> SqliteResult<Vec<GalleryEmbedding>> {
127        let mut stmt = self.conn.prepare(
128            "SELECT cluster_id, face_id, embedding FROM person_gallery_embeddings ORDER BY cluster_id",
129        )?;
130
131        let rows = stmt.query_map([], |row| {
132            Ok((
133                row.get::<_, i64>(0)?,
134                row.get::<_, i64>(1)?,
135                row.get::<_, Vec<u8>>(2)?,
136            ))
137        })?;
138
139        let mut result = Vec::new();
140        for row in rows {
141            let (cluster_id, face_id, bytes) = row?;
142            match FaceEmbedding::from_bytes(&bytes) {
143                Some(embedding) => {
144                    result.push(GalleryEmbedding {
145                        cluster_id,
146                        face_id,
147                        embedding,
148                    });
149                }
150                None => tracing::warn!(
151                    "Corrupted gallery embedding for cluster_id={}, face_id={}: {} bytes",
152                    cluster_id,
153                    face_id,
154                    bytes.len()
155                ),
156            }
157        }
158
159        Ok(result)
160    }
161
162    pub fn get_cluster_photo_ids(&self) -> SqliteResult<Vec<(i64, i64)>> {
163        let mut stmt = self.conn.prepare(
164            "SELECT DISTINCT cluster_id, photo_id FROM faces WHERE cluster_id IS NOT NULL",
165        )?;
166
167        let rows = stmt.query_map([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?)))?;
168        let mut result = Vec::new();
169        for row in rows {
170            result.push(row?);
171        }
172        Ok(result)
173    }
174
175    /// Normalised face boxes `(photo_id, x, y, width, height)` for the given
176    /// photos, in display orientation. Used to keep faces in frame when a
177    /// photo is cropped into a collage cell.
178    pub fn get_face_boxes_for_photos(&self, photo_ids: &[i64]) -> SqliteResult<Vec<FaceBoxRow>> {
179        if photo_ids.is_empty() {
180            return Ok(Vec::new());
181        }
182        let placeholders = vec!["?"; photo_ids.len()].join(",");
183        let mut stmt = self.conn.prepare(&format!(
184            "SELECT photo_id, bbox_x, bbox_y, bbox_width, bbox_height
185             FROM faces WHERE photo_id IN ({placeholders}) AND user_confirmed >= 0
186             ORDER BY photo_id, id"
187        ))?;
188        let rows = stmt
189            .query_map(params_from_iter(photo_ids), |row| {
190                Ok((
191                    row.get(0)?,
192                    row.get(1)?,
193                    row.get(2)?,
194                    row.get(3)?,
195                    row.get(4)?,
196                ))
197            })?
198            .collect();
199        rows
200    }
201
202    /// The faces in one photo, left to right, with who each one is. Faces
203    /// set aside as "not a face" are left out.
204    pub fn faces_in_photo(&self, photo_id: i64) -> SqliteResult<Vec<PhotoFace>> {
205        let mut stmt = self.conn.prepare(
206            "SELECT f.id, f.bbox_x, f.bbox_y, f.bbox_width, f.bbox_height,
207                    f.cluster_id, fc.name, f.user_confirmed
208             FROM faces f LEFT JOIN face_clusters fc ON fc.id = f.cluster_id
209             WHERE f.photo_id = ?1 AND f.user_confirmed >= 0
210             ORDER BY f.bbox_x, f.id",
211        )?;
212        let rows = stmt.query_map(params![photo_id], |row| {
213            Ok(PhotoFace {
214                face_id: row.get(0)?,
215                bbox: (row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?),
216                cluster_id: row.get(5)?,
217                name: row.get(6)?,
218                confirmed: row.get::<_, i32>(7)? == 1,
219            })
220        })?;
221        rows.collect()
222    }
223
224    /// Get person names for a photo (faces detected in this photo with cluster names)
225    /// Get (cluster_id, display_name) pairs for all people detected in a photo.
226    pub fn get_people_for_photo(&self, photo_id: i64) -> SqliteResult<Vec<(i64, String)>> {
227        let mut stmt = self.conn.prepare(
228            r#"
229            SELECT DISTINCT cluster_id, name FROM (
230                SELECT fc.id AS cluster_id, COALESCE(fc.name, 'Person ' || fc.id) AS name
231                FROM faces f
232                JOIN face_clusters fc ON f.cluster_id = fc.id
233                WHERE f.photo_id = ?1
234
235                UNION
236
237                SELECT fc.id AS cluster_id, COALESCE(fc.name, 'Person ' || fc.id) AS name
238                FROM photo_inferred_identities pii
239                JOIN face_clusters fc ON pii.cluster_id = fc.id
240                WHERE pii.photo_id = ?1
241            )
242            ORDER BY name
243            "#,
244        )?;
245
246        let people = stmt
247            .query_map(params![photo_id], |row| {
248                Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
249            })?
250            .collect::<SqliteResult<Vec<_>>>()?;
251
252        Ok(people)
253    }
254
255    /// Get all photo IDs that contain faces from a given cluster
256    pub fn get_photos_for_cluster(&self, cluster_id: i64) -> SqliteResult<Vec<i64>> {
257        let mut stmt = self.conn.prepare(
258            r#"
259            SELECT p.id
260            FROM photos p
261            JOIN (
262                SELECT f.photo_id
263                FROM faces f
264                WHERE f.cluster_id = ?1
265                UNION
266                SELECT pii.photo_id
267                FROM photo_inferred_identities pii
268                WHERE pii.cluster_id = ?1
269            ) matches ON matches.photo_id = p.id
270            WHERE p.is_trashed = FALSE
271            GROUP BY p.id
272            ORDER BY p.date_taken IS NULL ASC, p.date_taken DESC, p.id DESC
273            "#,
274        )?;
275
276        let rows = stmt.query_map(params![cluster_id], |row| row.get(0))?;
277
278        let mut photo_ids = Vec::new();
279        for row in rows {
280            photo_ids.push(row?);
281        }
282
283        Ok(photo_ids)
284    }
285
286    /// Find contextual candidate identities from nearby photos in the same folder.
287    pub fn get_contextual_cluster_candidates(
288        &self,
289        photo_id: i64,
290        folder_prefix_like: Option<&str>,
291        target_ts: i64,
292        window_secs: i64,
293    ) -> SqliteResult<Vec<(i64, i64, i64, String)>> {
294        let sql_with_folder = r#"
295            SELECT DISTINCT
296                p.id,
297                f.cluster_id,
298                CAST(strftime('%s', p.date_taken) AS INTEGER) AS source_ts,
299                p.file_path
300            FROM photos p
301            JOIN faces f ON f.photo_id = p.id
302            WHERE p.id != ?1
303                AND p.is_trashed = FALSE
304                AND p.date_taken IS NOT NULL
305                AND f.cluster_id IS NOT NULL
306                AND p.file_path LIKE ?2
307                AND ABS(CAST(strftime('%s', p.date_taken) AS INTEGER) - ?3) <= ?4
308        "#;
309
310        let sql_without_folder = r#"
311            SELECT DISTINCT
312                p.id,
313                f.cluster_id,
314                CAST(strftime('%s', p.date_taken) AS INTEGER) AS source_ts,
315                p.file_path
316            FROM photos p
317            JOIN faces f ON f.photo_id = p.id
318            WHERE p.id != ?1
319                AND p.is_trashed = FALSE
320                AND p.date_taken IS NOT NULL
321                AND f.cluster_id IS NOT NULL
322                AND ABS(CAST(strftime('%s', p.date_taken) AS INTEGER) - ?2) <= ?3
323        "#;
324
325        let mut result = Vec::new();
326
327        if let Some(folder_like) = folder_prefix_like {
328            let mut stmt = self.conn.prepare(sql_with_folder)?;
329            let rows = stmt.query_map(
330                params![photo_id, folder_like, target_ts, window_secs],
331                |row| {
332                    Ok((
333                        row.get::<_, i64>(0)?,
334                        row.get::<_, i64>(1)?,
335                        row.get::<_, i64>(2)?,
336                        row.get::<_, String>(3)?,
337                    ))
338                },
339            )?;
340            for row in rows {
341                result.push(row?);
342            }
343        } else {
344            let mut stmt = self.conn.prepare(sql_without_folder)?;
345            let rows = stmt.query_map(params![photo_id, target_ts, window_secs], |row| {
346                Ok((
347                    row.get::<_, i64>(0)?,
348                    row.get::<_, i64>(1)?,
349                    row.get::<_, i64>(2)?,
350                    row.get::<_, String>(3)?,
351                ))
352            })?;
353            for row in rows {
354                result.push(row?);
355            }
356        }
357
358        Ok(result)
359    }
360
361    /// Get unprocessed photos with optional timestamp for contextual identity linking.
362    pub fn get_unprocessed_photos_with_context(&self) -> SqliteResult<Vec<UnprocessedPhotoRow>> {
363        let mut stmt = self.conn.prepare(
364            r#"
365            SELECT
366                id,
367                file_path,
368                COALESCE(orientation, 1) AS orientation,
369                CASE
370                    WHEN date_taken IS NOT NULL THEN CAST(strftime('%s', date_taken) AS INTEGER)
371                    ELSE NULL
372                END AS taken_ts,
373                file_hash
374            FROM photos
375            WHERE faces_processed = FALSE AND is_trashed = FALSE
376            ORDER BY date_taken DESC
377            "#,
378        )?;
379
380        let rows = stmt.query_map([], |row| {
381            Ok((
382                row.get::<_, i64>(0)?,
383                row.get::<_, String>(1)?,
384                row.get::<_, i32>(2)?,
385                row.get::<_, Option<i64>>(3)?,
386                row.get::<_, String>(4)?,
387            ))
388        })?;
389
390        let mut result = Vec::new();
391        for row in rows {
392            result.push(row?);
393        }
394        Ok(result)
395    }
396
397    /// Read the cached `photos.brightness` value for a photo. Returns
398    /// `None` if the photo doesn't exist OR brightness was never
399    /// computed (NULL in the column). Caller is expected to fall back
400    /// to on-disk recomputation in that case.
401    pub fn get_photo_brightness(&self, photo_id: i64) -> SqliteResult<Option<f32>> {
402        self.conn
403            .query_row(
404                "SELECT brightness FROM photos WHERE id = ?1",
405                rusqlite::params![photo_id],
406                |row| row.get::<_, Option<f32>>(0),
407            )
408            .or_else(|e| match e {
409                rusqlite::Error::QueryReturnedNoRows => Ok(None),
410                other => Err(other),
411            })
412    }
413
414    /// Cluster IDs of the already-assigned faces in the given photo (other
415    /// than the face we're resolving). Used as the "context" in co-occurrence.
416    pub fn get_photo_other_clusters(
417        &self,
418        photo_id: i64,
419        exclude_face_id: i64,
420    ) -> SqliteResult<Vec<i64>> {
421        let mut stmt = self.conn.prepare(
422            "SELECT DISTINCT cluster_id FROM faces
423             WHERE photo_id = ?1 AND id != ?2 AND cluster_id IS NOT NULL",
424        )?;
425        let rows = stmt.query_map(params![photo_id, exclude_face_id], |row| {
426            row.get::<_, i64>(0)
427        })?;
428        let mut out = Vec::new();
429        for row in rows {
430            out.push(row?);
431        }
432        Ok(out)
433    }
434
435    /// How many photos contain both cluster_a and cluster_b.
436    ///
437    /// Used as the co-occurrence strength between two clusters. High values
438    /// mean the two people appear together frequently and should bias
439    /// retrieval toward whichever matches the rest of the photo's cast.
440    pub fn cooccurrence_count(&self, cluster_a: i64, cluster_b: i64) -> SqliteResult<i64> {
441        if cluster_a == cluster_b {
442            return Ok(0);
443        }
444        self.conn.query_row(
445            r#"
446            SELECT COUNT(*) FROM (
447                SELECT photo_id FROM faces WHERE cluster_id = ?1
448                INTERSECT
449                SELECT photo_id FROM faces WHERE cluster_id = ?2
450            )
451            "#,
452            params![cluster_a, cluster_b],
453            |row| row.get(0),
454        )
455    }
456
457    /// Clusters assigned to faces within a time window around `date_taken`,
458    /// excluding the photo itself. Returns (cluster_id, delta_seconds).
459    ///
460    /// Used for temporal-chain propagation: if nearby-in-time photos contain
461    /// high-confidence assignments for cluster X, an ambiguous face in our
462    /// photo should be biased toward X.
463    pub fn temporal_neighbor_clusters(
464        &self,
465        photo_id: i64,
466        window_secs: i64,
467    ) -> SqliteResult<Vec<(i64, i64)>> {
468        let mut stmt = self.conn.prepare(
469            r#"
470            WITH base AS (
471                SELECT date_taken AS t
472                FROM photos
473                WHERE id = ?1 AND date_taken IS NOT NULL
474            )
475            SELECT DISTINCT f.cluster_id,
476                CAST(ABS(
477                    strftime('%s', p.date_taken) - strftime('%s', (SELECT t FROM base))
478                ) AS INTEGER) AS delta_sec
479            FROM faces f
480            JOIN photos p ON p.id = f.photo_id
481            WHERE f.cluster_id IS NOT NULL
482              AND p.id != ?1
483              AND p.is_trashed = FALSE
484              AND p.date_taken IS NOT NULL
485              AND ABS(
486                  strftime('%s', p.date_taken) - strftime('%s', (SELECT t FROM base))
487              ) <= ?2
488            "#,
489        )?;
490        let rows = stmt.query_map(params![photo_id, window_secs], |row| {
491            Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?))
492        })?;
493        let mut out = Vec::new();
494        for row in rows {
495            out.push(row?);
496        }
497        Ok(out)
498    }
499
500    /// Get faces for a cluster filtered by status.
501    pub fn get_faces_by_cluster(
502        &self,
503        cluster_id: i64,
504        status: FaceStatus,
505        cursor: Option<i64>,
506        limit: usize,
507    ) -> SqliteResult<Vec<FaceDetail>> {
508        let (where_clause, params_slice): (String, Vec<rusqlite::types::Value>) = match status {
509            FaceStatus::Confirmed => (
510                "f.cluster_id = ?1 AND f.user_confirmed = 1".to_string(),
511                vec![rusqlite::types::Value::from(cluster_id)],
512            ),
513            FaceStatus::Unconfirmed => (
514                "f.cluster_id = ?1 AND f.user_confirmed = 0".to_string(),
515                vec![rusqlite::types::Value::from(cluster_id)],
516            ),
517            FaceStatus::All => (
518                "f.cluster_id = ?1".to_string(),
519                vec![rusqlite::types::Value::from(cluster_id)],
520            ),
521        };
522
523        let mut sql = format!(
524            "SELECT f.id, f.photo_id, f.cluster_id, f.confidence, f.user_confirmed
525             FROM faces f
526             WHERE {} ",
527            where_clause
528        );
529
530        let mut params: Vec<rusqlite::types::Value> = params_slice;
531        if let Some(c) = cursor {
532            sql.push_str("AND f.id > ?2 ");
533            params.push(rusqlite::types::Value::from(c));
534            sql.push_str("ORDER BY f.id ASC LIMIT ?3");
535        } else {
536            sql.push_str("ORDER BY f.id ASC LIMIT ?2");
537        }
538        params.push(rusqlite::types::Value::from(limit as i64));
539
540        let param_refs: Vec<&dyn rusqlite::types::ToSql> = params
541            .iter()
542            .map(|v| v as &dyn rusqlite::types::ToSql)
543            .collect();
544
545        let mut stmt = self.conn.prepare(&sql)?;
546        let rows = stmt.query_map(param_refs.as_slice(), |row| {
547            Ok(FaceDetail {
548                face_id: row.get(0)?,
549                photo_id: row.get(1)?,
550                cluster_id: row.get(2)?,
551                confidence: row.get(3)?,
552                user_confirmed: row.get(4)?,
553            })
554        })?;
555
556        let mut faces = Vec::new();
557        for row in rows {
558            faces.push(row?);
559        }
560        Ok(faces)
561    }
562
563    /// Recently detected faces that are not assigned to a person yet.
564    /// Used only as a live, in-progress surface while the face pipeline
565    /// is still clustering. The final People grid remains cluster-based.
566    pub fn get_unclustered_faces(
567        &self,
568        cursor: Option<i64>,
569        limit: usize,
570    ) -> SqliteResult<Vec<FaceDetail>> {
571        let mut sql = String::from(
572            "SELECT f.id, f.photo_id, f.cluster_id, f.confidence, f.user_confirmed
573             FROM faces f
574             JOIN photos p ON p.id = f.photo_id
575             WHERE f.cluster_id IS NULL
576               AND f.user_confirmed >= 0
577               AND p.is_trashed = FALSE ",
578        );
579        let mut params: Vec<rusqlite::types::Value> = Vec::new();
580        if let Some(c) = cursor {
581            sql.push_str("AND f.id > ?1 ORDER BY f.id ASC LIMIT ?2");
582            params.push(rusqlite::types::Value::from(c));
583            params.push(rusqlite::types::Value::from(limit as i64));
584        } else {
585            sql.push_str("ORDER BY f.id ASC LIMIT ?1");
586            params.push(rusqlite::types::Value::from(limit as i64));
587        }
588        let param_refs: Vec<&dyn rusqlite::types::ToSql> = params
589            .iter()
590            .map(|v| v as &dyn rusqlite::types::ToSql)
591            .collect();
592
593        let mut stmt = self.conn.prepare(&sql)?;
594        let rows = stmt.query_map(param_refs.as_slice(), |row| {
595            Ok(FaceDetail {
596                face_id: row.get(0)?,
597                photo_id: row.get(1)?,
598                cluster_id: row.get(2)?,
599                confidence: row.get(3)?,
600                user_confirmed: row.get(4)?,
601            })
602        })?;
603
604        let mut faces = Vec::new();
605        for row in rows {
606            faces.push(row?);
607        }
608        Ok(faces)
609    }
610
611    /// Count unconfirmed faces across all clusters, leaving out ones the
612    /// user skipped in review.
613    /// Returns (total_unconfirmed, clusters_with_unconfirmed).
614    pub fn count_unconfirmed_global(&self) -> SqliteResult<(i64, i64)> {
615        let total: i64 = self.conn.query_row(
616            &format!(
617                "SELECT COUNT(*) FROM faces
618                 WHERE cluster_id IS NOT NULL AND user_confirmed = 0 AND {NOT_SKIPPED}"
619            ),
620            [],
621            |row| row.get(0),
622        )?;
623        let cluster_count: i64 = self.conn.query_row(
624            &format!(
625                "SELECT COUNT(DISTINCT cluster_id) FROM faces
626                 WHERE cluster_id IS NOT NULL AND user_confirmed = 0 AND {NOT_SKIPPED}"
627            ),
628            [],
629            |row| row.get(0),
630        )?;
631        Ok((total, cluster_count))
632    }
633
634    /// Return the next review batch, leaving out faces the user skipped.
635    /// A skip isn't a confirm or reject decision; it just takes the face
636    /// out of review (see `skip_review_face`). `excluded_face_ids` are
637    /// this session's skips still in flight.
638    pub fn next_unconfirmed_face_batch_excluding(
639        &self,
640        limit: usize,
641        excluded_face_ids: &[i64],
642    ) -> SqliteResult<Vec<FaceDetail>> {
643        if excluded_face_ids.is_empty() {
644            return self.next_unconfirmed_face_batch_without_exclusions(limit);
645        }
646
647        let placeholders = vec!["?"; excluded_face_ids.len()].join(", ");
648        let sql = format!(
649            r#"
650            WITH next_cluster AS (
651                SELECT cluster_id
652                FROM faces
653                WHERE cluster_id IS NOT NULL
654                  AND user_confirmed = 0
655                  AND id NOT IN ({placeholders})
656                  AND {NOT_SKIPPED}
657                GROUP BY cluster_id
658                ORDER BY COUNT(*) DESC, MIN(id) ASC
659                LIMIT 1
660            )
661            SELECT f.id, f.photo_id, f.cluster_id, f.confidence, f.user_confirmed
662            FROM faces f
663            JOIN next_cluster n ON n.cluster_id = f.cluster_id
664            WHERE f.user_confirmed = 0
665              AND f.id NOT IN ({placeholders})
666              AND f.{NOT_SKIPPED}
667            ORDER BY f.id ASC
668            LIMIT ?
669            "#
670        );
671        let mut args = Vec::with_capacity(excluded_face_ids.len() * 2 + 1);
672        args.extend_from_slice(excluded_face_ids);
673        args.extend_from_slice(excluded_face_ids);
674        args.push(limit as i64);
675
676        let mut stmt = self.conn.prepare(&sql)?;
677        let rows = stmt.query_map(params_from_iter(args), |row| {
678            Ok(FaceDetail {
679                face_id: row.get(0)?,
680                photo_id: row.get(1)?,
681                cluster_id: row.get(2)?,
682                confidence: row.get(3)?,
683                user_confirmed: row.get(4)?,
684            })
685        })?;
686
687        let mut faces = Vec::new();
688        for row in rows {
689            faces.push(row?);
690        }
691        Ok(faces)
692    }
693
694    fn next_unconfirmed_face_batch_without_exclusions(
695        &self,
696        limit: usize,
697    ) -> SqliteResult<Vec<FaceDetail>> {
698        let mut stmt = self.conn.prepare(&format!(
699            r#"
700            WITH next_cluster AS (
701                SELECT cluster_id
702                FROM faces
703                WHERE cluster_id IS NOT NULL
704                  AND user_confirmed = 0
705                  AND {NOT_SKIPPED}
706                GROUP BY cluster_id
707                ORDER BY COUNT(*) DESC, MIN(id) ASC
708                LIMIT 1
709            )
710            SELECT f.id, f.photo_id, f.cluster_id, f.confidence, f.user_confirmed
711            FROM faces f
712            JOIN next_cluster n ON n.cluster_id = f.cluster_id
713            WHERE f.user_confirmed = 0
714              AND f.{NOT_SKIPPED}
715            ORDER BY f.id ASC
716            LIMIT ?1
717            "#,
718        ))?;
719        let rows = stmt.query_map(params![limit as i64], |row| {
720            Ok(FaceDetail {
721                face_id: row.get(0)?,
722                photo_id: row.get(1)?,
723                cluster_id: row.get(2)?,
724                confidence: row.get(3)?,
725                user_confirmed: row.get(4)?,
726            })
727        })?;
728
729        let mut faces = Vec::new();
730        for row in rows {
731            faces.push(row?);
732        }
733        Ok(faces)
734    }
735
736    /// Get negatives for a face (clusters it should NOT be in).
737    pub fn get_negatives_for_face(&self, face_id: i64) -> SqliteResult<Vec<i64>> {
738        let mut stmt = self
739            .conn
740            .prepare("SELECT not_cluster_id FROM face_negatives WHERE face_id = ?1")?;
741        let rows = stmt.query_map(params![face_id], |row| row.get::<_, i64>(0))?;
742        let mut out = Vec::new();
743        for row in rows {
744            out.push(row?);
745        }
746        Ok(out)
747    }
748
749    /// K-similar: find K nearest unassigned faces to a cluster's confirmed gallery centroid.
750    pub fn k_similar_to_cluster(&self, cluster_id: i64, k: usize) -> SqliteResult<Vec<(i64, f32)>> {
751        if k == 0 {
752            return Ok(Vec::new());
753        }
754
755        // Gather confirmed gallery embeddings for centroid.
756        let mut stmt = self.conn.prepare(
757            "SELECT embedding FROM person_gallery_embeddings WHERE cluster_id = ?1 AND source = 'user_confirmed'",
758        )?;
759        let rows = stmt.query_map(params![cluster_id], |row| row.get::<_, Vec<u8>>(0))?;
760        let mut embeddings: Vec<FaceEmbedding> = Vec::new();
761        for row in rows {
762            let bytes = row?;
763            if let Some(emb) = FaceEmbedding::from_bytes(&bytes) {
764                embeddings.push(emb);
765            }
766        }
767
768        // If no user-confirmed gallery, fall back to auto gallery.
769        if embeddings.is_empty() {
770            let mut stmt2 = self
771                .conn
772                .prepare("SELECT embedding FROM person_gallery_embeddings WHERE cluster_id = ?1")?;
773            let rows2 = stmt2.query_map(params![cluster_id], |row| row.get::<_, Vec<u8>>(0))?;
774            for row in rows2 {
775                let bytes = row?;
776                if let Some(emb) = FaceEmbedding::from_bytes(&bytes) {
777                    embeddings.push(emb);
778                }
779            }
780        }
781
782        if embeddings.is_empty() {
783            return Ok(Vec::new());
784        }
785
786        // Compute centroid (mean of all gallery vectors).
787        let dim = embeddings[0].vector.len();
788        let mut centroid = ndarray::Array1::<f32>::zeros(dim);
789        for emb in &embeddings {
790            centroid += &emb.vector;
791        }
792        centroid /= embeddings.len() as f32;
793
794        // Normalize the centroid.
795        let norm = centroid.dot(&centroid).sqrt();
796        if norm > 0.0 {
797            centroid /= norm;
798        }
799        let centroid_emb = FaceEmbedding::new(centroid);
800
801        // Load candidate faces: unassigned (cluster_id IS NULL OR user_confirmed = 0),
802        // excluding faces with a negative against this cluster.
803        let mut cand_stmt = self.conn.prepare(
804            r#"
805            SELECT f.id, f.embedding
806            FROM faces f
807            JOIN photos p ON p.id = f.photo_id
808            WHERE (f.cluster_id IS NULL OR (f.cluster_id IS NOT NULL AND f.user_confirmed = 0))
809              AND f.user_confirmed >= 0
810              AND p.is_trashed = FALSE
811              AND f.id NOT IN (
812                  SELECT face_id FROM face_negatives WHERE not_cluster_id = ?1
813              )
814            "#,
815        )?;
816        let cand_rows = cand_stmt.query_map(params![cluster_id], |row| {
817            Ok((row.get::<_, i64>(0)?, row.get::<_, Vec<u8>>(1)?))
818        })?;
819
820        let mut scored: Vec<(i64, f32)> = Vec::new();
821        for row in cand_rows {
822            let (face_id, bytes) = row?;
823            if let Some(emb) = FaceEmbedding::from_bytes(&bytes) {
824                let sim = centroid_emb.cosine_similarity(&emb);
825                scored.push((face_id, sim));
826            }
827        }
828
829        // Sort descending by similarity, take top K.
830        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
831        scored.truncate(k);
832
833        Ok(scored)
834    }
835}
836
837#[cfg(test)]
838mod tests {
839    use rusqlite::{params, Connection};
840
841    use super::*;
842    use crate::db::create_schema;
843    use ndarray::Array1;
844
845    fn embedding(seed: f32) -> Vec<u8> {
846        let mut values = vec![0.0; 512];
847        values[0] = seed;
848        values[1] = 1.0 - seed;
849        FaceEmbedding::new(Array1::from_vec(values)).to_bytes()
850    }
851
852    fn seeded_conn() -> Connection {
853        let conn = Connection::open_in_memory().unwrap();
854        create_schema(&conn).unwrap();
855        conn.execute(
856            "INSERT INTO face_clusters (id, name, face_count, photo_count) VALUES (10, 'Person', 3, 3)",
857            [],
858        )
859        .unwrap();
860
861        for id in 1..=3 {
862            conn.execute(
863                "INSERT INTO photos (id, file_path, file_name, file_hash, file_size)
864                 VALUES (?1, ?2, ?3, ?4, 100)",
865                params![
866                    id,
867                    format!("photos/{id}.jpg"),
868                    format!("{id}.jpg"),
869                    format!("hash-{id}")
870                ],
871            )
872            .unwrap();
873            conn.execute(
874                "INSERT INTO faces (
875                    id, photo_id, bbox_x, bbox_y, bbox_width, bbox_height,
876                    embedding, cluster_id, confidence, user_confirmed
877                 )
878                 VALUES (?1, ?2, 0.1, 0.1, 0.2, 0.2, ?3, 10, 0.99, ?4)",
879                params![
880                    id,
881                    id,
882                    embedding(id as f32 / 10.0),
883                    if id == 3 { 1 } else { 0 }
884                ],
885            )
886            .unwrap();
887        }
888        conn
889    }
890
891    fn insert_cluster(conn: &Connection, id: i64, name: &str) {
892        conn.execute(
893            "INSERT INTO face_clusters (id, name, face_count, photo_count) VALUES (?1, ?2, 0, 0)",
894            params![id, name],
895        )
896        .unwrap();
897    }
898
899    fn insert_face(conn: &Connection, id: i64, cluster_id: i64, confirmed: i32) {
900        conn.execute(
901            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size)
902             VALUES (?1, ?2, ?3, ?4, 100)",
903            params![
904                id + 100,
905                format!("photos/review-{id}.jpg"),
906                format!("review-{id}.jpg"),
907                format!("review-hash-{id}")
908            ],
909        )
910        .unwrap();
911        conn.execute(
912            "INSERT INTO faces (
913                id, photo_id, bbox_x, bbox_y, bbox_width, bbox_height,
914                embedding, cluster_id, confidence, user_confirmed
915             )
916             VALUES (?1, ?2, 0.1, 0.1, 0.2, 0.2, ?3, ?4, 0.99, ?5)",
917            params![
918                id,
919                id + 100,
920                embedding(id as f32 / 10.0),
921                cluster_id,
922                confirmed
923            ],
924        )
925        .unwrap();
926    }
927
928    #[test]
929    fn face_boxes_are_returned_only_for_requested_photos() {
930        let conn = seeded_conn();
931        let repo = FaceRepo::new(&conn);
932
933        let boxes = repo.get_face_boxes_for_photos(&[1, 3, 99]).unwrap();
934
935        assert_eq!(boxes.iter().map(|b| b.0).collect::<Vec<_>>(), vec![1, 3]);
936        assert!((boxes[0].3 - 0.2).abs() < 1e-6);
937        assert!(repo.get_face_boxes_for_photos(&[]).unwrap().is_empty());
938    }
939
940    #[test]
941    fn get_faces_by_cluster_first_page_uses_valid_limit_parameter() {
942        let conn = seeded_conn();
943        let repo = FaceRepo::new(&conn);
944
945        let faces = repo
946            .get_faces_by_cluster(10, FaceStatus::Unconfirmed, None, 10)
947            .unwrap();
948
949        assert_eq!(
950            faces.iter().map(|f| f.face_id).collect::<Vec<_>>(),
951            vec![1, 2]
952        );
953    }
954
955    #[test]
956    fn get_faces_by_cluster_cursor_uses_valid_limit_parameter() {
957        let conn = seeded_conn();
958        let repo = FaceRepo::new(&conn);
959
960        let faces = repo
961            .get_faces_by_cluster(10, FaceStatus::All, Some(1), 10)
962            .unwrap();
963
964        assert_eq!(
965            faces.iter().map(|f| f.face_id).collect::<Vec<_>>(),
966            vec![2, 3]
967        );
968    }
969
970    #[test]
971    fn next_unconfirmed_face_batch_uses_the_cluster_with_most_pending_faces() {
972        let conn = Connection::open_in_memory().unwrap();
973        create_schema(&conn).unwrap();
974        insert_cluster(&conn, 10, "Small");
975        insert_cluster(&conn, 20, "Large");
976        insert_face(&conn, 1, 10, 0);
977        insert_face(&conn, 2, 20, 0);
978        insert_face(&conn, 3, 20, 0);
979        insert_face(&conn, 4, 20, 1);
980        let repo = FaceRepo::new(&conn);
981
982        let faces = repo.next_unconfirmed_face_batch_excluding(10, &[]).unwrap();
983
984        assert_eq!(
985            faces.iter().map(|f| f.face_id).collect::<Vec<_>>(),
986            vec![2, 3]
987        );
988        assert!(faces.iter().all(|f| f.cluster_id == Some(20)));
989    }
990
991    #[test]
992    fn next_unconfirmed_face_batch_excluding_skipped_faces_moves_to_next_cluster() {
993        let conn = Connection::open_in_memory().unwrap();
994        create_schema(&conn).unwrap();
995        insert_cluster(&conn, 10, "Small");
996        insert_cluster(&conn, 20, "Large");
997        insert_face(&conn, 1, 10, 0);
998        insert_face(&conn, 2, 20, 0);
999        insert_face(&conn, 3, 20, 0);
1000        let repo = FaceRepo::new(&conn);
1001
1002        let faces = repo
1003            .next_unconfirmed_face_batch_excluding(10, &[2, 3])
1004            .unwrap();
1005
1006        assert_eq!(faces.iter().map(|f| f.face_id).collect::<Vec<_>>(), vec![1]);
1007        assert!(faces.iter().all(|f| f.cluster_id == Some(10)));
1008    }
1009
1010    #[test]
1011    fn unclustered_embedding_candidates_skip_trashed_and_hidden_faces() {
1012        let conn = Connection::open_in_memory().unwrap();
1013        create_schema(&conn).unwrap();
1014        for id in 1..=3 {
1015            conn.execute(
1016                "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, is_trashed)
1017                 VALUES (?1, ?2, ?3, ?4, 100, ?5)",
1018                params![
1019                    id,
1020                    format!("photos/{id}.jpg"),
1021                    format!("{id}.jpg"),
1022                    format!("hash-{id}"),
1023                    if id == 2 { 1 } else { 0 }
1024                ],
1025            )
1026            .unwrap();
1027        }
1028        conn.execute(
1029            "INSERT INTO faces (
1030                id, photo_id, bbox_x, bbox_y, bbox_width, bbox_height,
1031                embedding, cluster_id, confidence, user_confirmed
1032             )
1033             VALUES
1034                (1, 1, 0.1, 0.1, 0.2, 0.2, ?1, NULL, 0.9, 0),
1035                (2, 2, 0.1, 0.1, 0.2, 0.2, ?2, NULL, 0.9, 0),
1036                (3, 3, 0.1, 0.1, 0.2, 0.2, ?3, NULL, 0.9, -1)",
1037            params![embedding(0.1), embedding(0.2), embedding(0.3)],
1038        )
1039        .unwrap();
1040
1041        let faces = FaceRepo::new(&conn)
1042            .get_unclustered_faces_with_photo_embeddings()
1043            .unwrap();
1044
1045        assert_eq!(
1046            faces.iter().map(|(id, _, _)| *id).collect::<Vec<_>>(),
1047            vec![1]
1048        );
1049    }
1050
1051    #[test]
1052    fn k_similar_skips_trashed_candidates_and_zero_k_short_circuits() {
1053        let conn = Connection::open_in_memory().unwrap();
1054        create_schema(&conn).unwrap();
1055        insert_cluster(&conn, 10, "Person");
1056        for id in 1..=3 {
1057            conn.execute(
1058                "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, is_trashed)
1059                 VALUES (?1, ?2, ?3, ?4, 100, ?5)",
1060                params![
1061                    id,
1062                    format!("photos/{id}.jpg"),
1063                    format!("{id}.jpg"),
1064                    format!("hash-{id}"),
1065                    if id == 3 { 1 } else { 0 }
1066                ],
1067            )
1068            .unwrap();
1069        }
1070        conn.execute(
1071            "INSERT INTO faces (
1072                id, photo_id, bbox_x, bbox_y, bbox_width, bbox_height,
1073                embedding, cluster_id, confidence, user_confirmed
1074             )
1075             VALUES
1076                (1, 1, 0.1, 0.1, 0.2, 0.2, ?1, 10, 0.9, 1),
1077                (2, 2, 0.1, 0.1, 0.2, 0.2, ?2, NULL, 0.9, 0),
1078                (3, 3, 0.1, 0.1, 0.2, 0.2, ?3, NULL, 0.9, 0)",
1079            params![embedding(0.9), embedding(0.8), embedding(0.9)],
1080        )
1081        .unwrap();
1082        conn.execute(
1083            "INSERT INTO person_gallery_embeddings (cluster_id, face_id, embedding, quality_score, source)
1084             VALUES (10, 1, ?1, 0.9, 'user_confirmed')",
1085            params![embedding(0.9)],
1086        )
1087        .unwrap();
1088        let repo = FaceRepo::new(&conn);
1089
1090        assert!(repo.k_similar_to_cluster(10, 0).unwrap().is_empty());
1091        let similar = repo.k_similar_to_cluster(10, 10).unwrap();
1092
1093        assert_eq!(
1094            similar.iter().map(|(id, _)| *id).collect::<Vec<_>>(),
1095            vec![2]
1096        );
1097    }
1098}