Skip to main content

smriti/services/
face_processor.rs

1//! Face processing pipeline
2//!
3//! Orchestrates the face detection -> embedding -> clustering workflow.
4//! Uses rayon for parallel photo processing with thread-local ONNX sessions.
5
6use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
9use std::sync::{mpsc, Arc, Mutex};
10
11use rayon::prelude::*;
12
13use crate::db::face_repo::FaceRepo;
14use crate::db::Database;
15use crate::db::InferredIdentityRepo;
16use crate::ml::{
17    ClusterInput, FaceClusterer, FaceDetector, FaceEmbedder, FaceEmbedding, OnnxRuntime,
18};
19use crate::services::image_utils::apply_exif_orientation;
20use crate::services::path_util::safe_join_relative;
21
22/// Failed face-detection runs after which a photo is given up on.
23const MAX_FACE_ATTEMPTS: i64 = 3;
24
25/// Coarse progress phase. The UI uses this to keep the bar moving past
26/// the per-photo loop into clustering, so we never sit at "x/x" while
27/// the post-processing tail runs.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum FaceProcessingStage {
30    /// Per-photo detect + embed loop. `processed` counts photos.
31    Detecting,
32    /// Stage 3 propagation + Stage 4 clustering — runs once after the
33    /// per-photo loop finishes. `processed` is capped at 95% of `total`
34    /// so the UI shows a "wrapping up" state instead of staying at 100%.
35    Finishing,
36    /// Pipeline complete. `processed == total`.
37    Done,
38}
39
40/// Where face embeddings are being computed for this run.
41///
42/// Detection is always local — only the embedding (112×112 → 512-d
43/// step) can be offloaded. This is surfaced to the frontend so the
44/// user can confirm at a glance whether their cloud bridge is
45/// actually carrying load, vs silently falling back to local.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum EmbedderRoute {
48    /// Local ONNX session — the default path.
49    Local,
50    /// Configured remote bridge — embeddings POSTed as 112×112 crops.
51    Bridge,
52}
53
54impl EmbedderRoute {
55    pub fn as_str(self) -> &'static str {
56        match self {
57            EmbedderRoute::Local => "local",
58            EmbedderRoute::Bridge => "bridge",
59        }
60    }
61}
62
63/// Progress information for face processing
64#[derive(Debug, Clone)]
65pub struct FaceProcessingProgress {
66    pub processed: usize,
67    pub total: usize,
68    pub faces_found: usize,
69    /// Wall-clock seconds since processing started.
70    pub elapsed_secs: f64,
71    pub stage: FaceProcessingStage,
72    /// Number of streaming flushes the writer thread has committed so
73    /// far. The UI watches this and refreshes the People view when it
74    /// increments — that's how new clusters appear during a long run
75    /// instead of only at the end.
76    pub chunks_flushed: u32,
77    /// Where embeddings are running for this job. Set at job start
78    /// based on `face_gpu_bridge_enabled` + URL + a one-shot /health
79    /// probe; doesn't track runtime fallback (the 3-strikes circuit
80    /// breaker inside RemoteEmbedder will silently switch to local
81    /// without flipping this flag). Use the Test Connection button
82    /// in Settings if you need a live health check.
83    pub embedder_route: EmbedderRoute,
84}
85
86impl Default for FaceProcessingProgress {
87    fn default() -> Self {
88        Self {
89            processed: 0,
90            total: 0,
91            faces_found: 0,
92            elapsed_secs: 0.0,
93            stage: FaceProcessingStage::Detecting,
94            chunks_flushed: 0,
95            embedder_route: EmbedderRoute::Local,
96        }
97    }
98}
99
100/// Result of a face processing run
101#[derive(Debug, Clone)]
102pub struct FaceProcessingResult {
103    pub photos_processed: usize,
104    pub faces_detected: usize,
105    pub clusters_created: usize,
106    pub rejected_small: usize,
107    pub rejected_lowconf: usize,
108    pub rejected_blurry: usize,
109    pub rejected_yaw: usize,
110}
111
112/// Result of processing a single photo (collected from parallel workers)
113struct PhotoFaceResult {
114    photo_id: i64,
115    file_path: String,
116    faces: Vec<FaceInsert>,
117    taken_ts: Option<i64>,
118    brightness: f32,
119    had_error: bool,
120}
121
122/// Lightweight summary kept around after a result has been handed off
123/// to the writer thread. Stage 3 (contextual identity propagation)
124/// runs over these — it doesn't need the (large) face crops or
125/// embeddings, just enough to look up neighbors.
126struct ProcessedPhotoSummary {
127    photo_id: i64,
128    file_path: String,
129    taken_ts: Option<i64>,
130    brightness: f32,
131    had_error: bool,
132    has_faces: bool,
133}
134
135/// A face ready for DB insertion
136struct FaceInsert {
137    bbox_normalized: (f32, f32, f32, f32),
138    confidence: f32,
139    embedding: FaceEmbedding,
140    aligned_face: image::RgbImage,
141}
142
143struct ContextPropagationInput<'a> {
144    drive_path: &'a Path,
145    photo_id: i64,
146    file_path: &'a str,
147    target_ts: i64,
148    target_brightness: f32,
149    brightness_map: &'a HashMap<i64, f32>,
150}
151
152/// Face processing pipeline
153///
154/// Call `process_photos` to run the full detect -> embed -> cluster pipeline.
155pub struct FaceProcessor;
156
157impl FaceProcessor {
158    const CONTEXT_WINDOW_SECS: i64 = 60;
159    const CONTEXT_MIN_CONFIDENCE: f32 = 0.5;
160
161    /// Run the full face processing pipeline on unprocessed photos.
162    ///
163    /// Uses rayon for parallel detection/embedding with thread-local ONNX sessions,
164    /// then batches DB writes for efficiency.
165    pub fn process_photos(
166        drive_path: &Path,
167        model_dir: &Path,
168        detector_confidence: f32,
169        clustering_threshold: f32,
170        resolver_weights: crate::ml::ResolverWeights,
171        progress_tx: Option<async_channel::Sender<FaceProcessingProgress>>,
172        cancel_flag: Option<Arc<AtomicBool>>,
173    ) -> Result<FaceProcessingResult, String> {
174        // Open database
175        let db = Database::open_for_drive(drive_path)
176            .map_err(|e| format!("Failed to open database: {}", e))?;
177        let face_repo = FaceRepo::new(&db.conn);
178
179        // Get unprocessed photos. Do not reset every processing flag merely
180        // because the library currently contains no faces: a legitimate
181        // no-face library would otherwise be processed again on every run.
182        let unprocessed = face_repo
183            .get_unprocessed_photos_with_context()
184            .map_err(|e| format!("Failed to get unprocessed photos: {}", e))?;
185
186        let inferred_repo = InferredIdentityRepo::new(&db.conn);
187
188        let total = unprocessed.len();
189        if total == 0 {
190            let clusters_created =
191                Self::run_clustering(&face_repo, clustering_threshold, resolver_weights)?;
192            return Ok(FaceProcessingResult {
193                photos_processed: 0,
194                faces_detected: 0,
195                clusters_created,
196                rejected_small: 0,
197                rejected_lowconf: 0,
198                rejected_blurry: 0,
199                rejected_yaw: 0,
200            });
201        }
202
203        let pipeline_start = std::time::Instant::now();
204
205        // Initialize ONNX Runtime. The bare error from `OnnxRuntime::init`
206        // is already explicit ("library not found, set ORT_DYLIB_PATH or
207        // place libonnxruntime.so..."); the previous wrapper duplicated
208        // those instructions and produced a wall-of-text toast. Keep the
209        // toast short and point users at the setup that installs
210        // everything in one shot.
211        let runtime = OnnxRuntime::init().map_err(|e| {
212            format!(
213                "Face detection unavailable — {}. Enable face recognition in People or Settings.",
214                e
215            )
216        })?;
217
218        let detector_path = model_dir.join("scrfd_10g_bnkps.onnx");
219        let cfg = crate::config::AppConfig::load();
220        let embedder_path = model_dir.join(&cfg.face_embedder_model);
221        // Captured per-worker so the embedder can be built once per
222        // thread. Cloned cheaply via Arc<String>.
223        let gpu_bridge_url: Option<String> = if cfg.face_gpu_bridge_enabled {
224            cfg.face_gpu_bridge_url.clone()
225        } else {
226            None
227        };
228        let embedder_model_name: String = cfg.face_embedder_model.clone();
229        // Snapshot intended routing so the UI can show whether
230        // embedding is heading to the bridge or running locally for
231        // this run. We don't probe /health here — workers do that on
232        // their own when they construct the embedder, and per-thread
233        // results would be racy to aggregate. The chip on the UI
234        // reflects intent; live health is the Test Connection button.
235        let embedder_route = if gpu_bridge_url.is_some() {
236            EmbedderRoute::Bridge
237        } else {
238            EmbedderRoute::Local
239        };
240
241        if !detector_path.exists() {
242            return Err(
243                "Face detection model is missing. Enable face recognition in People or Settings."
244                    .to_string(),
245            );
246        }
247        if !embedder_path.exists() && gpu_bridge_url.is_none() {
248            return Err(
249                "Face embedding model is missing. Enable face recognition in People or Settings, or configure a healthy remote GPU bridge."
250                    .to_string(),
251            );
252        }
253
254        // Create faces directory
255        let faces_dir = Self::faces_dir(drive_path);
256        if let Err(e) = std::fs::create_dir_all(&faces_dir) {
257            tracing::warn!("Failed to create faces directory: {}", e);
258        }
259
260        tracing::info!("Face processing: {} photos to process", total);
261
262        // Determine parallelism
263        let available_cpus = std::thread::available_parallelism()
264            .map(|n| n.get())
265            .unwrap_or(4);
266        // Bumped from 6 → 8 because the new two-stage pipeline does
267        // most of its work on tiny thumbnails; per-worker memory is a
268        // fraction of what it was when each worker held a 24 MP
269        // RGB buffer. 8 saturates an 8-core machine without OOM risk.
270        let (num_workers, intra_threads, cpu_budget) = background_face_budget(available_cpus);
271
272        tracing::info!(
273            "Face pipeline: {} workers, {} intra-threads per session ({} CPUs, budget {})",
274            num_workers,
275            intra_threads,
276            available_cpus,
277            cpu_budget
278        );
279
280        // Build a custom rayon thread pool so we don't pollute the global pool
281        let pool = rayon::ThreadPoolBuilder::new()
282            .num_threads(num_workers)
283            .build()
284            .map_err(|e| format!("Failed to create thread pool: {}", e))?;
285
286        let processed_count = Arc::new(AtomicUsize::new(0));
287        let faces_count = Arc::new(AtomicUsize::new(0));
288        let rejected_small = Arc::new(AtomicUsize::new(0));
289        let rejected_lowconf = Arc::new(AtomicUsize::new(0));
290        let rejected_blurry = Arc::new(AtomicUsize::new(0));
291        let rejected_yaw = Arc::new(AtomicUsize::new(0));
292        let cancel = cancel_flag
293            .clone()
294            .unwrap_or_else(|| Arc::new(AtomicBool::new(false)));
295        // Bumped by the streaming writer after every chunk commit. The
296        // UI uses this signal to refresh the People view mid-run so
297        // newly-detected faces show up before the whole pipeline ends.
298        let chunks_flushed = Arc::new(AtomicUsize::new(0));
299
300        // Shared paths for thread-local session init
301        let detector_path = Arc::new(detector_path);
302        let embedder_path = Arc::new(embedder_path);
303        let drive_path_arc = Arc::new(drive_path.to_path_buf());
304
305        // ---- Streaming writer thread ----
306        // Owns its own DB connection (rusqlite Connection isn't Send,
307        // so we can't share `db.conn` here). Drains chunks of
308        // PhotoFaceResult from the channel below, transactionally
309        // writes faces + flips faces_processed, and bumps the
310        // chunks_flushed atomic so the UI can refresh mid-run.
311        // Smaller chunks → more frequent UI refreshes during a run.
312        // The writer thread is fast (one transaction per flush), so the
313        // overhead of 5× more flushes is negligible compared to the
314        // visual win: faces appear in the People grid every ~5 photos
315        // instead of every ~25.
316        const FLUSH_CHUNK: usize = 5;
317        let (chunk_tx, chunk_rx) = mpsc::sync_channel::<Vec<PhotoFaceResult>>(4);
318        let writer_handle: std::thread::JoinHandle<Result<(usize, usize), String>> = {
319            let drive_path_buf = drive_path.to_path_buf();
320            let faces_dir_buf = faces_dir.clone();
321            let chunks_flushed = chunks_flushed.clone();
322            let cancel = cancel.clone();
323            let writer_resolver_weights = resolver_weights;
324            std::thread::spawn(move || -> Result<(usize, usize), String> {
325                let writer_db = Database::open_for_drive(&drive_path_buf)
326                    .map_err(|e| format!("Failed to open writer DB: {}", e))?;
327                let mut total_faces = 0usize;
328                let mut photos_processed = 0usize;
329                while let Ok(chunk) = chunk_rx.recv() {
330                    let was_cancelled = cancel.load(Ordering::Relaxed);
331                    let (faces_added, photos_added) = flush_result_chunk(
332                        &writer_db,
333                        &faces_dir_buf,
334                        &chunk,
335                        was_cancelled,
336                        &chunks_flushed,
337                        clustering_threshold,
338                        writer_resolver_weights,
339                    )?;
340                    total_faces += faces_added;
341                    photos_processed += photos_added;
342                }
343                Ok((total_faces, photos_processed))
344            })
345        };
346
347        // ---- Stage 1: Parallel Detection + Embedding (streaming) ----
348        let summaries: Arc<Mutex<Vec<ProcessedPhotoSummary>>> = Arc::new(Mutex::new(Vec::new()));
349        let buffer: Arc<Mutex<Vec<PhotoFaceResult>>> =
350            Arc::new(Mutex::new(Vec::with_capacity(FLUSH_CHUNK)));
351        let chunk_tx = Arc::new(chunk_tx);
352        pool.install(|| {
353            unprocessed
354                .par_iter()
355                .for_each(|(photo_id, file_path, orientation, taken_ts, file_hash)| {
356                    // Skip entirely on cancellation — don't mark this
357                    // photo processed, so a future run will retry it.
358                    if cancel.load(Ordering::Relaxed) {
359                        return;
360                    }
361                    // A panic in a decoder or ONNX session fails this
362                    // photo only; the rest of the batch carries on.
363                    let guarded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> PhotoFaceResult {
364
365                    // Thread-local ONNX sessions
366                    thread_local! {
367                        static DETECTOR: std::cell::RefCell<Option<FaceDetector>> = const { std::cell::RefCell::new(None) };
368                        static EMBEDDER: std::cell::RefCell<Option<FaceEmbedder>> = const { std::cell::RefCell::new(None) };
369                    }
370
371                    // Ensure sessions are initialized for this thread
372                    let det_path = detector_path.clone();
373                    let emb_path = embedder_path.clone();
374                    DETECTOR.with(|d| {
375                        if d.borrow().is_none() {
376                            match FaceDetector::new_with_threads(&runtime, det_path.as_ref(), intra_threads) {
377                                Ok(det) => {
378                                    *d.borrow_mut() = Some(det.with_confidence_threshold(detector_confidence));
379                                }
380                                Err(e) => {
381                                    tracing::error!("Failed to init detector in worker: {}", e);
382                                }
383                            }
384                        }
385                    });
386                    EMBEDDER.with(|e| {
387                        if e.borrow().is_none() {
388                            let embedder_cfg = crate::ml::EmbedderConfig {
389                                model_path: emb_path.as_ref().clone(),
390                                gpu_bridge_url: gpu_bridge_url.clone(),
391                                expected_model: embedder_model_name.clone(),
392                                intra_threads,
393                            };
394                            match FaceEmbedder::from_config(&runtime, &embedder_cfg) {
395                                Ok(emb) => {
396                                    *e.borrow_mut() = Some(emb);
397                                }
398                                Err(e_err) => {
399                                    tracing::error!("Failed to init embedder in worker: {}", e_err);
400                                }
401                            }
402                        }
403                    });
404
405                    // Two-stage decode: detect on the cheap cached
406                    // thumbnail, embed on the full image. SCRFD
407                    // downsamples to 640×640 internally so detection
408                    // accuracy doesn't care about the source size; it's
409                    // the ArcFace 112×112 alignment crop that needs
410                    // resolution. Decoding a 24 MP HEIC takes ~250 ms
411                    // vs ~5 ms for the 860 px thumb — for the ~80% of
412                    // photos that have zero faces, we skip the full
413                    // decode entirely.
414                    let full_path = match safe_join_relative(&drive_path_arc, file_path) {
415                        Ok(path) => path,
416                        Err(e) => {
417                            tracing::debug!("Invalid stored photo path {}: {}", file_path, e);
418                            processed_count.fetch_add(1, Ordering::Relaxed);
419                            return PhotoFaceResult {
420                                photo_id: *photo_id,
421                                file_path: file_path.clone(),
422                                faces: Vec::new(),
423                                taken_ts: *taken_ts,
424                                brightness: 0.0,
425                                had_error: true,
426                            };
427                        }
428                    };
429                    let large_thumb = crate::services::cache_location::thumbnails_dir(&drive_path_arc)
430                        .join("large")
431                        .join("v2")
432                        .join(&file_hash[..2.min(file_hash.len())])
433                        .join(format!("{}.jpg", file_hash));
434
435                    // ---- Stage 1: detect on the thumbnail when present ----
436                    let detect_image: image::DynamicImage = if large_thumb.exists() {
437                        match image::ImageReader::open(&large_thumb)
438                            .ok()
439                            .and_then(|r| r.with_guessed_format().ok())
440                            .and_then(|r| r.decode().ok())
441                        {
442                            Some(img) => img,
443                            None => match crate::services::image_io::open_image(&full_path) {
444                                Ok(img) => {
445                                    let img = apply_exif_orientation(img, *orientation);
446                                    let max_dim = img.width().max(img.height());
447                                    if max_dim > 2048 {
448                                        img.resize(2048, 2048, image::imageops::FilterType::Triangle)
449                                    } else {
450                                        img
451                                    }
452                                }
453                                Err(e) => {
454                                    tracing::debug!("Failed to open image {}: {}", file_path, e);
455                                    processed_count.fetch_add(1, Ordering::Relaxed);
456                                    return PhotoFaceResult {
457                                        photo_id: *photo_id,
458                                        file_path: file_path.clone(),
459                                        faces: Vec::new(),
460                                        taken_ts: *taken_ts,
461                                        brightness: 0.0,
462                                        had_error: true,
463                                    };
464                                }
465                            },
466                        }
467                    } else {
468                        // No thumbnail yet — decode full and use it for
469                        // both stages.
470                        match crate::services::image_io::open_image(&full_path) {
471                            Ok(img) => {
472                                let img = apply_exif_orientation(img, *orientation);
473                                let max_dim = img.width().max(img.height());
474                                if max_dim > 2048 {
475                                    img.resize(2048, 2048, image::imageops::FilterType::Triangle)
476                                } else {
477                                    img
478                                }
479                            }
480                            Err(e) => {
481                                tracing::debug!("Failed to open image {}: {}", file_path, e);
482                                processed_count.fetch_add(1, Ordering::Relaxed);
483                                return PhotoFaceResult {
484                                    photo_id: *photo_id,
485                                    file_path: file_path.clone(),
486                                    faces: Vec::new(),
487                                    taken_ts: *taken_ts,
488                                    brightness: 0.0,
489                                    had_error: true,
490                                };
491                            }
492                        }
493                    };
494
495                    // Brightness needs only thumbnail resolution.
496                    let brightness = Self::average_brightness(&detect_image);
497
498                    if cancel.load(Ordering::Relaxed) {
499                        return PhotoFaceResult {
500                            photo_id: *photo_id,
501                            file_path: file_path.clone(),
502                            faces: Vec::new(),
503                            taken_ts: *taken_ts,
504                            brightness,
505                            had_error: true,
506                        };
507                    }
508
509                    // Detect faces on the thumbnail.
510                    let mut detected = DETECTOR.with(|d| {
511                        let mut borrow = d.borrow_mut();
512                        match borrow.as_mut() {
513                            Some(det) => det.detect_adaptive(&detect_image),
514                            None => Vec::new(),
515                        }
516                    });
517
518                    // ---- Stage 2: re-align faces against the full
519                    // image for crisp embeddings. We only pay the
520                    // full-decode cost when faces actually exist.
521                    if !detected.is_empty() && large_thumb.exists() {
522                        if let Ok(full_img) =
523                            crate::services::image_io::open_image(&full_path)
524                        {
525                            let full_img = apply_exif_orientation(full_img, *orientation);
526                            let scale_x =
527                                full_img.width() as f32 / detect_image.width() as f32;
528                            let scale_y =
529                                full_img.height() as f32 / detect_image.height() as f32;
530                            for face in detected.iter_mut() {
531                                let mut scaled = face.landmarks;
532                                for lm in &mut scaled {
533                                    lm.0 *= scale_x;
534                                    lm.1 *= scale_y;
535                                }
536                                if let Some(aligned) =
537                                    crate::ml::alignment::align_face_112(&full_img, &scaled)
538                                {
539                                    face.aligned_face = Some(aligned);
540                                }
541                            }
542                        }
543                    }
544
545                    if !detected.is_empty() {
546                        tracing::info!(
547                            "Photo: {} faces detected in {}",
548                            detected.len(),
549                            file_path
550                        );
551                    }
552
553                    // Cancel check: post-detect, before per-face embeds.
554                    if cancel.load(Ordering::Relaxed) {
555                        return PhotoFaceResult {
556                            photo_id: *photo_id,
557                            file_path: file_path.clone(),
558                            faces: Vec::new(),
559                            taken_ts: *taken_ts,
560                            brightness,
561                            had_error: true,
562                        };
563                    }
564
565                    // Collect faces that pass quality gates, then embed as a single
566                    // batch. Group photos can have 8+ faces; batching eliminates
567                    // 3-5 separate ONNX sessions into one.
568                    let mut qualifying: Vec<(usize, &image::RgbImage)> = Vec::new();
569                    for (fi, face) in detected.iter().enumerate() {
570                        if cancel.load(Ordering::Relaxed) {
571                            break;
572                        }
573                        let (_bx, _by, bw, bh) = face.bbox;
574                        if bw * bh < Self::MIN_FACE_AREA_PX2 {
575                            rejected_small.fetch_add(1, Ordering::Relaxed);
576                            continue;
577                        }
578                        if face.confidence < Self::MIN_FACE_CONFIDENCE {
579                            rejected_lowconf.fetch_add(1, Ordering::Relaxed);
580                            continue;
581                        }
582                        let aligned = match face.aligned_face.as_ref() {
583                            Some(a) => a,
584                            None => continue,
585                        };
586                        let sharpness = Self::laplacian_variance(aligned);
587                        if sharpness < Self::MIN_LAPLACIAN_VAR {
588                            rejected_blurry.fetch_add(1, Ordering::Relaxed);
589                            continue;
590                        }
591                        let yaw = crate::ml::face_detector::estimate_yaw_from_landmarks(
592                            &face.landmarks,
593                        );
594                        if yaw > Self::MAX_FACE_YAW_DEG {
595                            rejected_yaw.fetch_add(1, Ordering::Relaxed);
596                            continue;
597                        }
598                        qualifying.push((fi, aligned));
599                    }
600
601                    let crops: Vec<image::RgbImage> = qualifying
602                        .iter()
603                        .map(|(_, a)| (*a).clone())
604                        .collect();
605                    let batch_embs = if crops.is_empty() {
606                        Vec::new()
607                    } else {
608                        EMBEDDER.with(|e| {
609                            let mut borrow = e.borrow_mut();
610                            borrow
611                                .as_mut()
612                                .map_or(Vec::new(), |emb| emb.embed_batch(&crops))
613                        })
614                    };
615
616                    let mut face_inserts = Vec::new();
617                    for (bi, &(fi, _aligned)) in qualifying.iter().enumerate() {
618                        if let Some(embedding) = batch_embs.get(bi).and_then(|e: &Option<FaceEmbedding>| e.clone()) {
619                            face_inserts.push(FaceInsert {
620                                bbox_normalized: detected[fi].bbox_normalized,
621                                confidence: detected[fi].confidence,
622                                embedding,
623                                aligned_face: detected[fi].aligned_face.clone().unwrap_or_default(),
624                            });
625                        }
626                    }
627
628                    faces_count.fetch_add(face_inserts.len(), Ordering::Relaxed);
629                    processed_count.fetch_add(1, Ordering::Relaxed);
630
631                    PhotoFaceResult {
632                        photo_id: *photo_id,
633                        file_path: file_path.clone(),
634                        faces: face_inserts,
635                        taken_ts: *taken_ts,
636                        brightness,
637                        had_error: false,
638                    }
639                    }));
640                    let result = guarded.unwrap_or_else(|_| {
641                        tracing::warn!("face processing crashed on {file_path}; skipping it");
642                        processed_count.fetch_add(1, Ordering::Relaxed);
643                        PhotoFaceResult {
644                            photo_id: *photo_id,
645                            file_path: file_path.clone(),
646                            faces: Vec::new(),
647                            taken_ts: *taken_ts,
648                            brightness: 0.0,
649                            had_error: true,
650                        }
651                    });
652
653                    if let Some(ref tx) = progress_tx {
654                        let _ = tx.try_send(FaceProcessingProgress {
655                            processed: processed_count.load(Ordering::Relaxed),
656                            total,
657                            faces_found: faces_count.load(Ordering::Relaxed),
658                            elapsed_secs: pipeline_start.elapsed().as_secs_f64(),
659                            stage: FaceProcessingStage::Detecting,
660                            chunks_flushed: chunks_flushed.load(Ordering::Relaxed) as u32,
661                            embedder_route,
662                        });
663                    }
664
665                    // Record summary BEFORE handing the result off — the
666                    // writer thread takes ownership of `result`, but
667                    // Stage 3 still needs the photo metadata.
668                    summaries
669                        .lock()
670                        .unwrap_or_else(|e| e.into_inner())
671                        .push(ProcessedPhotoSummary {
672                        photo_id: result.photo_id,
673                        file_path: result.file_path.clone(),
674                        taken_ts: result.taken_ts,
675                        brightness: result.brightness,
676                        had_error: result.had_error,
677                        has_faces: !result.faces.is_empty(),
678                    });
679
680                    // Push into the streaming buffer. When it hits
681                    // FLUSH_CHUNK, ship the chunk to the writer thread
682                    // so the user sees faces appear mid-run AND the
683                    // photos are persisted as faces_processed=TRUE.
684                    let mut buf = buffer.lock().unwrap_or_else(|e| e.into_inner());
685                    buf.push(result);
686                    if buf.len() >= FLUSH_CHUNK {
687                        let chunk = std::mem::replace(&mut *buf, Vec::with_capacity(FLUSH_CHUNK));
688                        drop(buf);
689                        // send blocks if writer is behind — that's fine,
690                        // it's natural backpressure that prevents memory
691                        // blow-up on a fast detector / slow disk.
692                        let _ = chunk_tx.send(chunk);
693                    }
694                });
695        });
696
697        // Final flush of any sub-FLUSH_CHUNK leftover photos.
698        {
699            let leftover = std::mem::take(&mut *buffer.lock().unwrap_or_else(|e| e.into_inner()));
700            if !leftover.is_empty() {
701                let _ = chunk_tx.send(leftover);
702            }
703        }
704        // Drop the only remaining sender — once the writer drains the
705        // last chunk, recv() returns Err and the thread exits.
706        drop(chunk_tx);
707
708        // Wait for the writer to finish committing.
709        let (mut total_faces, mut photos_processed) = match writer_handle.join() {
710            Ok(Ok(pair)) => pair,
711            Ok(Err(e)) => return Err(e),
712            Err(_) => return Err("Face writer thread panicked".to_string()),
713        };
714        // The writer used `mut` because Stage 3 below still adds via
715        // brightness lookups; but for now the only mutation here is to
716        // refresh `total_faces`/`photos_processed` for the toast text.
717        // Suppress the unused-mut lint if the compiler flags it.
718        let _ = (&mut total_faces, &mut photos_processed);
719
720        // Per-photo loop is done. Move into the post-processing tail.
721
722        // Check if cancelled partway through
723        let was_cancelled = cancel.load(Ordering::Relaxed);
724
725        let rej_small = rejected_small.load(Ordering::Relaxed);
726        let rej_lowconf = rejected_lowconf.load(Ordering::Relaxed);
727        let rej_blurry = rejected_blurry.load(Ordering::Relaxed);
728        let rej_yaw = rejected_yaw.load(Ordering::Relaxed);
729        if rej_small + rej_lowconf + rej_blurry + rej_yaw > 0 {
730            tracing::info!(
731                "Quality filter: rejected {} small, {} low-confidence, {} blurry, {} high-yaw faces",
732                rej_small,
733                rej_lowconf,
734                rej_blurry,
735                rej_yaw
736            );
737        }
738
739        if was_cancelled {
740            if let Some(ref tx) = progress_tx {
741                let _ = tx.try_send(FaceProcessingProgress {
742                    processed: photos_processed,
743                    total,
744                    faces_found: total_faces,
745                    elapsed_secs: pipeline_start.elapsed().as_secs_f64(),
746                    stage: FaceProcessingStage::Done,
747                    chunks_flushed: chunks_flushed.load(Ordering::Relaxed) as u32,
748                    embedder_route,
749                });
750            }
751            return Ok(FaceProcessingResult {
752                photos_processed,
753                faces_detected: total_faces,
754                clusters_created: 0,
755                rejected_small: rej_small,
756                rejected_lowconf: rej_lowconf,
757                rejected_blurry: rej_blurry,
758                rejected_yaw: rej_yaw,
759            });
760        }
761
762        // ---- Stage 3: Contextual Identity Propagation ----
763        // Build a brightness map from successful summaries so propagation
764        // can compare lighting between target and neighbor photos
765        // without reopening images. Errored photos are excluded — their
766        // brightness was never measured.
767        let summaries_vec =
768            std::mem::take(&mut *summaries.lock().unwrap_or_else(|e| e.into_inner()));
769        let brightness_map: HashMap<i64, f32> = summaries_vec
770            .iter()
771            .filter(|s| !s.had_error)
772            .map(|s| (s.photo_id, s.brightness))
773            .collect();
774
775        for summary in &summaries_vec {
776            if summary.had_error || summary.has_faces {
777                continue; // Only propagate for photos with no detected faces
778            }
779            if let Some(target_ts) = summary.taken_ts {
780                let params = ContextPropagationInput {
781                    drive_path,
782                    photo_id: summary.photo_id,
783                    file_path: &summary.file_path,
784                    target_ts,
785                    target_brightness: summary.brightness,
786                    brightness_map: &brightness_map,
787                };
788                let _ = Self::propagate_identity_from_context(&face_repo, &inferred_repo, &params);
789            }
790        }
791        // Tell the UI when processing enters the clustering tail.
792        if let Some(ref tx) = progress_tx {
793            let _ = tx.try_send(FaceProcessingProgress {
794                processed: photos_processed,
795                total,
796                faces_found: total_faces,
797                elapsed_secs: pipeline_start.elapsed().as_secs_f64(),
798                stage: FaceProcessingStage::Finishing,
799                chunks_flushed: chunks_flushed.load(Ordering::Relaxed) as u32,
800                embedder_route,
801            });
802        }
803
804        // ---- Stage 4: Clustering ----
805        let clusters_created =
806            Self::run_clustering(&face_repo, clustering_threshold, resolver_weights)?;
807
808        // Emit one final Done tick for the UI.
809        if let Some(ref tx) = progress_tx {
810            let _ = tx.try_send(FaceProcessingProgress {
811                processed: photos_processed,
812                total,
813                faces_found: total_faces,
814                elapsed_secs: pipeline_start.elapsed().as_secs_f64(),
815                stage: FaceProcessingStage::Done,
816                chunks_flushed: chunks_flushed.load(Ordering::Relaxed) as u32,
817                embedder_route,
818            });
819        }
820
821        tracing::info!(
822            "Face processing complete: {} photos, {} faces, {} clusters",
823            photos_processed,
824            total_faces,
825            clusters_created
826        );
827
828        Ok(FaceProcessingResult {
829            photos_processed,
830            faces_detected: total_faces,
831            clusters_created,
832            rejected_small: rej_small,
833            rejected_lowconf: rej_lowconf,
834            rejected_blurry: rej_blurry,
835            rejected_yaw: rej_yaw,
836        })
837    }
838
839    fn propagate_identity_from_context(
840        face_repo: &FaceRepo,
841        inferred_repo: &InferredIdentityRepo,
842        params: &ContextPropagationInput<'_>,
843    ) -> Result<usize, String> {
844        let folder_like = std::path::Path::new(params.file_path).parent().map(|p| {
845            let s = p.to_string_lossy();
846            if s.is_empty() {
847                "%".to_string()
848            } else {
849                format!("{}%", s)
850            }
851        });
852
853        let candidates = face_repo
854            .get_contextual_cluster_candidates(
855                params.photo_id,
856                folder_like.as_deref(),
857                params.target_ts,
858                Self::CONTEXT_WINDOW_SECS,
859            )
860            .map_err(|e| format!("Failed to query contextual candidates: {}", e))?;
861
862        if candidates.is_empty() {
863            return Ok(0);
864        }
865
866        let mut best_by_cluster: HashMap<i64, (i64, f32)> = HashMap::new();
867
868        for (source_photo_id, cluster_id, source_ts, source_file_path) in candidates {
869            let delta = (source_ts - params.target_ts).abs() as f32;
870            let temporal_score = 1.0 - (delta / Self::CONTEXT_WINDOW_SECS as f32).clamp(0.0, 1.0);
871            let mut confidence = 0.5 + (temporal_score * 0.4);
872
873            // Brightness lookup: in-run map (this run's photos) →
874            // photos.brightness column (prior runs) → on-disk recompute
875            // (legacy rows from before brightness was persisted, until
876            // they get reprocessed and rewritten).
877            let source_brightness = params
878                .brightness_map
879                .get(&source_photo_id)
880                .copied()
881                .or_else(|| {
882                    face_repo
883                        .get_photo_brightness(source_photo_id)
884                        .ok()
885                        .flatten()
886                })
887                .or_else(|| {
888                    Self::load_average_brightness_from_relative(
889                        params.drive_path,
890                        &source_file_path,
891                    )
892                });
893
894            if let Some(source_brightness) = source_brightness {
895                // Smooth falloff instead of hard cutoff (Phase 2 fix included)
896                let diff = (params.target_brightness - source_brightness).abs();
897                let brightness_bonus = 0.1 * (1.0 - (diff / 0.3).clamp(0.0, 1.0));
898                confidence += brightness_bonus;
899            }
900
901            confidence = confidence.clamp(0.0, 1.0);
902
903            if confidence < Self::CONTEXT_MIN_CONFIDENCE {
904                continue;
905            }
906
907            match best_by_cluster.get(&cluster_id) {
908                Some((_, existing)) if *existing >= confidence => {}
909                _ => {
910                    best_by_cluster.insert(cluster_id, (source_photo_id, confidence));
911                }
912            }
913        }
914
915        let mut inserted = 0usize;
916        for (cluster_id, (source_photo_id, confidence)) in best_by_cluster {
917            if inferred_repo
918                .insert_inferred_identity(params.photo_id, cluster_id, source_photo_id, confidence)
919                .is_ok()
920            {
921                inserted += 1;
922            }
923        }
924
925        Ok(inserted)
926    }
927
928    /// Minimum bbox area (pixels^2) for a face to be worth embedding.
929    /// 30x30 px = 900.
930    const MIN_FACE_AREA_PX2: f32 = 900.0;
931
932    /// Minimum detection confidence to accept a face for embedding, even if the
933    /// detector's own threshold is looser.
934    const MIN_FACE_CONFIDENCE: f32 = 0.55;
935
936    /// Minimum Laplacian variance on the 112x112 aligned crop. Below this the
937    /// face is too blurry to produce a reliable embedding.
938    const MIN_LAPLACIAN_VAR: f32 = 40.0;
939
940    /// Maximum absolute yaw angle (degrees) for face embedding. Side-profile
941    /// faces produce unreliable embeddings and create bridge edges in clustering.
942    const MAX_FACE_YAW_DEG: f32 = 35.0;
943
944    /// Laplacian-of-gaussian-style blur measure on a 112x112 aligned crop.
945    /// Higher = sharper. Very blurry faces score near 0.
946    fn laplacian_variance(img: &image::RgbImage) -> f32 {
947        let w = img.width() as i32;
948        let h = img.height() as i32;
949        if w < 3 || h < 3 {
950            return 0.0;
951        }
952
953        let mut gray = vec![0.0f32; (w * h) as usize];
954        for y in 0..h {
955            for x in 0..w {
956                let p = img.get_pixel(x as u32, y as u32).0;
957                gray[(y * w + x) as usize] =
958                    0.299 * p[0] as f32 + 0.587 * p[1] as f32 + 0.114 * p[2] as f32;
959            }
960        }
961
962        let mut sum = 0.0f32;
963        let mut sum_sq = 0.0f32;
964        let mut count = 0usize;
965        for y in 1..(h - 1) {
966            for x in 1..(w - 1) {
967                let idx = (y * w + x) as usize;
968                let center = gray[idx];
969                let l = 4.0 * center
970                    - gray[(y * w + (x - 1)) as usize]
971                    - gray[(y * w + (x + 1)) as usize]
972                    - gray[((y - 1) * w + x) as usize]
973                    - gray[((y + 1) * w + x) as usize];
974                sum += l;
975                sum_sq += l * l;
976                count += 1;
977            }
978        }
979
980        let n = count as f32;
981        let mean = sum / n;
982        (sum_sq / n) - mean * mean
983    }
984
985    /// Build a resolver context for one face: co-occurrence counts between
986    /// candidate clusters and the already-assigned clusters in this photo,
987    /// plus temporal-neighbor assignments.
988    fn build_resolver_context(
989        face_repo: &FaceRepo,
990        photo_id: i64,
991        face_id: i64,
992        hits: &[crate::ml::RetrievalHit],
993    ) -> crate::ml::ResolverContext {
994        const TEMPORAL_WINDOW_SECS: i64 = 60;
995
996        let photo_other_clusters = face_repo
997            .get_photo_other_clusters(photo_id, face_id)
998            .unwrap_or_default();
999
1000        let mut cooccurrence_scores: std::collections::HashMap<i64, i64> =
1001            std::collections::HashMap::new();
1002        if !photo_other_clusters.is_empty() {
1003            for hit in hits {
1004                let mut total: i64 = 0;
1005                for other in &photo_other_clusters {
1006                    total += face_repo
1007                        .cooccurrence_count(hit.cluster_id, *other)
1008                        .unwrap_or(0);
1009                }
1010                if total > 0 {
1011                    cooccurrence_scores.insert(hit.cluster_id, total);
1012                }
1013            }
1014        }
1015
1016        let temporal_neighbor_clusters: std::collections::HashSet<i64> = face_repo
1017            .temporal_neighbor_clusters(photo_id, TEMPORAL_WINDOW_SECS)
1018            .unwrap_or_default()
1019            .into_iter()
1020            .map(|(cid, _)| cid)
1021            .collect();
1022
1023        crate::ml::ResolverContext {
1024            photo_other_clusters,
1025            cooccurrence_scores,
1026            temporal_neighbor_clusters,
1027        }
1028    }
1029
1030    fn average_brightness(image: &image::DynamicImage) -> f32 {
1031        let small = image
1032            .resize(64, 64, image::imageops::FilterType::Triangle)
1033            .to_rgb8();
1034        let mut total = 0.0f32;
1035        let mut count = 0.0f32;
1036
1037        for p in small.pixels() {
1038            let [r, g, b] = p.0;
1039            total += (0.2126 * (r as f32) + 0.7152 * (g as f32) + 0.0722 * (b as f32)) / 255.0;
1040            count += 1.0;
1041        }
1042
1043        if count == 0.0 {
1044            0.0
1045        } else {
1046            total / count
1047        }
1048    }
1049
1050    fn load_average_brightness_from_relative(
1051        drive_path: &Path,
1052        relative_path: &str,
1053    ) -> Option<f32> {
1054        let path = match safe_join_relative(drive_path, relative_path) {
1055            Ok(path) => path,
1056            Err(e) => {
1057                tracing::trace!(
1058                    "context-brightness lookup skipped invalid path {}: {}",
1059                    relative_path,
1060                    e
1061                );
1062                return None;
1063            }
1064        };
1065        match crate::services::image_io::open_image(&path) {
1066            Ok(image) => Some(Self::average_brightness(&image)),
1067            Err(e) => {
1068                tracing::trace!(
1069                    "context-brightness lookup failed for {}: {}",
1070                    path.display(),
1071                    e
1072                );
1073                None
1074            }
1075        }
1076    }
1077}
1078
1079/// Commit one streamed chunk of per-photo results: insert detected
1080/// faces, mark photos `faces_processed=TRUE`, save face crops to disk.
1081/// On cancellation, photos with `had_error && faces.is_empty()` are
1082/// left as `faces_processed=FALSE` so a later run will retry them.
1083///
1084/// After the commit, runs an inline Stage A pass: each freshly-inserted
1085/// face is matched against existing cluster galleries and assigned a
1086/// `cluster_id` if a HIGH-confidence match exists. This is what makes
1087/// faces appear in the People view *during* the run — without it,
1088/// faces carry `cluster_id = NULL` until end-of-pipeline clustering
1089/// and the grid stays empty.
1090///
1091/// Returns `(faces_added, photos_added)` for stats only — durable state
1092/// is the SQL writes.
1093fn flush_result_chunk(
1094    db: &Database,
1095    faces_dir: &Path,
1096    chunk: &[PhotoFaceResult],
1097    was_cancelled: bool,
1098    chunks_flushed: &AtomicUsize,
1099    clustering_threshold: f32,
1100    resolver_weights: crate::ml::ResolverWeights,
1101) -> Result<(usize, usize), String> {
1102    let mut faces_added = 0usize;
1103    let mut photos_added = 0usize;
1104    let after_id: i64 = db
1105        .conn
1106        .query_row("SELECT COALESCE(MAX(id), 0) FROM faces", [], |row| {
1107            row.get(0)
1108        })
1109        .map_err(|e| format!("Read face cursor: {e}"))?;
1110    // Crop encoding/writes happen after commit, outside SQLite's write lock.
1111    let mut crops = Vec::new();
1112
1113    let tx = db
1114        .conn
1115        .unchecked_transaction()
1116        .map_err(|e| format!("Failed to begin chunk transaction: {}", e))?;
1117
1118    for result in chunk {
1119        if result.had_error && result.faces.is_empty() {
1120            // Count the failure, and give up (mark processed) only after
1121            // MAX_FACE_ATTEMPTS runs, so a transient problem — drive
1122            // unplugged, decoder missing — is retried rather than recorded
1123            // as "no faces". Cancelled runs leave the photo queued as is.
1124            if !was_cancelled {
1125                let _ = tx.execute(
1126                    "UPDATE photos
1127                        SET face_attempts = face_attempts + 1,
1128                            faces_processed = (face_attempts + 1 >= ?2)
1129                      WHERE id = ?1",
1130                    rusqlite::params![result.photo_id, MAX_FACE_ATTEMPTS],
1131                );
1132                photos_added += 1;
1133            }
1134            continue;
1135        }
1136
1137        let _ = tx.execute(
1138            "DELETE FROM photo_inferred_identities WHERE photo_id = ?1",
1139            rusqlite::params![result.photo_id],
1140        );
1141
1142        for face in &result.faces {
1143            match tx.execute(
1144                r#"
1145                INSERT INTO faces (
1146                    photo_id,
1147                    bbox_x, bbox_y, bbox_width, bbox_height,
1148                    confidence, embedding
1149                ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
1150                "#,
1151                rusqlite::params![
1152                    result.photo_id,
1153                    face.bbox_normalized.0,
1154                    face.bbox_normalized.1,
1155                    face.bbox_normalized.2,
1156                    face.bbox_normalized.3,
1157                    face.confidence,
1158                    face.embedding.to_bytes(),
1159                ],
1160            ) {
1161                Ok(_) => {
1162                    let face_id = tx.last_insert_rowid();
1163                    crops.push((face_id, &face.aligned_face));
1164                    faces_added += 1;
1165                }
1166                Err(e) => {
1167                    tracing::warn!("Failed to insert face: {}", e);
1168                }
1169            }
1170        }
1171
1172        // Persist brightness alongside the processed flag so future
1173        // runs and propagation lookups can read it from SQL instead of
1174        // re-decoding the JPEG to compute luma again.
1175        let _ = tx.execute(
1176            "UPDATE photos SET faces_processed = TRUE, brightness = ?2 WHERE id = ?1",
1177            rusqlite::params![result.photo_id, result.brightness],
1178        );
1179        photos_added += 1;
1180    }
1181
1182    tx.commit()
1183        .map_err(|e| format!("Failed to commit chunk: {}", e))?;
1184
1185    for (face_id, crop) in crops {
1186        let crop_path = faces_dir.join(format!("{face_id}.jpg"));
1187        if let Err(e) = FaceProcessor::save_face_crop(crop, &crop_path) {
1188            tracing::warn!("Failed to save face crop {}: {}", face_id, e);
1189        }
1190    }
1191    // Publish the committed batch before potentially expensive identity assignment.
1192    chunks_flushed.fetch_add(1, Ordering::Relaxed);
1193
1194    // Per-chunk Stage A: assign HIGH-band gallery matches now so the
1195    // user sees faces appear in People mid-run for everyone they've
1196    // already named (or who survived a previous run). New people are
1197    // still introduced at the end-of-pipeline clustering pass.
1198    let face_repo = FaceRepo::new(&db.conn);
1199    if let Err(e) = FaceProcessor::stream_assign_existing_clusters(
1200        &face_repo,
1201        after_id,
1202        clustering_threshold,
1203        resolver_weights,
1204    ) {
1205        tracing::debug!("Per-chunk Stage A skipped: {}", e);
1206    }
1207
1208    Ok((faces_added, photos_added))
1209}
1210
1211mod clustering;
1212mod manual;
1213
1214pub use manual::{iou, ManualFace, ManualFaceError, SoftCrop};
1215
1216/// Bound aggregate CPU use, not just the threads inside each inference session.
1217///
1218/// Returns `(workers, intra_threads_per_worker, aggregate_thread_budget)`.
1219///
1220/// Face processing must never take the whole machine. It runs in the
1221/// background while the user is browsing, so the invariant that matters is
1222/// `workers * intra <= budget` with the budget strictly below the CPU count —
1223/// leaving real capacity for the webview, the async runtime and SQLite.
1224///
1225/// History worth not repeating: an earlier revision computed
1226/// `budget = 0.75 * logical` then `intra = budget / workers`, which floored
1227/// `intra` to 1 on everything up to ~10 CPUs (8 workers x 1 thread on a
1228/// 16-core box). A later fix "corrected" that by granting small machines 100%
1229/// of their cores, which on the 2-core/4-thread laptop this project is tested
1230/// on handed face processing all four threads and froze the UI. Both extremes
1231/// are wrong: the budget must scale with the machine AND always leave headroom.
1232fn background_face_budget(logical_cpus: usize) -> (usize, usize, usize) {
1233    let logical = logical_cpus.max(1);
1234    // Reserve at least one thread for the rest of the app, then take 3/4 of
1235    // what remains. On 4 CPUs -> 2 (leaves 2 for the UI). On 16 -> 11. On 1 ->
1236    // 1, because with a single CPU there is nothing to reserve.
1237    let budget = if logical <= 1 {
1238        1
1239    } else {
1240        (((logical - 1) as f64) * 0.75).floor().max(1.0) as usize
1241    };
1242    let workers = budget.clamp(1, 8);
1243    let intra = (budget / workers).max(1);
1244    (workers, intra, budget)
1245}
1246
1247#[cfg(test)]
1248mod background_budget_tests {
1249    use super::background_face_budget;
1250    #[test]
1251    fn reserves_capacity_on_low_end_and_large_machines() {
1252        for cores in [1, 2, 4, 7, 8, 12, 16, 64] {
1253            let (w, t, b) = background_face_budget(cores);
1254            assert!(w * t <= b, "workers*intra must fit the budget");
1255            assert!(w >= 1);
1256            assert!(t >= 1);
1257        }
1258    }
1259
1260    /// Every machine must keep real capacity for the UI.
1261    ///
1262    /// Two past regressions are pinned here: `intra_threads` collapsing to 1 on
1263    /// ordinary machines (so sessions were effectively single-threaded), and a
1264    /// later "fix" that granted small machines every core (so on the 2-core /
1265    /// 4-thread laptop this is developed on, face processing took all four
1266    /// threads and the UI froze).
1267    #[test]
1268    fn budget_always_leaves_headroom_and_never_collapses_to_one_thread() {
1269        for cores in 1..=64usize {
1270            let (workers, intra, budget) = background_face_budget(cores);
1271            assert!(workers >= 1 && intra >= 1, "{cores}: {workers}x{intra}");
1272            assert!(
1273                workers * intra <= budget,
1274                "{cores}: {workers}x{intra} exceeds budget {budget}"
1275            );
1276            assert!(
1277                budget <= cores,
1278                "{cores}: budget {budget} exceeds the CPU count"
1279            );
1280            if cores > 1 {
1281                assert!(
1282                    budget < cores,
1283                    "{cores}: budget {budget} consumes every CPU; the UI needs one"
1284                );
1285            }
1286        }
1287
1288        // The development machine: 2 cores / 4 threads. Half the machine, so
1289        // the webview and async runtime keep two threads.
1290        assert_eq!(background_face_budget(4), (2, 1, 2));
1291        // A single CPU has nothing to reserve.
1292        assert_eq!(background_face_budget(1), (1, 1, 1));
1293        // Roomier machines stay well under their ceiling.
1294        assert_eq!(background_face_budget(8), (5, 1, 5));
1295        assert_eq!(background_face_budget(16), (8, 1, 11));
1296        // Large machines must not come back single-threaded per session.
1297        let (w24, t24, b24) = background_face_budget(24);
1298        assert_eq!(b24, 17);
1299        assert_eq!(
1300            (w24, t24),
1301            (8, 2),
1302            "24-core sessions must not be single-threaded"
1303        );
1304        assert_eq!(background_face_budget(64), (8, 5, 47));
1305    }
1306}