From 418d63105767705109af80690abd0e06ec85e35b Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 20 Oct 2026 15:49:40 -0400 Subject: [PATCH 1/5] PERF-SEARCH: search and Text rules read each photo's text from a kept lower-cased copy The library search lower-cased the word and each photo's file name, title, caption, camera, lens, location, format and every keyword, for every photo and every word, on every keystroke; a smart album's Text rule joined and lower-cased a photo's text the same way. At 312 000 photos that was most of the time of a keystroke. The catalog now keeps each photo's lower-cased searchable text, made the first time it is asked for (like the other indexes) and kept current by the ops that change a searched field (AddPhoto, RemovePhoto, SetMeta, SetFile, Relink), their inverses and the rollback of a failed batch. A smart album's Text rule has its own kept text, made on first use, so the sidebar counts and the grid use it too. The search words are lower-cased once per query. A photo that isn't the catalog's own (a copy tried with other values) is still read from its own fields. Which photos match is unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/index.rs | 166 ++++++++- crates/catalog/src/lib.rs | 21 +- crates/catalog/src/query.rs | 58 +++- crates/catalog/src/rules.rs | 55 +-- crates/catalog/src/tests_search_text.rs | 429 ++++++++++++++++++++++++ docs/whats-new.md | 11 + 6 files changed, 699 insertions(+), 41 deletions(-) create mode 100644 crates/catalog/src/tests_search_text.rs diff --git a/crates/catalog/src/index.rs b/crates/catalog/src/index.rs index 2c347473bc..14d441a167 100644 --- a/crates/catalog/src/index.rs +++ b/crates/catalog/src/index.rs @@ -11,7 +11,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::OnceLock; -use crate::{AlbumId, Catalog, PhotoId, StackId}; +use crate::{AlbumId, Catalog, Photo, PhotoId, StackId}; #[derive(Default)] pub(crate) struct Indexes { @@ -20,6 +20,10 @@ pub(crate) struct Indexes { stacks: OnceLock>>, /// Album → its photos (regular albums; a smart album's list is empty). albums: OnceLock>>, + /// Photo → its lower-cased searchable text ([`PhotoText`]), for the free-text search. + search: OnceLock>, + /// Photo → the lower-cased text a smart album's Text rule looks through ([`crate::rules::rule_text`]). + rule_text: OnceLock>, } /// A copy builds its own when asked (copies are made to be saved, not queried). @@ -70,6 +74,145 @@ impl Indexes { } } } + + /// Photo `id` is `p` now (`None`: it is gone): the text kept for it is made again. + pub(crate) fn text_changed(&mut self, id: PhotoId, p: Option<&Photo>) { + if let Some(m) = self.search.get_mut() { + match p { + Some(p) => m.insert(id, PhotoText::of(p)), + None => m.remove(&id), + }; + } + if let Some(m) = self.rule_text.get_mut() { + match p { + Some(p) => m.insert(id, RuleText::of(p)), + None => m.remove(&id), + }; + } + } + + /// Photo `id` is about to be changed in place, at `p`: an edit of a photo that others hold + /// (`Arc::make_mut`) puts it at another address, which its text follows. + pub(crate) fn text_moved(&mut self, id: PhotoId, p: &Photo) { + let at = addr(p); + if let Some(t) = self.search.get_mut().and_then(|m| m.get_mut(&id)) { + t.at = at; + } + if let Some(t) = self.rule_text.get_mut().and_then(|m| m.get_mut(&id)) { + t.at = at; + } + } +} + +/// A map from photos, for a pass over the library that asks about each one in id order. +type ByPhoto = HashMap>; + +/// Hashes a photo id as itself in the table's low bits, which is where the table looks first, so +/// ids that follow each other sit next to each other and a pass in id order walks it in order +/// rather than jumping about (a pass over 300 000 photos spent most of its time on that). The top +/// bits, which tag an entry in the table, are mixed so entries still tell each other apart. +#[derive(Default)] +pub(crate) struct IdHasher(u64); + +impl std::hash::Hasher for IdHasher { + fn finish(&self) -> u64 { + self.0 ^ (self.0.wrapping_mul(0x9E37_79B9_7F4A_7C15) & 0xFE00_0000_0000_0000) + } + + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = self.0.rotate_left(8) ^ u64::from(*b); + } + } + + fn write_u64(&mut self, n: u64) { + self.0 = n; + } +} + +/// Where `p` is in memory. The contract of the kept texts: a text is used only for the photo at the +/// address it was made for. The catalog's own photos (`Arc` contents) stay where they are +/// until `Arc::make_mut` copies one that others hold, which `photo_mut` reports ([`Indexes::text_moved`]); +/// every op that changes a searched field makes the text again ([`Indexes::text_changed`]). A copy +/// of a photo (a candidate tried with other values) is at another address, so it is read from its +/// own fields, never from a text kept for the photo with its id. Only ids and addresses are +/// compared; the address is never turned back into a reference. A catalog read from a snapshot +/// (and then repaired) or cloned starts with no texts at all: they are made when asked. +fn addr(p: &Photo) -> usize { + std::ptr::from_ref(p).addr() +} + +/// What the free-text search looks through for one photo, lower-cased as `str::to_lowercase` does +/// for each field alone: file name, title, caption, camera, lens, location, format, then each +/// keyword, then the name of each person (a named face), separated by NUL. A search word may hold +/// white space (a quoted phrase) but never NUL, so it never runs over a field. +pub(crate) struct PhotoText { + /// The address of the photo this was made from ([`addr`]). + at: usize, + text: Box, +} + +impl PhotoText { + pub(crate) fn of(p: &Photo) -> PhotoText { + let fields = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]; + let people = p.people(); + // (exact for ASCII, which most text is: the box takes the buffer without copying it) + let len = fields + .iter() + .map(|f| f.len() + 1) + .chain(p.meta.keywords.iter().map(|k| k.len() + 1)) + .chain(people.iter().map(|n| n.len() + 1)) + .sum::() + .saturating_sub(1); + let mut text = String::with_capacity(len); + for (i, field) in fields.into_iter().enumerate() { + if i > 0 { + text.push('\0'); + } + push_lowercase(&mut text, field); + } + for k in p.meta.keywords.iter().map(String::as_str).chain(people) { + text.push('\0'); + push_lowercase(&mut text, k); + } + PhotoText { at: addr(p), text: text.into_boxed_str() } + } + + /// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens, + /// location, format, a keyword or the name of a person. + pub(crate) fn contains(&self, t: &str) -> bool { + self.text.contains(t) + } + + #[cfg(test)] + pub(crate) fn text(&self) -> &str { + &self.text + } +} + +/// Push `s` lower-cased as `str::to_lowercase` gives it, without a temporary string for ASCII. +fn push_lowercase(out: &mut String, s: &str) { + if s.is_ascii() { + let from = out.len(); + out.push_str(s); + if let Some(added) = out.get_mut(from..) { + added.make_ascii_lowercase(); + } + } else { + out.push_str(&s.to_lowercase()); + } +} + +/// A photo's text for a smart album's Text rule: [`crate::rules::rule_text`]. +struct RuleText { + at: usize, + text: Box, +} + +impl RuleText { + fn of(p: &Photo) -> RuleText { + RuleText { at: addr(p), text: crate::rules::rule_text(p).into_boxed_str() } + } } impl Catalog { @@ -98,4 +241,25 @@ impl Catalog { let m = self.index.albums.get_or_init(|| self.albums.values().map(|a| (a.id, a.photos.iter().copied().collect())).collect()); m.get(&album).is_some_and(|s| s.contains(&photo)) } + + /// `p`'s lower-cased text for the free-text search, when `p` is this catalog's own photo and the + /// text was made. `build`: make it for every photo first when it wasn't (a pass over the whole + /// library does; testing one photo shouldn't build it for 300 000). + pub(crate) fn search_text(&self, p: &Photo, build: bool) -> Option<&PhotoText> { + let m = if build { + self.index.search.get_or_init(|| self.photos.values().map(|p| (p.id, PhotoText::of(p))).collect()) + } else { + self.index.search.get()? + }; + m.get(&p.id).filter(|t| t.at == addr(p)) + } + + /// [`Catalog::search_text`] for a smart album's Text rule: the lower-cased, trimmed text of + /// [`crate::rules::rule_text`], made for every photo on first use (a smart album's count or + /// view asks for it photo by photo). + pub(crate) fn rule_text_of(&self, p: &Photo) -> Option<&str> { + let m = self.index.rule_text.get_or_init(|| self.photos.values().map(|p| (p.id, RuleText::of(p))).collect()); + let t = m.get(&p.id)?; + (t.at == addr(p)).then_some(&*t.text) + } } diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 7e094200ca..4a07efdd77 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -568,7 +568,10 @@ impl Catalog { fn photo_mut(&mut self, id: PhotoId) -> Result<&mut Photo> { self.touch(id); - self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id)) + let p = self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id))?; + // (`Arc::make_mut` copies a photo others hold: the text kept for it goes with the copy) + self.index.text_moved(id, p); + Ok(p) } /// The op being applied changes photo `id` (or adds or removes it). @@ -706,10 +709,12 @@ impl Catalog { let id = photo.id; self.next_photo = self.next_photo.max(id.0.saturating_add(1)); self.photos.insert(id, Arc::new(*photo)); + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); Op::RemovePhoto { id } } Op::RemovePhoto { id } => { let p = self.photos.remove(&id).ok_or(CatalogError::NoPhoto(id))?; + self.index.text_changed(id, None); // album membership is restored by the batch the engine builds (see `delete_permanently`) Op::AddPhoto { photo: Box::new((*p).clone()) } } @@ -737,7 +742,9 @@ impl Catalog { } Op::SetMeta { id, meta } => { let p = self.photo_mut(id)?; - Op::SetMeta { id, meta: Box::new(std::mem::replace(&mut p.meta, *meta)) } + let old = std::mem::replace(&mut p.meta, *meta); + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); + Op::SetMeta { id, meta: Box::new(old) } } Op::SetDeleted { id, deleted } => { let p = self.photo_mut(id)?; @@ -912,7 +919,9 @@ impl Catalog { let p = self.photo_mut(id)?; let old_name = std::mem::replace(&mut p.file_name, file_name); let old_format = format.map(|f| std::mem::replace(&mut p.format, f)); - Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format } + let old = Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format }; + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); + old } Op::SetContent { id, width, height, file_size, content_hash, preview_only, preview_checked } => { let p = self.photo_mut(id)?; @@ -943,7 +952,9 @@ impl Catalog { } let p = self.photo_mut(id)?; let old_name = std::mem::replace(&mut p.file_name, file_name); - Op::SetFile { id, file_name: old_name, source: std::mem::replace(&mut p.source, source) } + let old = Op::SetFile { id, file_name: old_name, source: std::mem::replace(&mut p.source, source) }; + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); + old } Op::SetLabelName { label, name } => { let name = name.map(|n| n.trim().to_string()).filter(|n| !n.is_empty()); @@ -1225,6 +1236,8 @@ mod tests_repair; #[cfg(test)] mod tests_scale; #[cfg(test)] +mod tests_search_text; +#[cfg(test)] mod tests_tally; #[cfg(test)] mod tests_torn_append; diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index ff94268a8b..e102c5c0ba 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -143,6 +143,10 @@ fn shuffle_rank(seed: u64, id: PhotoId) -> u64 { pub(crate) struct Prepared { root: Option, only: Option>, + /// The search words ([`Filter::tokens`]). + tokens: Vec, + /// A pass over the library, which makes the text kept for each photo when it isn't ([`Catalog::search_text`]). + whole: bool, } /// The tokens of a search text: split at whitespace, except inside double quotes, so @@ -174,8 +178,8 @@ fn unquote(s: &str) -> &str { s.strip_prefix('"').map_or(s, |inner| inner.strip_suffix('"').unwrap_or(inner)) } -fn token_matches(p: &Photo, tok: &str) -> bool { - let t = tok.to_lowercase(); +/// Whether the word `t` (lower-cased) is in `p`, as a field of it or as plain text. +fn token_matches(p: &Photo, t: &str, hay: &Hay) -> bool { // a token that starts with a quote is a phrase, even with a colon in it if let Some((field, quoted)) = t.split_once(':').filter(|_| !t.starts_with('"')) { let val = unquote(quoted); @@ -217,20 +221,30 @@ fn token_matches(p: &Photo, tok: &str) -> bool { "name" | "file" => p.file_name.to_lowercase().contains(val), // Not a known field: the colon is part of a plain word ("10:30", "Re:"), its value unquoted // (`re:"a b"` is the text `re:a b`). - _ if val.len() != quoted.len() => text_matches(p, &format!("{field}:{val}")), - _ => text_matches(p, &t), + _ if val.len() != quoted.len() => hay.text().contains(&format!("{field}:{val}")), + _ => hay.text().contains(t), }; } - text_matches(p, unquote(&t)) + hay.text().contains(unquote(t)) } -/// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens, location, -/// format, a keyword or the name of a person (a named face) of `p`. -fn text_matches(p: &Photo, t: &str) -> bool { - let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]; - hay.iter().any(|h| h.to_lowercase().contains(t)) - || p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t)) - || p.people().iter().any(|n| n.to_lowercase().contains(t)) +/// A photo's lower-cased text for the free-text search: the one the catalog keeps when `p` is its +/// own photo and a pass over the library made them ([`Prepared::whole`]), else made when first asked. +struct Hay<'a> { + p: &'a Photo, + cat: &'a Catalog, + whole: bool, + kept: std::cell::OnceCell>, + own: std::cell::OnceCell, +} + +impl Hay<'_> { + fn text(&self) -> &crate::index::PhotoText { + match self.kept.get_or_init(|| self.cat.search_text(self.p, self.whole)) { + Some(t) => t, + None => self.own.get_or_init(|| crate::index::PhotoText::of(self.p)), + } + } } /// Whether `p` has a named face region called `name` (case-insensitive). @@ -332,13 +346,23 @@ impl Filter { /// [`Filter::prepare`] for testing one photo (the `only` ids are looked through, not hashed). pub(crate) fn prepare_one(&self) -> Prepared { - Prepared { root: self.library_root(), only: None } + Prepared { root: self.library_root(), only: None, tokens: self.tokens(), whole: false } } /// What [`Filter::matches_in`] needs worked out once for a pass over many photos rather than /// once per photo: the library folder's identity and the `only` ids as a set. pub(crate) fn prepare(&self) -> Prepared { - Prepared { root: self.library_root(), only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()) } + Prepared { + root: self.library_root(), + only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()), + tokens: self.tokens(), + whole: true, + } + } + + /// The search words ([`search_tokens`]), lower-cased (as `str::to_lowercase` does, once per query, not once per photo). + fn tokens(&self) -> Vec { + search_tokens(&self.text).map(str::to_lowercase).collect() } /// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice. @@ -462,7 +486,11 @@ impl Filter { { return false; } - search_tokens(&self.text).all(|tok| token_matches(p, tok)) + if prepared.tokens.is_empty() { + return true; + } + let hay = Hay { p, cat, whole: prepared.whole, kept: std::cell::OnceCell::new(), own: std::cell::OnceCell::new() }; + prepared.tokens.iter().all(|t| token_matches(p, t, &hay)) } } diff --git a/crates/catalog/src/rules.rs b/crates/catalog/src/rules.rs index 2976a2659b..9b2c3c90ab 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -702,8 +702,37 @@ fn lower(v: &Value) -> String { } } +/// What a Text rule looks through for `p`: its file name, title, caption, camera, lens, location, city, +/// state, country, alt text, format, keywords, people and copy name, trimmed and lower-cased. +pub(crate) fn rule_text(p: &Photo) -> String { + let m = &p.meta; + let all = [ + p.file_name.as_str(), + &m.title, + &m.caption, + &m.camera, + &m.lens, + &m.location, + &m.city, + &m.state, + &m.country, + &m.alt_text, + &p.format, + &m.keywords.join(" "), + &p.people().join(" "), + p.copy_name.as_deref().unwrap_or(""), + ] + .join(" "); + let all = all.trim(); + if all.is_ascii() { all.to_ascii_lowercase() } else { all.to_lowercase() } +} + fn text_op(op: &str, have: &str, want: &str) -> bool { - let have = have.trim().to_lowercase(); + text_op_lowered(op, &have.trim().to_lowercase(), want) +} + +/// [`text_op`] for a `have` that is trimmed and lower-cased already. +fn text_op_lowered(op: &str, have: &str, want: &str) -> bool { match op { "contains" => want.split_whitespace().all(|w| have.contains(w)), "notContains" => !want.split_whitespace().any(|w| have.contains(w)), @@ -981,26 +1010,10 @@ impl Rule { "keywordCount" => num_op(op, Some(p.keyword_count() as f64), value), "person" => names_op(op, &p.people(), &want), "personCount" => num_op(op, Some(p.people().len() as f64), value), - "text" => { - let all = [ - p.file_name.as_str(), - &m.title, - &m.caption, - &m.camera, - &m.lens, - &m.location, - &m.city, - &m.state, - &m.country, - &m.alt_text, - &p.format, - &m.keywords.join(" "), - &p.people().join(" "), - p.copy_name.as_deref().unwrap_or(""), - ] - .join(" "); - text(&all) - } + "text" => match cat.rule_text_of(p) { + Some(have) => text_op_lowered(op, have, &want), + None => text_op_lowered(op, &rule_text(p), &want), + }, "fileName" => text(&p.file_name), "extension" => text_op(op, p.extension(), want.trim_start_matches('.')), "duration" => num_op(op, p.duration.filter(|d| d.is_finite()), value), diff --git a/crates/catalog/src/tests_search_text.rs b/crates/catalog/src/tests_search_text.rs new file mode 100644 index 0000000000..123e6d5692 --- /dev/null +++ b/crates/catalog/src/tests_search_text.rs @@ -0,0 +1,429 @@ +//! The free-text search and smart albums' Text rules read a photo's lower-cased text from a cache +//! ([`crate::index`]) rather than lower-casing every field of every photo on every keystroke. The +//! cache must give the matches the fields give, and follow every edit of a field it holds. + +use lightcraft_meta::{Rect, Region, RegionKind}; +use serde_json::json; + +use super::*; +use crate::index::PhotoText; + +fn photo(id: u64, file: &str) -> Photo { + Photo::new(PhotoId(id), Source::Demo { scene: 1 }, file, "JPEG", 60, 40, "2026-01-01T00:00:00") +} + +fn face(name: &str) -> Region { + Region { rect: Rect { x0: 0.4, y0: 0.4, x1: 0.6, y1: 0.6 }, kind: RegionKind::Face, name: Some(name.into()), description: None } +} + +/// Photos whose text is hard on a lower-casing shortcut: Unicode that changes length or depends on +/// its neighbours, a word that is only there across two fields, a colon in a plain word. +fn library() -> Catalog { + let mut photos = Vec::new(); + let mut p = photo(1, "IMG_0001.JPG"); + p.rating = 3; + p.meta.camera = "Canon EOS R5".into(); + p.meta.lens = "RF24-70mm F2.8 L".into(); + p.meta.title = "Trip to Ōsaka".into(); + p.meta.caption = "Straße am Fluss".into(); + p.meta.location = "Kyōto".into(); + p.meta.keywords = vec!["Travel|Italy".into(), "Ὀδυσσεύς".into(), "Kyōto Japan".into()]; + photos.push(p); + let mut p = photo(2, "İstanbul.jpg"); + p.meta.title = "ΣΊΣΥΦΟΣ".into(); + p.meta.caption = "Re: 10:30 meeting".into(); + p.meta.city = "Zürich".into(); + p.meta.regions = vec![face("Ana Lima")]; + photos.push(p); + let mut p = photo(3, "plain.png"); + p.format = "PNG".into(); + photos.push(p); + let mut p = photo(4, "abc"); + p.meta.camera = "def".into(); + p.meta.title = "Dž dž".into(); + photos.push(p); + let mut p = photo(5, "name:colon.jpg"); + p.meta.lens = "title:trip".into(); + p.copy_name = Some("Black and White".into()); + photos.push(p); + let mut c = Catalog::new(); + for p in photos { + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + c +} + +/// How the search read a word before the cache: each field lower-cased alone, for every photo. +fn before_text_matches(p: &Photo, t: &str) -> bool { + let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]; + hay.iter().any(|h| h.to_lowercase().contains(t)) + || p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t)) + || p.people().iter().any(|n| n.to_lowercase().contains(t)) +} + +/// [`before_text_matches`] for the words the tests use: plain ones and the fields the cache serves. +fn before_matches(p: &Photo, text: &str) -> bool { + text.split_whitespace().all(|tok| { + let t = tok.to_lowercase(); + match t.split_once(':') { + Some(("camera", val)) => p.meta.camera.to_lowercase().contains(val), + Some(("lens", val)) => p.meta.lens.to_lowercase().contains(val), + Some(("name" | "file", val)) => p.file_name.to_lowercase().contains(val), + Some(("rating", val)) => p.rating.to_string() == val, + Some(("kw" | "keyword", val)) => p.meta.keywords.iter().any(|k| crate::keywords::is_under(k, val)), + _ => before_text_matches(p, &t), + } + }) +} + +const QUERIES: &[&str] = &[ + "img", + "IMG_0001", + "IMG_0001.JPG", + "canon r5", + "CANON eos", + "ōsaka", + "ŌSAKA", + "osaka", + "straße", + "STRASSE", + "i̇stanbul", + "İSTANBUL", + "istanbul", + "σίσυφος", + "ΣΊΣΥΦΟΣ", + "ς", + "σ", + "ὀδυσσεύς", + "travel", + "italy", + "travel|italy", + "kyōto japan", + "kyōto", + "10:30", + "re:", + "name:img", + "NAME:IMG_0001", + "file:plain", + "name:", + "camera:canon", + "camera:r5", + "lens:rf24", + "lens:", + "title:trip", + "abcdef", + "abc def", + "dž", + "rating:3 trip", + "kw:travel ōsaka", + "kw:travel osaka", + "png jpeg", + "", + " ", + "zzz", +]; + +fn shown(c: &Catalog, text: &str) -> Vec { + let f = Filter { text: text.into(), ..Default::default() }; + let mut ids: Vec = c.query(&f, &Sort::default()).into_iter().map(|id| id.0).collect(); + ids.sort_unstable(); + ids +} + +fn expected(c: &Catalog, text: &str) -> Vec { + c.photos().filter(|p| !p.deleted && before_matches(p, text)).map(|p| p.id.0).collect() +} + +/// A search finds what the fields hold, whether it asks for one photo at a time, as a pass over the +/// library that makes the cache, or one photo after that. +#[test] +fn search_matches_as_the_fields_do() { + let c = library(); + let mut one_by_one = Vec::new(); + for q in QUERIES.iter().copied() { + let f = Filter { text: q.into(), ..Default::default() }; + one_by_one.push(c.photos().filter(|p| f.matches(p, &c)).map(|p| p.id.0).collect::>()); + } + assert!(c.photos().all(|p| c.search_text(p, false).is_none()), "testing one photo makes no cache for the library"); + for (q, got) in QUERIES.iter().zip(&one_by_one) { + assert_eq!(*got, expected(&c, q), "{q:?}, one photo at a time"); + } + for q in QUERIES.iter().copied() { + assert_eq!(shown(&c, q), expected(&c, q), "{q:?}, a pass over the library"); + } + assert!(c.photos().all(|p| c.search_text(p, false).is_some()), "a pass made the cache"); + for q in QUERIES.iter().copied() { + let f = Filter { text: q.into(), ..Default::default() }; + let got: Vec = c.photos().filter(|p| f.matches(p, &c)).map(|p| p.id.0).collect(); + assert_eq!(got, expected(&c, q), "{q:?}, one photo at a time, with the cache"); + } +} + +/// A photo that isn't the catalog's own (an edit not made yet, a candidate being tried) is read +/// from its own fields, not from what the catalog kept for the photo with its id. +#[test] +fn a_copy_of_a_photo_is_read_as_it_is() { + let c = library(); + let f = Filter { text: "ōsaka".into(), ..Default::default() }; + assert_eq!(c.count(&f), 1); + let mut p = (**c.photo(PhotoId(1)).unwrap()).clone(); + p.meta.title = "Trip to Nara".into(); + p.meta.keywords.clear(); + p.meta.location.clear(); + assert!(!f.matches(&p, &c), "the catalog's own text says Ōsaka, this copy doesn't"); + let nara = Filter { text: "nara".into(), ..Default::default() }; + assert!(nara.matches(&p, &c)); + assert!(!nara.matches(c.photo(PhotoId(1)).unwrap(), &c)); + let rule = Filter { rule_set: Some(rules(json!({"rules": [{"field": "text", "op": "contains", "value": "nara"}]}))), ..Default::default() }; + assert_eq!(c.count(&rule), 0); + assert!(rule.matches(&p, &c)); +} + +fn rules(v: serde_json::Value) -> RuleSet { + serde_json::from_value(v).unwrap() +} + +fn text_rule(op: &str, value: &str) -> Filter { + Filter { rule_set: Some(rules(json!({"rules": [{"field": "text", "op": op, "value": value}]}))), ..Default::default() } +} + +/// What the cache holds is what a scan of the photos would give it, and every photo's is used. +fn assert_current(c: &Catalog) { + for p in c.photos() { + let kept = c.search_text(p, false).unwrap_or_else(|| panic!("photo {}: no text kept, or kept for another place", p.id.0)); + let now = PhotoText::of(p); + assert_eq!(kept.text(), now.text(), "photo {}", p.id.0); + assert_eq!(c.rule_text_of(p), Some(crate::rules::rule_text(p).as_str()), "photo {}: the Text rule's text", p.id.0); + } +} + +/// Make the caches, as the first search and the first smart album with a Text rule do. +fn warm(c: &Catalog) { + c.count(&Filter { text: "x".into(), ..Default::default() }); + c.count(&text_rule("contains", "x")); + assert_current(c); +} + +fn found(c: &Catalog, text: &str) -> usize { + c.count(&Filter { text: text.into(), ..Default::default() }) +} + +fn found_by_rule(c: &Catalog, text: &str) -> usize { + c.count(&text_rule("contains", text)) +} + +/// An edit of each field that is searched puts the new text in the cache and takes the old one out, +/// through the op, its inverse and a batch that fails and is taken back. +#[test] +fn the_cache_follows_every_field_that_is_searched() { + let mut c = library(); + warm(&c); + let id = PhotoId(3); + let edit = |c: &mut Catalog, set: &dyn Fn(&mut Meta)| { + let mut meta = c.photo(id).unwrap().meta.clone(); + set(&mut meta); + c.apply(Op::SetMeta { id, meta: Box::new(meta) }).unwrap() + }; + type Set = fn(&mut Meta, &str); + let fields: [(&str, Set); 6] = [ + ("title", |m, v| m.title = v.into()), + ("caption", |m, v| m.caption = v.into()), + ("camera", |m, v| m.camera = v.into()), + ("lens", |m, v| m.lens = v.into()), + ("location", |m, v| m.location = v.into()), + ("keywords", |m, v| m.keywords = vec![v.into()]), + ]; + for (n, (field, set)) in fields.into_iter().enumerate() { + let word = format!("Zq{n}x"); + let before = found(&c, &word); + let undo = edit(&mut c, &|m| set(m, &word)); + assert_eq!((before, found(&c, &word)), (0, 1), "{field}: found after the edit"); + assert_eq!(found_by_rule(&c, &word.to_lowercase()), 1, "{field}: the Text rule"); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!(found(&c, &word), 0, "{field}: gone after the undo"); + assert_current(&c); + } + // the fields only Text rules read + let rule_fields: [(&str, Set); 3] = + [("city", |m, v| m.city = v.into()), ("state", |m, v| m.state = v.into()), ("country", |m, v| m.country = v.into())]; + for (n, (field, set)) in rule_fields.into_iter().enumerate() { + let word = format!("zr{n}y"); + let undo = edit(&mut c, &|m| set(m, &word)); + assert_eq!((found_by_rule(&c, &word), found(&c, &word)), (1, 0), "{field}"); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!(found_by_rule(&c, &word), 0, "{field}: gone after the undo"); + } + let undo = edit(&mut c, &|m| m.alt_text = "zalt".into()); + assert_eq!(found_by_rule(&c, "zalt"), 1); + c.apply(undo).unwrap(); + assert_eq!(found_by_rule(&c, "zalt"), 0); + let undo = edit(&mut c, &|m| m.regions = vec![face("Zed Person")]); + assert_eq!(found_by_rule(&c, "zed person"), 1, "a person named on a face"); + c.apply(undo).unwrap(); + assert_eq!(found_by_rule(&c, "zed person"), 0); + assert_current(&c); +} + +#[test] +fn the_cache_follows_a_file_name_and_a_format() { + let mut c = library(); + warm(&c); + let id = PhotoId(3); + let source = Source::Demo { scene: 1 }; + let undo = c.apply(Op::SetFile { id, file_name: "Renamed_0042.PNG".into(), source: source.clone() }).unwrap(); + assert_eq!((found(&c, "renamed_0042"), found(&c, "plain"), found(&c, "name:renamed")), (1, 0, 1)); + assert_eq!((found_by_rule(&c, "renamed_0042"), found_by_rule(&c, "plain")), (1, 0)); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!((found(&c, "renamed_0042"), found(&c, "plain")), (0, 1)); + assert_current(&c); + + let undo = c.apply(Op::Relink { id, file_name: "Moved.TIF".into(), source: source.clone(), format: Some("TIFF".into()) }).unwrap(); + assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (1, 1, 0)); + assert_eq!((found_by_rule(&c, "moved"), found_by_rule(&c, "tiff"), found_by_rule(&c, "png")), (1, 1, 0)); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (0, 0, 1)); + assert_current(&c); +} + +/// A photo that comes or goes (an import, a virtual copy, a permanent delete and its undo) does +/// too, and a virtual copy's name is read by a Text rule. +#[test] +fn the_cache_follows_photos_that_come_and_go() { + let mut c = library(); + warm(&c); + let mut copy = (**c.photo(PhotoId(1)).unwrap()).clone(); + copy.id = PhotoId(9); + copy.copy_of = Some(PhotoId(1)); + copy.meta = Default::default(); + copy.copy_name = Some("Zcopy Name".into()); + copy.file_name = "Zfresh.jpg".into(); + let undo = c.apply(Op::AddPhoto { photo: Box::new(copy) }).unwrap(); + assert_eq!((found(&c, "zfresh"), found_by_rule(&c, "zcopy"), found(&c, "zcopy")), (1, 1, 0)); + assert_current(&c); + let redo = c.apply(undo).unwrap(); + assert_eq!((found(&c, "zfresh"), found_by_rule(&c, "zcopy")), (0, 0)); + assert_current(&c); + c.apply(redo).unwrap(); + assert_eq!(found(&c, "zfresh"), 1); + assert_current(&c); + let removed = c.apply(Op::RemovePhoto { id: PhotoId(1) }).unwrap(); + assert_eq!(found(&c, "ōsaka"), 0); + assert_current(&c); + c.apply(removed).unwrap(); + assert_eq!(found(&c, "ōsaka"), 1); + assert_current(&c); +} + +/// A batch that fails half way is taken back, and the cache with it. +#[test] +fn the_cache_follows_a_batch_that_fails() { + let mut c = library(); + warm(&c); + let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone(); + meta.title = "Zbatch title".into(); + let batch = Op::Batch { + ops: vec![ + Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) }, + Op::SetFile { id: PhotoId(3), file_name: "Zbatch.png".into(), source: Source::Demo { scene: 1 } }, + Op::SetFile { id: PhotoId(404), file_name: "gone.png".into(), source: Source::Demo { scene: 1 } }, + ], + }; + assert!(c.apply(batch).is_err()); + assert_eq!((found(&c, "zbatch"), found_by_rule(&c, "zbatch")), (0, 0)); + assert_eq!(found(&c, "plain"), 1); + assert_current(&c); +} + +/// An edit of a photo that something else holds (a thumbnail list, an undo step) puts it at another +/// place in memory. The cache follows it, so a search isn't left reading every such photo from its fields. +#[test] +fn the_cache_follows_a_photo_that_others_hold() { + let mut c = library(); + warm(&c); + let held: Vec<_> = c.photos().cloned().collect(); + for p in &held { + c.apply(Op::SetRating { id: p.id, rating: 5 }).unwrap(); + } + assert!(held.iter().all(|old| !std::ptr::eq(&**old, &**c.photo(old.id).unwrap())), "the edits copied the photos"); + assert_current(&c); + assert_eq!(found(&c, "ōsaka"), 1); + c.apply(Op::SetFile { id: PhotoId(2), file_name: "after.jpg".into(), source: Source::Demo { scene: 1 } }).unwrap(); + assert_current(&c); + assert_eq!((found(&c, "after"), found(&c, "istanbul")), (1, 0)); +} + +/// A catalog read from a snapshot or cloned starts with no cache and builds its own. +#[test] +fn a_clone_builds_its_own() { + let mut c = library(); + warm(&c); + let mut copy = c.clone(); + assert!(copy.photos().all(|p| copy.search_text(p, false).is_none())); + assert_eq!(found(©, "ōsaka"), 1); + warm(©); + let mut meta = copy.photo(PhotoId(1)).unwrap().meta.clone(); + meta.title = "Elsewhere".into(); + copy.apply(Op::SetMeta { id: PhotoId(1), meta: Box::new(meta) }).unwrap(); + assert_eq!((found(©, "elsewhere"), found(&c, "elsewhere")), (1, 0)); + c.apply(Op::SetRating { id: PhotoId(1), rating: 1 }).unwrap(); + assert_current(&c); +} + +/// The words of Text rules (not the search) read the same with the cache as without. +#[test] +fn text_rules_match_as_the_fields_do() { + let c = library(); + let every_op = ["contains", "notContains", "is", "isNot", "startsWith", "endsWith", "isEmpty", "isNotEmpty"]; + let values = + ["", "ōsaka", "TRIP TO", "kyōto japan", "ana lima", "zürich", "img_0001.jpg", "black and white", "ς", "i̇stanbul", "png", "re: 10:30 meeting"]; + let before: Vec> = + every_op.iter().map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(p, &c)).count()).collect()).collect(); + let after: Vec> = every_op.iter().map(|op| values.iter().map(|v| c.count(&text_rule(op, v))).collect()).collect(); + assert_eq!(before, after); + assert!(c.photos().all(|p| c.rule_text_of(p).is_some()), "the first rule asked made the text"); + let again: Vec> = + every_op.iter().map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(p, &c)).count()).collect()).collect(); + assert_eq!(before, again); +} + +/// A smart album's count through the tally path (`album_contains`, one photo at a time) reads the +/// kept text: it is made there, and an edit shows in the next count. +#[test] +fn a_smart_album_count_reads_the_kept_text() { + let mut c = library(); + let mut album = Album::new(AlbumId(1), "Osaka"); + album.smart = Some(Box::new(text_rule("contains", "ōsaka"))); + c.apply(Op::AddAlbum { album }).unwrap(); + let one_by_one = |c: &Catalog| c.photos().filter(|p| c.album_contains(AlbumId(1), p)).count(); + assert_eq!(one_by_one(&c), 1); + assert!(c.photos().all(|p| c.rule_text_of(p).is_some()), "counting made the text"); + let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone(); + meta.title = "Ōsaka again".into(); + c.apply(Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) }).unwrap(); + assert_eq!(one_by_one(&c), 2); +} + +/// The kept text holds the names of the people on a photo's faces, and a quoted phrase is read as +/// one word that never runs from one field into the next. +#[test] +fn the_kept_text_holds_the_people_and_a_phrase_stays_in_one_field() { + let mut c = library(); + warm(&c); + assert_eq!(found(&c, "ana"), 1, "a person's name is searched"); + assert_eq!(found(&c, "\"ana lima\""), 1, "a quoted name is one phrase"); + assert_eq!(found(&c, "\"lima ana\""), 0); + assert_eq!(found(&c, "\"ōsaka straße\""), 0, "a phrase doesn't run from the title into the caption"); + assert_eq!(found(&c, "\"trip to ōsaka\""), 1, "…but fits inside one field"); + assert_eq!(found(&c, "\"Kyōto Japan\""), 1, "…or one keyword"); + // (the photo that has Ana Lima's face) + let mut meta = c.photo(PhotoId(2)).unwrap().meta.clone(); + meta.regions = vec![face("Zed Person")]; + c.apply(Op::SetMeta { id: PhotoId(2), meta: Box::new(meta) }).unwrap(); + assert_eq!(found(&c, "\"zed person\""), 1, "a renamed person is found at once"); + assert_eq!(found(&c, "ana"), 0, "and the old name is gone"); + assert_current(&c); +} diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c2592003..8e63b0eca5 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -157,6 +157,17 @@ the full count took about 14 s instead of about 23 s on a heavily loaded machine; the rest is the text rules of the albums themselves. The counts are the same as before, including for albums that loop through each other. +### Searching a big library keeps up with your typing +- Typing in the library search stalls less on a library of hundreds of thousands of photos. The search used to + lower-case a photo's file name, title, caption, camera, lens, location, format, every keyword and the names of the + people on its faces again for each photo and each letter you typed. It now keeps that text, makes it the first time + you search, and keeps it up to date as you edit titles, captions, keywords, people and file names. Smart albums with + a Text rule keep their own text the same + way, made the first time such an album is counted or shown. Which photos match is unchanged. On a test library of + 312 000 photos, finding the photos for a word took about 50 ms where it took 120 to 160 ms. The first search makes + the text, which takes a fraction of a second and about 32 MB of memory at that size; a Text rule's text is another + 33 MB. Searches with `camera:`, `lens:` or `name:` gain less (about 70 ms became about 60 ms). + ### Sharper resampling in HDR and panorama merges - Merged photos (HDR and panorama) are resampled with a sharper filter (Lanczos-3 instead of bilinear). Moving a photo by half a pixel used to lose a third of its finest detail; now it keeps most of it, without halos around From 69a7637cf0c0ba0c3426b3ec76b643164c771ac4 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 11:21:39 -0400 Subject: [PATCH 2/5] PERF-SEARCH: the Text rule cache tests can fail rule_text_made lets the tests look without making the text; the Text rule results are compared with the fields read photo by photo (a copy is not looked up), not with the cache itself. index.rs names the two texts. --- crates/catalog/src/index.rs | 13 +++++++++++-- crates/catalog/src/tests_search_text.rs | 21 ++++++++++++++------- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/crates/catalog/src/index.rs b/crates/catalog/src/index.rs index 14d441a167..63f0e3f09e 100644 --- a/crates/catalog/src/index.rs +++ b/crates/catalog/src/index.rs @@ -1,12 +1,14 @@ //! Lookups derived from the catalog's own data, so questions asked once per photo of a big library -//! don't scan a list each time: which stack a photo is in, whether a regular album holds it. +//! don't scan a list each time: which stack a photo is in, whether a regular album holds it, the lower-cased text +//! the free-text search reads, and the text a smart album's Text rule reads (each made for every photo on first use). //! //! They are never saved (the on-disk format is unchanged). Each is built on first use from what //! the catalog holds, so a catalog read from a snapshot, replayed from the journal or cloned starts //! without them and builds them when asked. Once built, [`crate::Catalog::apply`] keeps them up to //! date: the ops that change stacks or album photos (`AddStack`, `RemoveStack`, `SetStack`, //! `AddAlbum`, `RemoveAlbum`, `SetAlbumPhotos`) update them as they apply, inverses and the -//! rollback of a failed batch included, as those are ops too. +//! rollback of a failed batch included, as those are ops too. The two texts follow every op that changes +//! a photo's fields, and the photo moving to another place in memory. use std::collections::{HashMap, HashSet}; use std::sync::OnceLock; @@ -262,4 +264,11 @@ impl Catalog { let t = m.get(&p.id)?; (t.at == addr(p)).then_some(&*t.text) } + + /// Whether the Text rules' text has been made (asking for it makes it, so a test cannot look with + /// [`Catalog::rule_text_of`]). + #[cfg(test)] + pub(crate) fn rule_text_made(&self) -> bool { + self.index.rule_text.get().is_some() + } } diff --git a/crates/catalog/src/tests_search_text.rs b/crates/catalog/src/tests_search_text.rs index 123e6d5692..987f0e7765 100644 --- a/crates/catalog/src/tests_search_text.rs +++ b/crates/catalog/src/tests_search_text.rs @@ -373,21 +373,27 @@ fn a_clone_builds_its_own() { assert_current(&c); } -/// The words of Text rules (not the search) read the same with the cache as without. +/// The words of Text rules (not the search) read the same with the cache as without: what the fields give when each +/// photo is read alone (a copy of a photo is not the catalog's own, so its text is not looked up), and what the +/// kept text gives. #[test] fn text_rules_match_as_the_fields_do() { let c = library(); let every_op = ["contains", "notContains", "is", "isNot", "startsWith", "endsWith", "isEmpty", "isNotEmpty"]; let values = ["", "ōsaka", "TRIP TO", "kyōto japan", "ana lima", "zürich", "img_0001.jpg", "black and white", "ς", "i̇stanbul", "png", "re: 10:30 meeting"]; - let before: Vec> = - every_op.iter().map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(p, &c)).count()).collect()).collect(); + assert!(!c.rule_text_made(), "nothing made the text yet"); let after: Vec> = every_op.iter().map(|op| values.iter().map(|v| c.count(&text_rule(op, v))).collect()).collect(); - assert_eq!(before, after); - assert!(c.photos().all(|p| c.rule_text_of(p).is_some()), "the first rule asked made the text"); + assert!(c.rule_text_made(), "the first rule asked made the text"); + let from_the_fields: Vec> = every_op + .iter() + .map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(&Photo::clone(p), &c)).count()).collect()) + .collect(); + assert_eq!(from_the_fields, after); + assert!(after.iter().flatten().any(|&n| n > 0), "the rules found something"); let again: Vec> = every_op.iter().map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(p, &c)).count()).collect()).collect(); - assert_eq!(before, again); + assert_eq!(after, again); } /// A smart album's count through the tally path (`album_contains`, one photo at a time) reads the @@ -399,8 +405,9 @@ fn a_smart_album_count_reads_the_kept_text() { album.smart = Some(Box::new(text_rule("contains", "ōsaka"))); c.apply(Op::AddAlbum { album }).unwrap(); let one_by_one = |c: &Catalog| c.photos().filter(|p| c.album_contains(AlbumId(1), p)).count(); + assert!(!c.rule_text_made(), "nothing made the text yet"); assert_eq!(one_by_one(&c), 1); - assert!(c.photos().all(|p| c.rule_text_of(p).is_some()), "counting made the text"); + assert!(c.rule_text_made(), "counting made the text"); let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone(); meta.title = "Ōsaka again".into(); c.apply(Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) }).unwrap(); From 9732607e617a011a2076995a921520c2ab66b38e Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 11:58:01 -0400 Subject: [PATCH 3/5] PERF-SEARCH: two comments say when the kept text is made and when it is used --- crates/catalog/src/index.rs | 2 +- crates/catalog/src/tests_search_text.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/catalog/src/index.rs b/crates/catalog/src/index.rs index 63f0e3f09e..6795b313dc 100644 --- a/crates/catalog/src/index.rs +++ b/crates/catalog/src/index.rs @@ -1,6 +1,6 @@ //! Lookups derived from the catalog's own data, so questions asked once per photo of a big library //! don't scan a list each time: which stack a photo is in, whether a regular album holds it, the lower-cased text -//! the free-text search reads, and the text a smart album's Text rule reads (each made for every photo on first use). +//! the free-text search reads, and the text a smart album's Text rule reads (each made for every photo the first time it is needed for every photo). //! //! They are never saved (the on-disk format is unchanged). Each is built on first use from what //! the catalog holds, so a catalog read from a snapshot, replayed from the journal or cloned starts diff --git a/crates/catalog/src/tests_search_text.rs b/crates/catalog/src/tests_search_text.rs index 987f0e7765..709529218b 100644 --- a/crates/catalog/src/tests_search_text.rs +++ b/crates/catalog/src/tests_search_text.rs @@ -374,7 +374,7 @@ fn a_clone_builds_its_own() { } /// The words of Text rules (not the search) read the same with the cache as without: what the fields give when each -/// photo is read alone (a copy of a photo is not the catalog's own, so its text is not looked up), and what the +/// photo is read alone (a copy of a photo is not the catalog's own, so the text kept for its id is not used), and what the /// kept text gives. #[test] fn text_rules_match_as_the_fields_do() { From ab21a4c8098516ae41602b1bfd12a532012b9967 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 14:54:32 -0400 Subject: [PATCH 4/5] Search: a word holding NUL is looked for inside one field, never across two --- crates/catalog/src/index.rs | 21 +++++++++++++++++++-- crates/catalog/src/query.rs | 12 +++++++++--- crates/catalog/src/tests_search_text.rs | 17 +++++++++++++++++ 3 files changed, 45 insertions(+), 5 deletions(-) diff --git a/crates/catalog/src/index.rs b/crates/catalog/src/index.rs index 6795b313dc..4db512354e 100644 --- a/crates/catalog/src/index.rs +++ b/crates/catalog/src/index.rs @@ -147,7 +147,8 @@ fn addr(p: &Photo) -> usize { /// What the free-text search looks through for one photo, lower-cased as `str::to_lowercase` does /// for each field alone: file name, title, caption, camera, lens, location, format, then each /// keyword, then the name of each person (a named face), separated by NUL. A search word may hold -/// white space (a quoted phrase) but never NUL, so it never runs over a field. +/// white space (a quoted phrase); one that holds NUL is read from the fields one by one +/// ([`PhotoText::field_contains`]), so no word runs over a field. pub(crate) struct PhotoText { /// The address of the photo this was made from ([`addr`]). at: usize, @@ -155,8 +156,13 @@ pub(crate) struct PhotoText { } impl PhotoText { + /// The fields of `p` that the text joins before its keywords and people. + fn fields(p: &Photo) -> [&String; 7] { + [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format] + } + pub(crate) fn of(p: &Photo) -> PhotoText { - let fields = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]; + let fields = Self::fields(p); let people = p.people(); // (exact for ASCII, which most text is: the box takes the buffer without copying it) let len = fields @@ -186,6 +192,17 @@ impl PhotoText { self.text.contains(t) } + /// [`PhotoText::contains`] read from `p`'s fields one by one, for a word that holds NUL: the joined text can't tell + /// the NUL that separates two fields from one inside a field, and a word never runs over two fields. + pub(crate) fn field_contains(p: &Photo, t: &str) -> bool { + Self::fields(p) + .into_iter() + .map(String::as_str) + .chain(p.meta.keywords.iter().map(String::as_str)) + .chain(p.people()) + .any(|f| f.to_lowercase().contains(t)) + } + #[cfg(test)] pub(crate) fn text(&self) -> &str { &self.text diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index e102c5c0ba..26325740e0 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -221,11 +221,11 @@ fn token_matches(p: &Photo, t: &str, hay: &Hay) -> bool { "name" | "file" => p.file_name.to_lowercase().contains(val), // Not a known field: the colon is part of a plain word ("10:30", "Re:"), its value unquoted // (`re:"a b"` is the text `re:a b`). - _ if val.len() != quoted.len() => hay.text().contains(&format!("{field}:{val}")), - _ => hay.text().contains(t), + _ if val.len() != quoted.len() => hay.contains(&format!("{field}:{val}")), + _ => hay.contains(t), }; } - hay.text().contains(unquote(t)) + hay.contains(unquote(t)) } /// A photo's lower-cased text for the free-text search: the one the catalog keeps when `p` is its @@ -245,6 +245,12 @@ impl Hay<'_> { None => self.own.get_or_init(|| crate::index::PhotoText::of(self.p)), } } + + /// Whether `t` (lower-cased) is in one field of the photo ([`crate::index::PhotoText::contains`]): a word with NUL + /// is read from the fields themselves, for the joined text separates them with NUL. + fn contains(&self, t: &str) -> bool { + if t.contains('\0') { crate::index::PhotoText::field_contains(self.p, t) } else { self.text().contains(t) } + } } /// Whether `p` has a named face region called `name` (case-insensitive). diff --git a/crates/catalog/src/tests_search_text.rs b/crates/catalog/src/tests_search_text.rs index 709529218b..632f77e70a 100644 --- a/crates/catalog/src/tests_search_text.rs +++ b/crates/catalog/src/tests_search_text.rs @@ -434,3 +434,20 @@ fn the_kept_text_holds_the_people_and_a_phrase_stays_in_one_field() { assert_eq!(found(&c, "ana"), 0, "and the old name is gone"); assert_current(&c); } + +/// A word that holds NUL (a filter's text can) is looked for inside one field, as before the cache: it never matches across +/// the NUL the cache puts between two fields, and still matches a field that holds NUL itself. +#[test] +fn a_word_holding_nul_never_runs_over_two_fields() { + let mut c = Catalog::new(); + let mut p = photo(1, "a"); + p.meta.title = "b".into(); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let mut p = photo(2, "c\0d"); + p.meta.title = "e".into(); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + for text in ["a\0b", "\"a\0b\"", "b\0", "\0e"] { + assert_eq!(shown(&c, text), Vec::::new(), "{text:?}"); + } + assert_eq!(shown(&c, "c\0d"), vec![2], "a field's own NUL is still found"); +} From 315cd357a90b4b501eb7d7c98d77bea4f88172d8 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 19 Nov 2026 10:36:31 -0500 Subject: [PATCH 5/5] catalog: repair drops the derived lookups before it copies photos `repair` copies every photo others hold (`Arc::make_mut`) without reporting a change on a sound catalog, so the kept search and Text-rule texts stayed keyed to the address a retained photo still has, and read that photo's old text after it was edited on its own. Drop the lookups up front (they are built again when asked), which also covers any copy a later change to `repair` adds. Co-Authored-By: Claude --- crates/catalog/src/index.rs | 3 ++- crates/catalog/src/lib.rs | 9 ++++++--- crates/catalog/src/tests_search_text.rs | 21 +++++++++++++++++++++ 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/catalog/src/index.rs b/crates/catalog/src/index.rs index 4db512354e..b40c4a698b 100644 --- a/crates/catalog/src/index.rs +++ b/crates/catalog/src/index.rs @@ -134,7 +134,8 @@ impl std::hash::Hasher for IdHasher { /// Where `p` is in memory. The contract of the kept texts: a text is used only for the photo at the /// address it was made for. The catalog's own photos (`Arc` contents) stay where they are -/// until `Arc::make_mut` copies one that others hold, which `photo_mut` reports ([`Indexes::text_moved`]); +/// until `Arc::make_mut` copies one that others hold, which `photo_mut` reports ([`Indexes::text_moved`]; `repair` +/// copies them in bulk and drops every lookup instead); /// every op that changes a searched field makes the text again ([`Indexes::text_changed`]). A copy /// of a photo (a candidate tried with other values) is at another address, so it is read from its /// own fields, never from a text kept for the photo with its id. Only ids and addresses are diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 55b1e2d94f..605aeb4710 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -1231,6 +1231,10 @@ impl Catalog { /// wrote). pub fn repair(&mut self) -> Vec { let mut changed = Vec::new(); + // Photos others hold are copied below (`Arc::make_mut`), which moves them in memory and strands the text kept + // for their address ([`index::Indexes`]), and stacks and albums change outside `apply`: nothing derived is + // kept across a repair, and the lookups are built again when asked. + self.index = index::Indexes::default(); // Segmentation grids shared by the snapshot this was read from (issue #2154): each // reference takes its grid's data, and the table is not kept — a live catalog always // stores the data inline, so masks render and serialize without the snapshot's table. @@ -1341,9 +1345,8 @@ impl Catalog { self.next_stack = self.next_stack.max(stack); } if !changed.is_empty() { - // stacks and albums changed outside `apply`: the lookups are built again when asked - self.index = index::Indexes::default(); - // (and what was worked out from the albums, the guard of [`Self::keeps_written_order`] too) + // stacks and albums changed outside `apply`: what was worked out from the albums is made again (the guard of + // [`Self::keeps_written_order`] too) self.plans = PlansMemo::default(); } changed diff --git a/crates/catalog/src/tests_search_text.rs b/crates/catalog/src/tests_search_text.rs index 632f77e70a..2c9ae6c668 100644 --- a/crates/catalog/src/tests_search_text.rs +++ b/crates/catalog/src/tests_search_text.rs @@ -373,6 +373,27 @@ fn a_clone_builds_its_own() { assert_current(&c); } +/// `repair` copies the photos others hold (`Arc::make_mut`) without reporting a change, so the cache would +/// still keep a text for the address the retained photo has. The retained photo, changed on its own, is +/// read from its fields, never from the text kept for the photo with its id. +#[test] +fn repair_keeps_no_text_for_a_photo_it_copied() { + let mut c = library(); + warm(&c); + let mut held = c.photo(PhotoId(1)).unwrap().clone(); + assert!(c.repair().is_empty(), "a sound catalog"); + assert!(!std::ptr::eq(&*held, &**c.photo(PhotoId(1)).unwrap()), "repair copied the photo"); + std::sync::Arc::make_mut(&mut held).meta.title = "Trip to Nara".into(); + let nara = Filter { text: "nara".into(), ..Default::default() }; + let osaka = Filter { text: "ōsaka".into(), ..Default::default() }; + assert!(nara.matches(&held, &c), "the retained photo's own title"); + assert!(!osaka.matches(&held, &c), "not the title it had"); + assert!(text_rule("contains", "nara").matches(&held, &c), "the Text rule reads the retained photo's own title"); + assert!(!text_rule("contains", "ōsaka").matches(&held, &c)); + warm(&c); + assert_eq!((found(&c, "ōsaka"), found(&c, "nara")), (1, 0)); +} + /// The words of Text rules (not the search) read the same with the cache as without: what the fields give when each /// photo is read alone (a copy of a photo is not the catalog's own, so the text kept for its id is not used), and what the /// kept text gives.