Skip to main content

smriti/services/face_processor/
clustering.rs

1use super::*;
2
3/// Upper bound on unresolved faces fed into Stage B when the legacy
4/// complete-link path is in use. With `hnsw_clustering` (default-on)
5/// FaceClusterer::cluster runs in O(n log n) so the cap is effectively
6/// infinite; we keep the constant only to bound the legacy fallback
7/// when someone disables the feature for A/B testing.
8#[cfg(not(feature = "hnsw_clustering"))]
9const MAX_STAGE_B_INPUT: usize = 800;
10const MAX_POST_MERGE_CLUSTER_PAIRS: usize = 50_000;
11
12impl FaceProcessor {
13    /// Run incremental clustering in two stages:
14    /// 1) Gallery k-NN retrieval + confidence bands:
15    ///    HIGH      -> auto-assign to top cluster
16    ///    AMBIGUOUS -> queue for user review
17    ///    LOW       -> leave for Stage 2
18    /// 2) Complete-link agglomerative clustering on still-unresolved faces
19    ///
20    /// Public so integration tests (and re-cluster-only flows that skip
21    /// detection) can call it without going through the full
22    /// `process_photos` pipeline.
23    pub fn run_clustering(
24        face_repo: &FaceRepo,
25        clustering_threshold: f32,
26        resolver_weights: crate::ml::ResolverWeights,
27    ) -> Result<usize, String> {
28        let mut assigned_to_existing = 0usize;
29        let mut ambiguous = 0usize;
30        let strict_max_distance = clustering_threshold.clamp(0.15, 0.6);
31
32        // Stage A: gallery-based retrieval with confidence bands.
33        let galleries = face_repo
34            .get_gallery_embeddings()
35            .map_err(|e| format!("Failed to load person galleries: {}", e))?;
36        let cluster_photo_rows = face_repo
37            .get_cluster_photo_ids()
38            .map_err(|e| format!("Failed to load cluster-photo map: {}", e))?;
39        let cannot_merge = face_repo
40            .get_cannot_merge_map()
41            .map_err(|e| format!("Failed to load cannot-merge constraints: {}", e))?;
42
43        let mut cluster_photo_ids: std::collections::HashMap<i64, std::collections::HashSet<i64>> =
44            std::collections::HashMap::new();
45        for (cluster_id, photo_id) in cluster_photo_rows {
46            cluster_photo_ids
47                .entry(cluster_id)
48                .or_default()
49                .insert(photo_id);
50        }
51
52        // Build the gallery slice form retrieve_candidates expects.
53        let mut gallery_by_cluster: std::collections::HashMap<
54            i64,
55            Vec<(i64, crate::ml::FaceEmbedding)>,
56        > = std::collections::HashMap::new();
57        for g in galleries {
58            gallery_by_cluster
59                .entry(g.cluster_id)
60                .or_default()
61                .push((g.face_id, g.embedding));
62        }
63        let gallery_vec: Vec<(i64, Vec<(i64, crate::ml::FaceEmbedding)>)> =
64            gallery_by_cluster.into_iter().collect();
65
66        let banding = crate::ml::BandingConfig::default();
67
68        let unclustered = face_repo
69            .get_unclustered_faces_with_photo_embeddings()
70            .map_err(|e| format!("Failed to get unclustered faces: {}", e))?;
71
72        for (face_id, photo_id, embedding) in &unclustered {
73            // Build exclusion set: clusters already present in this photo
74            // (same-photo conflict) and anything cannot-merge with those.
75            let mut exclude: std::collections::HashSet<i64> = std::collections::HashSet::new();
76            let clusters_in_photo: Vec<i64> = cluster_photo_ids
77                .iter()
78                .filter(|(_, set)| set.contains(photo_id))
79                .map(|(cid, _)| *cid)
80                .collect();
81            for cid in &clusters_in_photo {
82                exclude.insert(*cid);
83                if let Some(forbidden) = cannot_merge.get(cid) {
84                    for f in forbidden {
85                        exclude.insert(*f);
86                    }
87                }
88            }
89
90            let hits = crate::ml::retrieve_candidates(
91                embedding,
92                &gallery_vec,
93                5,
94                1.0 - strict_max_distance, // treat distance threshold as similarity lower bound
95                &exclude,
96            );
97
98            // Context re-rank using co-occurrence and temporal-neighbor signals.
99            let resolver_ctx = Self::build_resolver_context(face_repo, *photo_id, *face_id, &hits);
100            let reranked = crate::ml::rerank(&hits, &resolver_ctx, resolver_weights);
101            let band = crate::ml::retrieval::classify(&reranked, &banding);
102
103            match band {
104                crate::ml::ConfidenceBand::High { hit } => {
105                    face_repo
106                        .assign_face_to_cluster(*face_id, hit.cluster_id)
107                        .map_err(|e| format!("Failed to assign face to cluster: {}", e))?;
108                    cluster_photo_ids
109                        .entry(hit.cluster_id)
110                        .or_default()
111                        .insert(*photo_id);
112                    assigned_to_existing += 1;
113                }
114                crate::ml::ConfidenceBand::Ambiguous { .. } => {
115                    // Too close to call; Stage B decides from scratch.
116                    ambiguous += 1;
117                }
118                crate::ml::ConfidenceBand::Low => {
119                    // Leave unassigned; Stage B (agglomerative) will handle it.
120                }
121            }
122        }
123
124        if ambiguous > 0 {
125            tracing::info!("{} ambiguous faces left for Stage B", ambiguous);
126        }
127
128        // Stage B: complete-link agglomerative clustering on unresolved faces.
129        let unresolved = face_repo
130            .get_unclustered_faces_with_photo_embeddings()
131            .map_err(|e| format!("Failed to reload unresolved faces: {}", e))?;
132
133        if unresolved.is_empty() {
134            face_repo
135                .refresh_all_galleries()
136                .map_err(|e| format!("Failed to refresh galleries: {}", e))?;
137            tracing::info!(
138                "Agglomerative clustering: assigned {} faces to existing galleries; no unresolved faces left",
139                assigned_to_existing
140            );
141            return Ok(0);
142        }
143
144        #[cfg(not(feature = "hnsw_clustering"))]
145        if unresolved.len() > MAX_STAGE_B_INPUT {
146            // Legacy path only: skip Stage B; route unresolved faces
147            // through the rescue pipeline so they remain visible
148            // (auto-matched against galleries) instead of paying the
149            // quadratic cost.
150            tracing::warn!(
151                "Skipping Stage B complete-link clustering: {} unresolved faces exceeds cap of {}. Enable `hnsw_clustering` to remove this cap.",
152                unresolved.len(),
153                MAX_STAGE_B_INPUT
154            );
155            face_repo
156                .refresh_all_galleries()
157                .map_err(|e| format!("Failed to refresh galleries: {}", e))?;
158            let rescued = Self::rescue_orphan_faces(face_repo)?;
159            tracing::info!(
160                "Clustering (Stage B skipped): {} to-existing, {} rescued, from {} unresolved",
161                assigned_to_existing,
162                rescued,
163                unresolved.len()
164            );
165            return Ok(0);
166        }
167
168        let inputs: Vec<ClusterInput> = unresolved
169            .iter()
170            .map(|(face_id, photo_id, emb)| ClusterInput {
171                face_id: *face_id,
172                photo_id: *photo_id,
173                current_cluster_id: None,
174                embedding: emb.clone(),
175            })
176            .collect();
177
178        // Load face_negatives so the clusterer can honour user rejections.
179        let negatives: std::collections::HashSet<(i64, i64)> = {
180            let mut stmt = face_repo
181                .conn
182                .prepare("SELECT face_id, not_cluster_id FROM face_negatives")
183                .map_err(|e| format!("Failed to load negatives: {}", e))?;
184            let rows = stmt
185                .query_map([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?)))
186                .map_err(|e| format!("Failed to query negatives: {}", e))?;
187            let mut set = std::collections::HashSet::new();
188            for row in rows {
189                let pair = row.map_err(|e| format!("Failed to read negative row: {}", e))?;
190                set.insert(pair);
191            }
192            set
193        };
194
195        let clusterer = FaceClusterer::new().with_max_distance(strict_max_distance);
196        let assignments = clusterer.cluster(&inputs, Some(&negatives));
197
198        let mut cluster_groups: HashMap<i32, Vec<i64>> = HashMap::new();
199        for (face_id, cluster_id) in assignments {
200            if cluster_id >= 0 {
201                cluster_groups.entry(cluster_id).or_default().push(face_id);
202            }
203        }
204
205        let mut clusters_created = 0usize;
206        for face_ids in cluster_groups.values() {
207            if face_ids.len() >= 2 {
208                face_repo
209                    .create_cluster(face_ids)
210                    .map_err(|e| format!("Failed to create cluster: {}", e))?;
211                clusters_created += 1;
212            }
213        }
214
215        face_repo
216            .refresh_all_galleries()
217            .map_err(|e| format!("Failed to refresh galleries: {}", e))?;
218
219        // Post-pass: unify clusters that are actually the same person but
220        // got split by complete-link's strictness under lighting variance.
221        // Uses single-link (best pair) across gallery members with a stricter
222        // "multiple good pairs" requirement to avoid false positives.
223        let merged = Self::merge_similar_clusters(face_repo)?;
224
225        // Rescue pass: faces that ended up as singletons (not placed into
226        // any cluster by Stage A or Stage B) need a second chance. Otherwise
227        // they're invisible to the user: they have cluster_id = NULL so they
228        // don't show in People.
229        let rescued = Self::rescue_orphan_faces(face_repo)?;
230
231        // Final fallback: any face still without a cluster becomes its own
232        // singleton cluster. Catches the "small library, every face unique"
233        // case where Stage A had no galleries to match against, Stage B's
234        // complete-link clusterer correctly produced no merges, and the
235        // rescue pass had nothing to compare to either. Without this, those
236        // faces stay cluster_id = NULL forever — invisible in the People
237        // view, even though detection successfully found them.
238        let singletons_promoted = Self::promote_orphans_to_singletons(face_repo)?;
239
240        tracing::info!(
241            "Clustering: {} to-existing, {} new, merged {}, rescued {}, singletons {}, from {} unresolved",
242            assigned_to_existing,
243            clusters_created,
244            merged,
245            rescued,
246            singletons_promoted,
247            unresolved.len()
248        );
249
250        Ok(clusters_created.saturating_sub(merged) + singletons_promoted)
251    }
252
253    /// Rescue pass for orphan faces (cluster_id IS NULL after all earlier
254    /// stages). For each orphan, k-NN retrieve against existing cluster
255    /// galleries with a looser threshold than the first-pass retrieval.
256    /// Classify:
257    ///   - HIGH       (mean top-k sim >= 0.60, 0.08 margin over runner-up):
258    ///     auto-assign to best cluster
259    ///   - otherwise: leave as orphan; a future scan or better gallery
260    ///     may eventually pick it up, and the singleton pass below
261    ///     keeps it visible meanwhile
262    ///
263    /// Returns the number of rescued faces.
264    fn rescue_orphan_faces(face_repo: &FaceRepo) -> Result<usize, String> {
265        // Deliberately looser than first-pass retrieval:
266        // first-pass min_similarity = 1.0 - strict_max_distance ~= 0.58.
267        // We accept weaker gallery members here because the orphan either
268        // didn't fit Stage B's strict complete-link or matched nothing in
269        // Stage A — it may still be a valid match under some gallery member.
270        const RESCUE_MIN_SIM: f32 = 0.45;
271
272        let rescue_banding = crate::ml::BandingConfig {
273            low_threshold: 0.45,
274            high_threshold: 0.60,
275            margin: 0.08,
276        };
277
278        let galleries = face_repo
279            .get_gallery_embeddings()
280            .map_err(|e| format!("Failed to load galleries for rescue: {}", e))?;
281
282        if galleries.is_empty() {
283            // No clusters exist -> nothing to match against.
284            return Ok(0);
285        }
286
287        let mut gallery_by_cluster: HashMap<i64, Vec<(i64, crate::ml::FaceEmbedding)>> =
288            HashMap::new();
289        for g in galleries {
290            gallery_by_cluster
291                .entry(g.cluster_id)
292                .or_default()
293                .push((g.face_id, g.embedding));
294        }
295        let gallery_vec: Vec<(i64, Vec<(i64, crate::ml::FaceEmbedding)>)> =
296            gallery_by_cluster.into_iter().collect();
297
298        let cannot_merge = face_repo
299            .get_cannot_merge_map()
300            .map_err(|e| format!("Failed to load cannot-merge: {}", e))?;
301
302        let cluster_photo_rows = face_repo
303            .get_cluster_photo_ids()
304            .map_err(|e| format!("Failed to load cluster-photo map: {}", e))?;
305        let mut cluster_photo_ids: HashMap<i64, std::collections::HashSet<i64>> = HashMap::new();
306        for (cid, pid) in cluster_photo_rows {
307            cluster_photo_ids.entry(cid).or_default().insert(pid);
308        }
309
310        let orphans = face_repo
311            .get_unclustered_faces_with_photo_embeddings()
312            .map_err(|e| format!("Failed to load orphan faces: {}", e))?;
313
314        let mut rescued = 0usize;
315
316        for (face_id, photo_id, embedding) in &orphans {
317            // Same-photo conflict + cannot-merge-transitively exclusions.
318            let mut exclude: std::collections::HashSet<i64> = std::collections::HashSet::new();
319            let clusters_in_photo: Vec<i64> = cluster_photo_ids
320                .iter()
321                .filter(|(_, set)| set.contains(photo_id))
322                .map(|(cid, _)| *cid)
323                .collect();
324            for cid in &clusters_in_photo {
325                exclude.insert(*cid);
326                if let Some(forbidden) = cannot_merge.get(cid) {
327                    for f in forbidden {
328                        exclude.insert(*f);
329                    }
330                }
331            }
332
333            let hits = crate::ml::retrieve_candidates(
334                embedding,
335                &gallery_vec,
336                5,
337                RESCUE_MIN_SIM,
338                &exclude,
339            );
340            let band = crate::ml::retrieval::classify(&hits, &rescue_banding);
341
342            match band {
343                crate::ml::ConfidenceBand::High { hit } => {
344                    if let Err(e) = face_repo.assign_face_to_cluster(*face_id, hit.cluster_id) {
345                        tracing::warn!("rescue: assign_face_to_cluster failed: {}", e);
346                        continue;
347                    }
348                    cluster_photo_ids
349                        .entry(hit.cluster_id)
350                        .or_default()
351                        .insert(*photo_id);
352                    rescued += 1;
353                }
354                crate::ml::ConfidenceBand::Ambiguous { .. } | crate::ml::ConfidenceBand::Low => {
355                    // Stays an orphan for now.
356                }
357            }
358        }
359
360        Ok(rescued)
361    }
362
363    /// Promote any face still lacking a cluster assignment into its own
364    /// singleton cluster. Runs after every other pass — by the time we
365    /// get here, the face has failed both stages of clustering AND the
366    /// rescue pass. Rather than leave it invisible, we give it a row in
367    /// `face_clusters` so the People view shows it. The UI's
368    /// "Faces seen only once" section is the destination.
369    ///
370    /// Honours `user_confirmed >= 0` so user-hidden faces (set to -1)
371    /// don't get resurrected as singleton clusters.
372    fn promote_orphans_to_singletons(face_repo: &FaceRepo) -> Result<usize, String> {
373        let orphan_ids: Vec<i64> = {
374            let mut stmt = face_repo
375                .conn
376                .prepare(
377                    "SELECT id FROM faces \
378                     WHERE cluster_id IS NULL AND user_confirmed >= 0",
379                )
380                .map_err(|e| format!("Failed to query orphan faces: {}", e))?;
381            let rows = stmt
382                .query_map([], |r| r.get::<_, i64>(0))
383                .map_err(|e| format!("Failed to read orphan faces: {}", e))?;
384            let mut out = Vec::new();
385            for r in rows {
386                out.push(r.map_err(|e| format!("Failed to read orphan row: {}", e))?);
387            }
388            out
389        };
390
391        let mut made = 0usize;
392        for face_id in orphan_ids {
393            match face_repo.create_cluster(&[face_id]) {
394                Ok(_) => made += 1,
395                Err(e) => tracing::warn!(
396                    "Could not promote orphan face {} to singleton cluster: {}",
397                    face_id,
398                    e
399                ),
400            }
401        }
402        Ok(made)
403    }
404
405    /// Unify clusters that likely represent the same person but got split by
406    /// complete-link's strict pairwise requirement.
407    ///
408    /// For each pair (A, B) of existing clusters:
409    ///   - Skip if cannot-merge is set.
410    ///   - Skip if they share any photo (same-photo-different-faces means
411    ///     they must be different people).
412    ///   - Compute cross-cluster similarity using single-link on the gallery:
413    ///     mean of the top-3 cosine similarities across all member pairs.
414    ///   - If the mean top-3 exceeds `merge_threshold`, queue the merge.
415    ///
416    /// Merges are applied in descending score order with a union-find over
417    /// live cluster IDs, so a chain of fragments can all collapse into one.
418    fn merge_similar_clusters(face_repo: &FaceRepo) -> Result<usize, String> {
419        // Tunable: how aggressively to unify fragments. Higher = safer.
420        // Mean of top-3 cross-cluster similarities above this -> merge.
421        const MERGE_THRESHOLD: f32 = 0.55;
422        const TOP_K_PAIRS: usize = 3;
423
424        let galleries = face_repo
425            .get_gallery_embeddings()
426            .map_err(|e| format!("Failed to load galleries: {}", e))?;
427
428        let mut gallery_by_cluster: HashMap<i64, Vec<crate::ml::FaceEmbedding>> = HashMap::new();
429        for g in galleries {
430            gallery_by_cluster
431                .entry(g.cluster_id)
432                .or_default()
433                .push(g.embedding);
434        }
435
436        let cannot_merge = face_repo
437            .get_cannot_merge_map()
438            .map_err(|e| format!("Failed to load cannot-merge: {}", e))?;
439
440        let cluster_photo_rows = face_repo
441            .get_cluster_photo_ids()
442            .map_err(|e| format!("Failed to load cluster-photo map: {}", e))?;
443        let mut cluster_photos: HashMap<i64, std::collections::HashSet<i64>> = HashMap::new();
444        for (cid, pid) in cluster_photo_rows {
445            cluster_photos.entry(cid).or_default().insert(pid);
446        }
447
448        let cluster_ids: Vec<i64> = gallery_by_cluster.keys().copied().collect();
449        let pair_count = post_merge_pair_count(cluster_ids.len());
450        if pair_count > MAX_POST_MERGE_CLUSTER_PAIRS {
451            tracing::info!(
452                "Skipping post-pass face-cluster merge: {} cluster pairs exceeds cap {}",
453                pair_count,
454                MAX_POST_MERGE_CLUSTER_PAIRS
455            );
456            return Ok(0);
457        }
458
459        let mut candidates: Vec<(f32, i64, i64)> = Vec::new();
460
461        for i in 0..cluster_ids.len() {
462            for j in (i + 1)..cluster_ids.len() {
463                let a = cluster_ids[i];
464                let b = cluster_ids[j];
465
466                if cannot_merge.get(&a).is_some_and(|set| set.contains(&b)) {
467                    continue;
468                }
469
470                let photos_a = cluster_photos.get(&a);
471                let photos_b = cluster_photos.get(&b);
472                let shares_photo = match (photos_a, photos_b) {
473                    (Some(pa), Some(pb)) => pa.iter().any(|p| pb.contains(p)),
474                    _ => false,
475                };
476                if shares_photo {
477                    continue;
478                }
479
480                let ga = gallery_by_cluster
481                    .get(&a)
482                    .map(|v| v.as_slice())
483                    .unwrap_or(&[]);
484                let gb = gallery_by_cluster
485                    .get(&b)
486                    .map(|v| v.as_slice())
487                    .unwrap_or(&[]);
488                if ga.is_empty() || gb.is_empty() {
489                    continue;
490                }
491
492                let mut sims: Vec<f32> = Vec::with_capacity(ga.len() * gb.len());
493                for ea in ga {
494                    for eb in gb {
495                        let s = ea.cosine_similarity(eb);
496                        if s.is_nan() {
497                            continue;
498                        }
499                        sims.push(s);
500                    }
501                }
502                if sims.is_empty() {
503                    continue;
504                }
505                sims.sort_by(|x, y| y.total_cmp(x));
506                let k = TOP_K_PAIRS.min(sims.len());
507                let mean_top_k: f32 = sims.iter().take(k).sum::<f32>() / k as f32;
508
509                if mean_top_k >= MERGE_THRESHOLD {
510                    candidates.push((mean_top_k, a, b));
511                }
512            }
513        }
514
515        candidates.sort_by(|x, y| y.0.total_cmp(&x.0));
516
517        // Union-find: each cluster starts pointing to itself; merges redirect.
518        let mut parent: HashMap<i64, i64> = cluster_ids.iter().map(|&c| (c, c)).collect();
519        fn find(parent: &mut HashMap<i64, i64>, mut x: i64) -> i64 {
520            loop {
521                let p = *parent.get(&x).unwrap_or(&x);
522                if p == x {
523                    return x;
524                }
525                // Path compression.
526                let pp = *parent.get(&p).unwrap_or(&p);
527                parent.insert(x, pp);
528                x = pp;
529            }
530        }
531
532        let mut merged_count = 0usize;
533        for (score, a, b) in candidates {
534            let ra = find(&mut parent, a);
535            let rb = find(&mut parent, b);
536            if ra == rb {
537                continue;
538            }
539            // Keep the smaller cluster id as the survivor (arbitrary but stable).
540            let (survivor, casualty) = if ra < rb { (ra, rb) } else { (rb, ra) };
541            match face_repo.merge_clusters(casualty, survivor) {
542                Ok(_) => {
543                    parent.insert(casualty, survivor);
544                    merged_count += 1;
545                    tracing::info!(
546                        "Post-pass merge: cluster {} -> {} (score {:.3})",
547                        casualty,
548                        survivor,
549                        score
550                    );
551                }
552                Err(e) => {
553                    tracing::warn!("merge_similar_clusters: merge failed {}: {}", casualty, e);
554                }
555            }
556        }
557
558        Ok(merged_count)
559    }
560
561    /// Save a face crop image to disk as JPEG, at the aligned face's own
562    /// 112×112: shrinking it further left too little detail to tell people
563    /// apart when the crop is shown large ("Find more like this").
564    pub(crate) fn save_face_crop(
565        aligned_face: &image::RgbImage,
566        path: &Path,
567    ) -> Result<(), image::ImageError> {
568        aligned_face.save(path)
569    }
570
571    /// Get the face crops directory for a drive.
572    pub fn faces_dir(drive_path: &Path) -> PathBuf {
573        crate::services::cache_location::faces_dir(drive_path)
574    }
575
576    /// Streaming Stage A — run *only* the gallery-match leg of the
577    /// clustering pipeline so faces appear in the People view as the
578    /// writer thread commits chunks. Stage B (complete-link / new
579    /// cluster creation) and the rescue pass stay end-of-pipeline,
580    /// because both need the full unresolved set to make sane
581    /// decisions.
582    ///
583    /// HIGH-band hits are auto-assigned. AMBIGUOUS hits go onto the
584    /// review queue (so the badge bumps). LOW hits stay unassigned
585    /// for end-of-run clustering to handle.
586    pub(crate) fn stream_assign_existing_clusters(
587        face_repo: &FaceRepo,
588        after_id: i64,
589        clustering_threshold: f32,
590        resolver_weights: crate::ml::ResolverWeights,
591    ) -> Result<usize, String> {
592        let strict_max_distance = clustering_threshold.clamp(0.15, 0.6);
593
594        let galleries = face_repo
595            .get_gallery_embeddings()
596            .map_err(|e| format!("stream Stage A: load galleries: {}", e))?;
597        if galleries.is_empty() {
598            // No existing clusters yet; nothing to match against. Wait
599            // for end-of-run Stage B to seed the first set of people.
600            return Ok(0);
601        }
602
603        let cluster_photo_rows = face_repo
604            .get_cluster_photo_ids()
605            .map_err(|e| format!("stream Stage A: cluster-photo map: {}", e))?;
606        let cannot_merge = face_repo
607            .get_cannot_merge_map()
608            .map_err(|e| format!("stream Stage A: cannot-merge: {}", e))?;
609
610        let mut cluster_photo_ids: HashMap<i64, std::collections::HashSet<i64>> = HashMap::new();
611        for (cid, pid) in cluster_photo_rows {
612            cluster_photo_ids.entry(cid).or_default().insert(pid);
613        }
614
615        let mut gallery_by_cluster: HashMap<i64, Vec<(i64, crate::ml::FaceEmbedding)>> =
616            HashMap::new();
617        for g in galleries {
618            gallery_by_cluster
619                .entry(g.cluster_id)
620                .or_default()
621                .push((g.face_id, g.embedding));
622        }
623        let gallery_vec: Vec<(i64, Vec<(i64, crate::ml::FaceEmbedding)>)> =
624            gallery_by_cluster.into_iter().collect();
625
626        let banding = crate::ml::BandingConfig::default();
627        let unclustered = face_repo
628            .get_unclustered_embeddings_after(after_id)
629            .map_err(|e| format!("stream Stage A: get unclustered: {}", e))?;
630
631        let mut assigned = 0usize;
632        for (face_id, photo_id, embedding) in &unclustered {
633            let mut exclude: std::collections::HashSet<i64> = std::collections::HashSet::new();
634            let clusters_in_photo: Vec<i64> = cluster_photo_ids
635                .iter()
636                .filter(|(_, set)| set.contains(photo_id))
637                .map(|(cid, _)| *cid)
638                .collect();
639            for cid in &clusters_in_photo {
640                exclude.insert(*cid);
641                if let Some(forbidden) = cannot_merge.get(cid) {
642                    for f in forbidden {
643                        exclude.insert(*f);
644                    }
645                }
646            }
647
648            let hits = crate::ml::retrieve_candidates(
649                embedding,
650                &gallery_vec,
651                5,
652                1.0 - strict_max_distance,
653                &exclude,
654            );
655            let resolver_ctx = Self::build_resolver_context(face_repo, *photo_id, *face_id, &hits);
656            let reranked = crate::ml::rerank(&hits, &resolver_ctx, resolver_weights);
657            let band = crate::ml::retrieval::classify(&reranked, &banding);
658
659            match band {
660                crate::ml::ConfidenceBand::High { hit }
661                    if face_repo
662                        .assign_face_to_cluster(*face_id, hit.cluster_id)
663                        .is_ok() =>
664                {
665                    cluster_photo_ids
666                        .entry(hit.cluster_id)
667                        .or_default()
668                        .insert(*photo_id);
669                    assigned += 1;
670                }
671                _ => {
672                    // AMBIGUOUS / LOW: leave for end-of-run pipeline.
673                }
674            }
675        }
676
677        Ok(assigned)
678    }
679}
680
681fn post_merge_pair_count(cluster_count: usize) -> usize {
682    cluster_count.saturating_mul(cluster_count.saturating_sub(1)) / 2
683}
684
685#[cfg(test)]
686mod tests {
687    use super::*;
688
689    #[test]
690    fn post_merge_pair_count_bounds_quadratic_pass() {
691        assert_eq!(post_merge_pair_count(0), 0);
692        assert_eq!(post_merge_pair_count(1), 0);
693        assert_eq!(post_merge_pair_count(316), 49_770);
694        assert_eq!(post_merge_pair_count(317), 50_086);
695    }
696}