Skip to main content

smriti/services/
reindexer.rs

1//! Incremental re-indexing service.
2
3use std::collections::{HashMap, HashSet};
4use std::fs;
5use std::path::{Path, PathBuf};
6
7use rusqlite::{params, Connection, Result as SqliteResult};
8use walkdir::WalkDir;
9
10use crate::db::face_repo::FaceRepo;
11use crate::services::exclusions::ExclusionMatcher;
12use crate::services::path_util::safe_join_relative;
13use crate::services::scanner::calculate_fast_hash;
14
15#[derive(Debug, Default, Clone)]
16pub struct IndexChanges {
17    pub added: Vec<PathBuf>,
18    pub removed: Vec<(i64, PathBuf)>,
19    pub moved: Vec<(i64, PathBuf, PathBuf)>,
20    pub modified: Vec<(i64, PathBuf)>,
21    /// Folders or files the walk could not read. Indexed photos under them
22    /// are left alone rather than reported as removed.
23    pub unreadable: usize,
24}
25
26impl IndexChanges {
27    pub fn is_empty(&self) -> bool {
28        self.added.is_empty()
29            && self.removed.is_empty()
30            && self.moved.is_empty()
31            && self.modified.is_empty()
32    }
33}
34
35#[derive(Debug, Default, Clone)]
36pub struct ApplyResult {
37    pub new_files: usize,
38    pub moves_applied: usize,
39    pub removals_applied: usize,
40    pub updates_applied: usize,
41}
42
43/// Outcome of [`Reindexer::reconcile_existing`].
44#[derive(Debug, Default, Clone)]
45pub struct ReconcileOutcome {
46    pub applied: ApplyResult,
47    /// Missing photos that were *not* trashed because so many vanished at
48    /// once that a disconnected folder or drive is the likelier cause.
49    pub held_back_removals: usize,
50    pub unreadable: usize,
51}
52
53/// Below this many missing photos, removals are always applied.
54const MASS_REMOVAL_MIN: usize = 25;
55/// Above this share (1 / N) of the active library, removals are held back
56/// for explicit confirmation.
57const MASS_REMOVAL_FRACTION: usize = 5;
58
59pub struct Reindexer {
60    supported_extensions: HashSet<String>,
61    scan_hidden_folders: bool,
62}
63
64impl Default for Reindexer {
65    fn default() -> Self {
66        Self::new()
67    }
68}
69
70impl Reindexer {
71    pub fn new() -> Self {
72        Self::new_with_options(false)
73    }
74
75    pub fn new_with_options(scan_hidden_folders: bool) -> Self {
76        // Share format support with the initial scanner.
77        let mut supported_extensions = HashSet::new();
78        for ext in crate::services::scanner::SUPPORTED_EXTENSIONS {
79            supported_extensions.insert(ext.to_string());
80        }
81
82        Self {
83            supported_extensions,
84            scan_hidden_folders,
85        }
86    }
87
88    pub fn detect_changes(
89        &self,
90        conn: &Connection,
91        drive_root: &Path,
92    ) -> SqliteResult<IndexChanges> {
93        let metadata = fs::metadata(drive_root)
94            .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
95        if !metadata.is_dir() {
96            return Err(rusqlite::Error::InvalidParameterName(
97                "library root is not a directory".into(),
98            ));
99        }
100        let mut changes = IndexChanges::default();
101        let exclusions = ExclusionMatcher::from_db(conn)?;
102
103        // Use a temp table instead of loading everything into a HashMap.
104        // This keeps memory usage O(1) in Rust regardless of library size.
105        conn.execute_batch(
106            "CREATE TEMP TABLE IF NOT EXISTS found_files (
107                path TEXT PRIMARY KEY,
108                mtime INTEGER,
109                size INTEGER
110            );
111            DELETE FROM found_files;",
112        )?;
113
114        let mut insert_stmt = conn
115            .prepare("INSERT OR IGNORE INTO found_files (path, mtime, size) VALUES (?1, ?2, ?3)")?;
116
117        // Relative paths the walk could not read. A permission error on one
118        // folder must neither abort the whole pass nor make every photo
119        // inside it look deleted.
120        let mut unreadable_prefixes: Vec<String> = Vec::new();
121
122        for entry in WalkDir::new(drive_root)
123            .follow_links(false)
124            .into_iter()
125            .filter_entry(|e| !self.should_skip(drive_root, e.path(), &exclusions))
126        {
127            let entry = match entry {
128                Ok(e) => e,
129                Err(error) => {
130                    let relative = error
131                        .path()
132                        .filter(|p| *p != drive_root)
133                        .and_then(|p| p.strip_prefix(drive_root).ok())
134                        .map(crate::services::path_util::relative_path_for_storage);
135                    match relative {
136                        Some(relative) => {
137                            tracing::warn!("reindex: skipping unreadable {relative}: {error}");
138                            unreadable_prefixes.push(relative);
139                            continue;
140                        }
141                        // The root itself became unreadable (drive unplugged
142                        // mid-walk): nothing can be concluded.
143                        None => {
144                            return Err(rusqlite::Error::ToSqlConversionFailure(Box::new(error)))
145                        }
146                    }
147                }
148            };
149
150            if !entry.file_type().is_file() {
151                continue;
152            }
153
154            let ext = entry
155                .path()
156                .extension()
157                .and_then(|e| e.to_str())
158                .map(|e| e.to_lowercase())
159                .unwrap_or_default();
160
161            if !self.supported_extensions.contains(&ext) {
162                continue;
163            }
164
165            // Forward-slash-normalized so a Windows write and a Linux
166            // write of the same drive produce identical strings.
167            let relative_path = match entry.path().strip_prefix(drive_root).ok() {
168                Some(p) => crate::services::path_util::relative_path_for_storage(p),
169                None => continue,
170            };
171
172            let metadata = match fs::metadata(entry.path()) {
173                Ok(metadata) => metadata,
174                Err(error) => {
175                    tracing::warn!("reindex: skipping unreadable {relative_path}: {error}");
176                    unreadable_prefixes.push(relative_path);
177                    continue;
178                }
179            };
180            let mtime = metadata
181                .modified()
182                .ok()
183                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
184                .map(|d| d.as_secs() as i64);
185
186            insert_stmt.execute(params![relative_path, mtime, metadata.len() as i64])?;
187        }
188        drop(insert_stmt);
189
190        // Added files: on disk but not in DB
191        {
192            let mut stmt = conn.prepare(
193                "SELECT f.path FROM temp.found_files f
194                 LEFT JOIN photos p ON p.file_path = f.path
195                 WHERE p.id IS NULL",
196            )?;
197            let rows = stmt.query_map([], |row| row.get::<_, String>(0))?;
198            for row in rows {
199                let path = row?;
200                if let Ok(full) = safe_join_relative(drive_root, &path) {
201                    changes.added.push(full);
202                }
203            }
204        }
205
206        // Modified files: matching path but different size or mtime
207        {
208            let mut stmt = conn.prepare(
209                "SELECT p.id, p.file_path, p.file_size, p.file_mtime, f.size, f.mtime
210                   FROM photos p
211                   INNER JOIN temp.found_files f ON f.path = p.file_path
212                  WHERE p.is_trashed = FALSE
213                    AND (f.mtime IS NOT p.file_mtime OR f.size != p.file_size)",
214            )?;
215            let rows = stmt.query_map([], |row| {
216                Ok((
217                    row.get::<_, i64>(0)?,
218                    row.get::<_, String>(1)?,
219                    row.get::<_, i64>(2)?,
220                    row.get::<_, Option<i64>>(3)?,
221                    row.get::<_, i64>(4)?,
222                    row.get::<_, Option<i64>>(5)?,
223                ))
224            })?;
225            for row in rows {
226                let (id, path, stored_size, stored_mtime, disk_size, disk_mtime) = row?;
227                if !content_may_have_changed(stored_size, stored_mtime, disk_size, disk_mtime) {
228                    continue;
229                }
230                if let Ok(full) = safe_join_relative(drive_root, &path) {
231                    changes.modified.push((id, full));
232                }
233            }
234        }
235
236        // Removed files: in DB but not on disk
237        // Also check for moves (same hash, different path)
238        {
239            let mut stmt = conn.prepare(
240                "SELECT p.id, p.file_path, p.file_hash FROM photos p
241                 LEFT JOIN temp.found_files f ON f.path = p.file_path
242                 WHERE p.is_trashed = FALSE AND f.path IS NULL",
243            )?;
244            let rows = stmt.query_map([], |row| {
245                Ok((
246                    row.get::<_, i64>(0)?,
247                    row.get::<_, String>(1)?,
248                    row.get::<_, String>(2)?,
249                ))
250            })?;
251
252            let mut missing: Vec<(i64, String, String)> = Vec::new();
253            for row in rows {
254                let row = row?;
255                // Files under unreadable folders, or of a type this build no
256                // longer indexes, were never in `found_files` — they are not
257                // missing, so they must not be trashed.
258                if !is_under_any_prefix(&row.1, &unreadable_prefixes)
259                    && self.is_supported_path(&row.1)
260                {
261                    missing.push(row);
262                }
263            }
264
265            // Pre-hash all candidate (added) files exactly once into a hash → path map.
266            // Without this, we'd re-hash every candidate for every missing file (N×M).
267            // Hashes computed here use the same fast hash as the scanner so
268            // the result matches the stored `photos.file_hash` column.
269            let candidate_paths: Vec<String> = changes
270                .added
271                .iter()
272                .filter_map(|p| p.strip_prefix(drive_root).ok())
273                .map(crate::services::path_util::relative_path_for_storage)
274                .collect();
275
276            let mut hash_to_candidate: HashMap<String, String> = HashMap::new();
277            for relative in &candidate_paths {
278                let Ok(full) = safe_join_relative(drive_root, relative) else {
279                    continue;
280                };
281                let Ok(meta) = fs::metadata(&full) else {
282                    continue;
283                };
284                let mtime = meta
285                    .modified()
286                    .ok()
287                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
288                    .map(|d| d.as_secs() as i64);
289                if let Ok(hash) = calculate_fast_hash(&full, meta.len(), mtime) {
290                    hash_to_candidate
291                        .entry(hash)
292                        .or_insert_with(|| relative.clone());
293                }
294            }
295
296            let mut consumed_candidates: HashSet<String> = HashSet::new();
297            for (id, old_path, hash) in &missing {
298                match hash_to_candidate.get(hash) {
299                    Some(new_path) if !consumed_candidates.contains(new_path) => {
300                        consumed_candidates.insert(new_path.clone());
301                        changes
302                            .moved
303                            .push((*id, PathBuf::from(old_path), PathBuf::from(new_path)));
304                    }
305                    _ => {
306                        changes.removed.push((*id, PathBuf::from(old_path)));
307                    }
308                }
309            }
310
311            // Files matched as moves are no longer "added"; drop them from the added list.
312            if !consumed_candidates.is_empty() {
313                changes.added.retain(|p| {
314                    let relative = p
315                        .strip_prefix(drive_root)
316                        .ok()
317                        .map(crate::services::path_util::relative_path_for_storage)
318                        .unwrap_or_default();
319                    !consumed_candidates.contains(&relative)
320                });
321            }
322        }
323
324        conn.execute("DROP TABLE IF EXISTS temp.found_files", [])?;
325
326        changes.unreadable = unreadable_prefixes.len();
327        Ok(changes)
328    }
329
330    /// Bring already-indexed rows in line with the disk: follow moves,
331    /// trash photos whose files are gone and reset photos edited outside
332    /// Smriti. New files are left to the scanner.
333    ///
334    /// When an unusually large share of the library is missing at once the
335    /// removals are held back (see [`ReconcileOutcome::held_back_removals`])
336    /// so a disconnected sub-folder or share doesn't empty the library into
337    /// the trash.
338    pub fn reconcile_existing(
339        &self,
340        conn: &Connection,
341        drive_root: &Path,
342    ) -> SqliteResult<ReconcileOutcome> {
343        let mut changes = self.detect_changes(conn, drive_root)?;
344        changes.added.clear();
345
346        let mut held_back_removals = 0;
347        if !changes.removed.is_empty() {
348            let active: i64 = conn.query_row(
349                "SELECT COUNT(*) FROM photos WHERE is_trashed = FALSE",
350                [],
351                |row| row.get(0),
352            )?;
353            if is_mass_removal(changes.removed.len(), active.max(0) as usize) {
354                held_back_removals = changes.removed.len();
355                changes.removed.clear();
356            }
357        }
358
359        let applied = if changes.is_empty() {
360            ApplyResult::default()
361        } else {
362            self.apply_changes(conn, &changes)?
363        };
364        Ok(ReconcileOutcome {
365            applied,
366            held_back_removals,
367            unreadable: changes.unreadable,
368        })
369    }
370
371    pub fn apply_changes(
372        &self,
373        conn: &Connection,
374        changes: &IndexChanges,
375    ) -> SqliteResult<ApplyResult> {
376        let mut result = ApplyResult::default();
377        let tx = conn.unchecked_transaction()?;
378
379        for (photo_id, _old_path, new_path) in &changes.moved {
380            let new_relative = crate::services::path_util::relative_path_for_storage(new_path);
381            let new_file_name = new_path
382                .file_name()
383                .and_then(|n| n.to_str())
384                .unwrap_or(&new_relative)
385                .to_string();
386            tx.execute(
387                "UPDATE photos
388                    SET file_path = ?1,
389                        file_name = ?2,
390                        updated_at = CURRENT_TIMESTAMP
391                  WHERE id = ?3",
392                params![new_relative, new_file_name, photo_id],
393            )?;
394            result.moves_applied += 1;
395        }
396
397        let removed_ids: Vec<_> = changes.removed.iter().map(|(id, _)| *id).collect();
398        result.removals_applied =
399            crate::services::trash::TrashService::trash_photos_tx(&tx, &removed_ids)?;
400
401        for (photo_id, path) in &changes.modified {
402            clear_face_derivatives_for_photo(&tx, *photo_id)?;
403            let file_facts = fs::metadata(path).ok().and_then(|meta| {
404                let size = i64::try_from(meta.len()).ok()?;
405                let mtime = meta
406                    .modified()
407                    .ok()
408                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
409                    .map(|d| d.as_secs() as i64);
410                let hash = calculate_fast_hash(path, meta.len(), mtime).ok()?;
411                Some((size, mtime, hash))
412            });
413            let (file_size, file_mtime, file_hash) = match file_facts {
414                Some((size, mtime, hash)) => (Some(size), mtime, Some(hash)),
415                None => (None, None, None),
416            };
417            tx.execute(
418                "UPDATE photos
419                    SET file_size = COALESCE(?2, file_size),
420                        file_mtime = COALESCE(?3, file_mtime),
421                        file_hash = COALESCE(?4, file_hash),
422                        metadata_extracted = FALSE,
423                        thumbnailed = FALSE,
424                        thumbnail_path = NULL,
425                        faces_processed = FALSE,
426                        face_attempts = 0,
427                        phash = NULL,
428                        content_hash = NULL,
429                        brightness = NULL,
430                        updated_at = CURRENT_TIMESTAMP
431                  WHERE id = ?1",
432                params![photo_id, file_size, file_mtime, file_hash],
433            )?;
434            result.updates_applied += 1;
435            tx.execute(
436                "DELETE FROM semantic_index_state WHERE photo_id = ?1",
437                [photo_id],
438            )?;
439        }
440
441        if !changes.added.is_empty() {
442            let db_path: String = tx.query_row(
443                "SELECT file FROM pragma_database_list WHERE name = 'main'",
444                [],
445                |row| row.get(0),
446            )?;
447            let root = Path::new(&db_path)
448                .parent()
449                .and_then(Path::parent)
450                .ok_or_else(|| {
451                    rusqlite::Error::InvalidParameterName(
452                        "new files require an on-disk library database".into(),
453                    )
454                })?;
455            // SQLite may report a canonical path even when the library was
456            // opened through an OS alias (notably /var -> /private/var on
457            // macOS). Compare canonical paths so valid additions remain under
458            // the same physical library root on every platform.
459            let root = fs::canonicalize(root)
460                .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
461            let mut insert = tx.prepare(
462                "INSERT INTO photos(file_path,file_name,file_hash,file_size,file_mtime,media_type)
463                VALUES (?1,?2,?3,?4,?5,?6) ON CONFLICT(file_path) DO NOTHING",
464            )?;
465            for path in &changes.added {
466                let canonical_path = fs::canonicalize(path)
467                    .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
468                let relative = canonical_path
469                    .strip_prefix(&root)
470                    .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
471                let relative = crate::services::path_util::relative_path_for_storage(relative);
472                crate::services::path_util::safe_existing_path_under_root(&root, &relative)
473                    .map_err(rusqlite::Error::InvalidParameterName)?;
474                let metadata = fs::metadata(&canonical_path)
475                    .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
476                let mtime = metadata
477                    .modified()
478                    .ok()
479                    .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
480                    .map(|time| time.as_secs() as i64);
481                let hash = calculate_fast_hash(&canonical_path, metadata.len(), mtime)
482                    .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
483                let media_type = crate::services::scanner::media_type_for_path(&canonical_path)
484                    .ok_or_else(|| {
485                        rusqlite::Error::InvalidParameterName("unsupported media file".into())
486                    })?;
487                result.new_files += insert.execute(params![
488                    relative,
489                    canonical_path
490                        .file_name()
491                        .unwrap_or_default()
492                        .to_string_lossy(),
493                    hash,
494                    metadata.len() as i64,
495                    mtime,
496                    media_type.as_str()
497                ])?;
498            }
499        }
500        tx.commit()?;
501        if !changes.modified.is_empty() {
502            FaceRepo::new(conn).normalize_cluster_stats()?;
503        }
504        Ok(result)
505    }
506
507    fn is_supported_path(&self, relative: &str) -> bool {
508        Path::new(relative)
509            .extension()
510            .and_then(|e| e.to_str())
511            .is_some_and(|e| self.supported_extensions.contains(&e.to_ascii_lowercase()))
512    }
513
514    fn should_skip(&self, drive_root: &Path, path: &Path, exclusions: &ExclusionMatcher) -> bool {
515        if path == drive_root {
516            return false;
517        }
518        let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
519        if !self.scan_hidden_folders && name.starts_with('.') {
520            return true;
521        }
522        // Same skip list as the scanner, so a reindex never reports the
523        // scanner's deliberately skipped folders (e.g. Synology `@eaDir`)
524        // as new files.
525        crate::services::scanner::SKIP_DIRECTORIES.contains(&name)
526            || exclusions.should_skip_path(drive_root, path)
527    }
528}
529
530fn is_under_any_prefix(path: &str, prefixes: &[String]) -> bool {
531    prefixes.iter().any(|prefix| {
532        path == prefix
533            || (path.len() > prefix.len()
534                && path.starts_with(prefix.as_str())
535                && path.as_bytes()[prefix.len()] == b'/')
536    })
537}
538
539fn is_mass_removal(missing: usize, active: usize) -> bool {
540    missing >= MASS_REMOVAL_MIN && missing * MASS_REMOVAL_FRACTION > active
541}
542
543/// Whether a size/mtime difference means the file content may have changed.
544///
545/// A same-size file whose mtime moved by up to 2 s (FAT resolution) or by a
546/// whole number of quarter hours within ±14 h (FAT/exFAT store local time,
547/// so a timezone or DST change shifts every mtime on the drive) is treated
548/// as unchanged: re-processing it would discard its faces for nothing.
549fn content_may_have_changed(
550    stored_size: i64,
551    stored_mtime: Option<i64>,
552    disk_size: i64,
553    disk_mtime: Option<i64>,
554) -> bool {
555    if stored_size != disk_size {
556        return true;
557    }
558    let (Some(stored), Some(disk)) = (stored_mtime, disk_mtime) else {
559        // Rows without a recorded mtime: size is all we can compare.
560        return false;
561    };
562    let delta = (disk - stored).abs();
563    if delta <= 2 {
564        return false;
565    }
566    !(delta % 900 == 0 && delta <= 14 * 3600)
567}
568
569fn clear_face_derivatives_for_photo(
570    tx: &rusqlite::Transaction<'_>,
571    photo_id: i64,
572) -> SqliteResult<()> {
573    let face_ids = {
574        let mut stmt = tx.prepare("SELECT id FROM faces WHERE photo_id = ?1")?;
575        let rows = stmt.query_map(params![photo_id], |row| row.get::<_, i64>(0))?;
576        rows.collect::<SqliteResult<Vec<_>>>()?
577    };
578
579    for face_id in face_ids {
580        tx.execute(
581            "DELETE FROM face_review_queue WHERE face_id = ?1",
582            params![face_id],
583        )?;
584        tx.execute(
585            "DELETE FROM face_negatives WHERE face_id = ?1",
586            params![face_id],
587        )?;
588        tx.execute(
589            "DELETE FROM person_gallery_embeddings WHERE face_id = ?1",
590            params![face_id],
591        )?;
592        tx.execute("DELETE FROM faces WHERE id = ?1", params![face_id])?;
593    }
594
595    tx.execute(
596        "DELETE FROM photo_inferred_identities WHERE photo_id = ?1 OR source_photo_id = ?1",
597        params![photo_id],
598    )?;
599
600    Ok(())
601}
602
603#[cfg(test)]
604mod tests {
605    use super::*;
606    use crate::db::create_schema;
607    use crate::services::scanner::calculate_hash;
608    use std::io::Write;
609    use tempfile::tempdir;
610
611    /// Two files sharing a 64 KB prefix but differing afterwards must hash
612    /// differently. The previous quick_hash (64 KB only) collided here, which
613    /// caused the reindexer to misidentify distinct files as moves of each
614    /// other.
615    #[test]
616    fn full_hash_distinguishes_files_with_shared_prefix() {
617        let temp = tempdir().unwrap();
618        let prefix = vec![0xABu8; 65_536];
619
620        let path_a = temp.path().join("a.bin");
621        let mut f = fs::File::create(&path_a).unwrap();
622        f.write_all(&prefix).unwrap();
623        f.write_all(&[0x01u8; 4096]).unwrap();
624        drop(f);
625
626        let path_b = temp.path().join("b.bin");
627        let mut f = fs::File::create(&path_b).unwrap();
628        f.write_all(&prefix).unwrap();
629        f.write_all(&[0x02u8; 4096]).unwrap();
630        drop(f);
631
632        let hash_a = calculate_hash(&path_a).unwrap();
633        let hash_b = calculate_hash(&path_b).unwrap();
634        assert_ne!(
635            hash_a, hash_b,
636            "files differing past the first 64 KB must produce different hashes"
637        );
638    }
639
640    #[test]
641    fn reindexer_excludes_folder_descendants() {
642        let temp = tempdir().unwrap();
643        let excluded = temp.path().join("Trips").join("Goa");
644        let similar = temp.path().join("Trips").join("Goa2");
645        fs::create_dir_all(&excluded).unwrap();
646        fs::create_dir_all(&similar).unwrap();
647
648        let matcher = ExclusionMatcher::new(vec!["Trips/Goa".into()]);
649        let reindexer = Reindexer::new();
650
651        assert!(reindexer.should_skip(temp.path(), &excluded, &matcher));
652        assert!(!reindexer.should_skip(temp.path(), &similar, &matcher));
653    }
654
655    #[test]
656    fn apply_removed_files_creates_trash_rows() {
657        let conn = Connection::open_in_memory().unwrap();
658        create_schema(&conn).unwrap();
659        conn.execute(
660            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, is_trashed)
661             VALUES (1, 'missing.jpg', 'missing.jpg', 'hash', 8, FALSE)",
662            [],
663        )
664        .unwrap();
665
666        let changes = IndexChanges {
667            removed: vec![(1, PathBuf::from("missing.jpg"))],
668            ..IndexChanges::default()
669        };
670        let result = Reindexer::new().apply_changes(&conn, &changes).unwrap();
671
672        assert_eq!(result.removals_applied, 1);
673        let is_trashed: bool = conn
674            .query_row("SELECT is_trashed FROM photos WHERE id = 1", [], |row| {
675                row.get(0)
676            })
677            .unwrap();
678        assert!(is_trashed);
679        let original_path: String = conn
680            .query_row(
681                "SELECT original_path FROM trash WHERE photo_id = 1",
682                [],
683                |row| row.get(0),
684            )
685            .unwrap();
686        assert_eq!(original_path, "missing.jpg");
687    }
688
689    #[test]
690    fn detect_changes_uses_file_mtime_for_modified_files() {
691        let temp = tempdir().unwrap();
692        let path = temp.path().join("photo.jpg");
693        fs::write(&path, vec![0xABu8; 12_000]).unwrap();
694        let metadata = fs::metadata(&path).unwrap();
695        let current_mtime = metadata
696            .modified()
697            .unwrap()
698            .duration_since(std::time::UNIX_EPOCH)
699            .unwrap()
700            .as_secs() as i64;
701
702        let conn = Connection::open_in_memory().unwrap();
703        create_schema(&conn).unwrap();
704        conn.execute(
705            "INSERT INTO photos (
706                id, file_path, file_name, file_hash, file_size, file_mtime,
707                metadata_extracted, thumbnailed, faces_processed, updated_at
708             ) VALUES (
709                1, 'photo.jpg', 'photo.jpg', 'hash', 12000, ?1,
710                TRUE, TRUE, TRUE, datetime('now', '+1 day')
711             )",
712            [current_mtime - 10],
713        )
714        .unwrap();
715
716        let changes = Reindexer::new_with_options(true)
717            .detect_changes(&conn, temp.path())
718            .unwrap();
719        assert_eq!(changes.modified.len(), 1);
720        assert_eq!(changes.modified[0].0, 1);
721    }
722
723    #[test]
724    fn detect_changes_identifies_moved_files() {
725        let temp = tempdir().unwrap();
726        let new_dir = temp.path().join("new");
727        fs::create_dir_all(&new_dir).unwrap();
728        let new_path = new_dir.join("photo.jpg");
729        fs::write(&new_path, vec![0xEFu8; 12_000]).unwrap();
730        let meta = fs::metadata(&new_path).unwrap();
731        let mtime = meta
732            .modified()
733            .ok()
734            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
735            .map(|d| d.as_secs() as i64);
736        let hash = calculate_fast_hash(&new_path, meta.len(), mtime).unwrap();
737
738        let conn = Connection::open_in_memory().unwrap();
739        create_schema(&conn).unwrap();
740        conn.execute(
741            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, is_trashed)
742             VALUES (1, 'old/photo.jpg', 'photo.jpg', ?1, ?2, FALSE)",
743            params![hash, meta.len() as i64],
744        )
745        .unwrap();
746
747        let changes = Reindexer::new_with_options(true)
748            .detect_changes(&conn, temp.path())
749            .unwrap();
750
751        assert_eq!(changes.moved.len(), 1);
752        assert_eq!(changes.moved[0].0, 1);
753        assert_eq!(changes.moved[0].1, PathBuf::from("old/photo.jpg"));
754        assert_eq!(changes.moved[0].2, PathBuf::from("new/photo.jpg"));
755        assert!(changes.added.is_empty());
756        assert!(changes.removed.is_empty());
757    }
758
759    #[test]
760    fn apply_modified_files_resets_stale_processing_state() {
761        let temp = tempdir().unwrap();
762        let changed_path = temp.path().join("changed.jpg");
763        fs::write(&changed_path, vec![0xCDu8; 12_000]).unwrap();
764        let meta = fs::metadata(&changed_path).unwrap();
765        let mtime = meta
766            .modified()
767            .ok()
768            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
769            .map(|d| d.as_secs() as i64);
770        let expected_hash = calculate_fast_hash(&changed_path, meta.len(), mtime).unwrap();
771
772        let conn = Connection::open_in_memory().unwrap();
773        create_schema(&conn).unwrap();
774        conn.execute(
775            "INSERT INTO photos (
776                id, file_path, file_name, file_hash, file_size, thumbnail_path,
777                file_mtime,
778                metadata_extracted, thumbnailed, faces_processed
779             ) VALUES (
780                1, 'changed.jpg', 'changed.jpg', 'old-hash', 8, '.photovault/thumbnails/medium/v2/ha/hash.jpg',
781                1,
782                TRUE, TRUE, TRUE
783             )",
784            [],
785        )
786        .unwrap();
787        conn.execute(
788            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size)
789             VALUES (2, 'other.jpg', 'other.jpg', 'other-hash', 8)",
790            [],
791        )
792        .unwrap();
793        conn.execute(
794            "INSERT INTO face_clusters (id, name, representative_face_id, face_count, photo_count)
795             VALUES (10, 'Stale', NULL, 1, 2), (20, 'Other', NULL, 0, 0)",
796            [],
797        )
798        .unwrap();
799        conn.execute(
800            "INSERT INTO faces (
801                id, photo_id, bbox_x, bbox_y, bbox_width, bbox_height,
802                embedding, cluster_id, confidence, user_confirmed
803             )
804             VALUES (100, 1, 0.1, 0.1, 0.2, 0.2, zeroblob(16), 10, 0.99, 0)",
805            [],
806        )
807        .unwrap();
808        conn.execute(
809            "UPDATE face_clusters SET representative_face_id = 100 WHERE id = 10",
810            [],
811        )
812        .unwrap();
813        conn.execute(
814            "INSERT INTO face_review_queue (face_id, candidate_cluster_id, score)
815             VALUES (100, 20, 0.75)",
816            [],
817        )
818        .unwrap();
819        conn.execute(
820            "INSERT INTO face_negatives (face_id, not_cluster_id) VALUES (100, 20)",
821            [],
822        )
823        .unwrap();
824        conn.execute(
825            "INSERT INTO person_gallery_embeddings (cluster_id, face_id, embedding)
826             VALUES (10, 100, zeroblob(16))",
827            [],
828        )
829        .unwrap();
830        conn.execute(
831            "INSERT INTO photo_inferred_identities (photo_id, cluster_id, source_photo_id, confidence)
832             VALUES (1, 10, 2, 0.5)",
833            [],
834        )
835        .unwrap();
836        conn.execute(
837            "INSERT INTO photo_inferred_identities (photo_id, cluster_id, source_photo_id, confidence)
838             VALUES (2, 10, 1, 0.5)",
839            [],
840        )
841        .unwrap();
842
843        let changes = IndexChanges {
844            modified: vec![(1, changed_path.clone())],
845            ..IndexChanges::default()
846        };
847        let result = Reindexer::new().apply_changes(&conn, &changes).unwrap();
848        assert_eq!(result.updates_applied, 1);
849
850        let row: (bool, bool, bool, Option<String>, i64, Option<i64>, String) = conn
851            .query_row(
852                "SELECT metadata_extracted, thumbnailed, faces_processed, thumbnail_path,
853                        file_size, file_mtime, file_hash
854                   FROM photos WHERE id = 1",
855                [],
856                |row| {
857                    Ok((
858                        row.get(0)?,
859                        row.get(1)?,
860                        row.get(2)?,
861                        row.get(3)?,
862                        row.get(4)?,
863                        row.get(5)?,
864                        row.get(6)?,
865                    ))
866                },
867            )
868            .unwrap();
869        assert_eq!(
870            row,
871            (
872                false,
873                false,
874                false,
875                None,
876                meta.len() as i64,
877                mtime,
878                expected_hash
879            )
880        );
881
882        for table in [
883            "faces",
884            "face_review_queue",
885            "face_negatives",
886            "person_gallery_embeddings",
887            "photo_inferred_identities",
888        ] {
889            let count: i64 = conn
890                .query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |row| {
891                    row.get(0)
892                })
893                .unwrap();
894            assert_eq!(count, 0, "{table} should be cleared");
895        }
896        let cluster_count: i64 = conn
897            .query_row(
898                "SELECT COUNT(*) FROM face_clusters WHERE id = 10",
899                [],
900                |row| row.get(0),
901            )
902            .unwrap();
903        assert_eq!(cluster_count, 0, "empty stale cluster should be pruned");
904    }
905
906    #[test]
907    fn timezone_and_fat_mtime_shifts_are_not_modifications() {
908        // Same size, FAT 2 s rounding / whole-hour / half-hour / DST shifts.
909        for delta in [1, 2, 3600, -3600, 1800, 5 * 3600 + 1800, 14 * 3600] {
910            assert!(
911                !content_may_have_changed(100, Some(1_000_000), 100, Some(1_000_000 + delta)),
912                "delta {delta} should be treated as unchanged"
913            );
914        }
915        // Real edits.
916        assert!(content_may_have_changed(
917            100,
918            Some(1_000_000),
919            101,
920            Some(1_000_000)
921        ));
922        assert!(content_may_have_changed(
923            100,
924            Some(1_000_000),
925            100,
926            Some(1_000_123)
927        ));
928        assert!(content_may_have_changed(
929            100,
930            Some(1_000_000),
931            100,
932            Some(1_000_000 + 15 * 3600)
933        ));
934        // Legacy rows without an mtime only compare size.
935        assert!(!content_may_have_changed(100, None, 100, Some(5)));
936    }
937
938    #[test]
939    fn prefix_match_respects_path_components() {
940        let prefixes = vec!["Trips/Goa".to_string()];
941        assert!(is_under_any_prefix("Trips/Goa", &prefixes));
942        assert!(is_under_any_prefix("Trips/Goa/a.jpg", &prefixes));
943        assert!(!is_under_any_prefix("Trips/Goa2/a.jpg", &prefixes));
944    }
945
946    #[test]
947    fn reindexer_skips_scanner_skip_directories() {
948        let temp = tempdir().unwrap();
949        let ea = temp.path().join("@eaDir");
950        fs::create_dir_all(&ea).unwrap();
951        let matcher = ExclusionMatcher::new(vec![]);
952        assert!(Reindexer::new().should_skip(temp.path(), &ea, &matcher));
953    }
954
955    fn insert_photo_row(conn: &Connection, id: i64, path: &str) {
956        conn.execute(
957            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, is_trashed)
958             VALUES (?1, ?2, ?2, ?3, 2048, FALSE)",
959            params![id, path, format!("hash-{id}")],
960        )
961        .unwrap();
962    }
963
964    #[test]
965    fn reconcile_trashes_a_few_missing_files() {
966        let temp = tempdir().unwrap();
967        let conn = Connection::open_in_memory().unwrap();
968        create_schema(&conn).unwrap();
969        for id in 1..=10 {
970            let name = format!("p{id}.jpg");
971            let path = temp.path().join(&name);
972            fs::write(&path, vec![0u8; 2048]).unwrap();
973            insert_photo_row(&conn, id, &name);
974        }
975        // Record the real mtimes so present files aren't seen as modified.
976        for id in 1..=10 {
977            let meta = fs::metadata(temp.path().join(format!("p{id}.jpg"))).unwrap();
978            let mtime = meta
979                .modified()
980                .unwrap()
981                .duration_since(std::time::UNIX_EPOCH)
982                .unwrap()
983                .as_secs() as i64;
984            conn.execute(
985                "UPDATE photos SET file_mtime = ?1 WHERE id = ?2",
986                params![mtime, id],
987            )
988            .unwrap();
989        }
990        fs::remove_file(temp.path().join("p3.jpg")).unwrap();
991
992        let outcome = Reindexer::new_with_options(true)
993            .reconcile_existing(&conn, temp.path())
994            .unwrap();
995        assert_eq!(outcome.applied.removals_applied, 1);
996        assert_eq!(outcome.applied.updates_applied, 0);
997        assert_eq!(outcome.held_back_removals, 0);
998    }
999
1000    #[test]
1001    fn reconcile_never_trashes_types_no_longer_indexed() {
1002        let temp = tempdir().unwrap();
1003        let conn = Connection::open_in_memory().unwrap();
1004        create_schema(&conn).unwrap();
1005        // Indexed by an older build; the file is still on disk, but the
1006        // walk no longer reports .avif files.
1007        fs::write(temp.path().join("old.avif"), vec![0u8; 2048]).unwrap();
1008        insert_photo_row(&conn, 1, "old.avif");
1009
1010        let outcome = Reindexer::new_with_options(true)
1011            .reconcile_existing(&conn, temp.path())
1012            .unwrap();
1013        assert_eq!(outcome.applied.removals_applied, 0);
1014        assert_eq!(outcome.held_back_removals, 0);
1015    }
1016
1017    #[test]
1018    fn reconcile_holds_back_mass_removal() {
1019        let temp = tempdir().unwrap();
1020        let conn = Connection::open_in_memory().unwrap();
1021        create_schema(&conn).unwrap();
1022        // 40 indexed photos, none present on disk: looks like a
1023        // disconnected folder, not 40 deliberate deletions.
1024        for id in 1..=40 {
1025            insert_photo_row(&conn, id, &format!("Gone/p{id}.jpg"));
1026        }
1027
1028        let outcome = Reindexer::new_with_options(true)
1029            .reconcile_existing(&conn, temp.path())
1030            .unwrap();
1031        assert_eq!(outcome.applied.removals_applied, 0);
1032        assert_eq!(outcome.held_back_removals, 40);
1033        let trashed: i64 = conn
1034            .query_row(
1035                "SELECT COUNT(*) FROM photos WHERE is_trashed = TRUE",
1036                [],
1037                |row| row.get(0),
1038            )
1039            .unwrap();
1040        assert_eq!(trashed, 0);
1041    }
1042
1043    #[test]
1044    fn apply_moved_files_updates_file_name() {
1045        let conn = Connection::open_in_memory().unwrap();
1046        create_schema(&conn).unwrap();
1047        conn.execute(
1048            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size)
1049             VALUES (1, 'old/name.jpg', 'name.jpg', 'hash', 8)",
1050            [],
1051        )
1052        .unwrap();
1053
1054        let changes = IndexChanges {
1055            moved: vec![(
1056                1,
1057                PathBuf::from("old/name.jpg"),
1058                PathBuf::from("new/renamed.jpg"),
1059            )],
1060            ..IndexChanges::default()
1061        };
1062        let result = Reindexer::new().apply_changes(&conn, &changes).unwrap();
1063        assert_eq!(result.moves_applied, 1);
1064
1065        let row: (String, String) = conn
1066            .query_row(
1067                "SELECT file_path, file_name FROM photos WHERE id = 1",
1068                [],
1069                |row| Ok((row.get(0)?, row.get(1)?)),
1070            )
1071            .unwrap();
1072        assert_eq!(row, ("new/renamed.jpg".into(), "renamed.jpg".into()));
1073    }
1074}