From 6b3984901cab3af030ddc4ad8a451f9f0094f03f Mon Sep 17 00:00:00 2001 From: Brian L Wong Date: Wed, 2 Dec 2026 09:28:29 -0500 Subject: [PATCH 001/244] CT-G2: Advanced Search "any of" several keywords is any in a one-group search A query of one group that must match all its conditions (the default) put the picked keywords into the filter's own keyword list, with the chosen any/all, and also added one `keywords contains ` rule per keyword to the rule set that is ANDed with it. So "any of travel, ocean" listed only photos with every keyword. The extra rules are gone: the keywords are said once, by the filter's list, which already carries the operator. Every other field keeps its meaning (the rules for the other categories, the words, people, collection and face count are untouched), and the other query shapes (match any/none/not all, further groups) never added the rules. Test: keyword_any_and_all_hold_in_every_query_shape runs any and all, alone and with another condition, through the one-group form and the rule-group form and the match any/none forms (fails without the change: [3] instead of [1, 2, 3, 4]). Version guard: nothing stored changes (a query is lowered to a filter at run time); no VERSION bump or NEWEST_FIELDS change. Manual: none (the Advanced Search page already says a ticked list matches any of its values; the behaviour now matches it) Co-Authored-By: Claude Sonnet 5.5 --- crates/catalog/src/advanced_search.rs | 56 +++++++++++++++---- .../2026-12-02-advanced-search-any-keyword.md | 3 + .../2026-12-02-advanced-search-any-keyword.md | 2 + 3 files changed, 51 insertions(+), 10 deletions(-) create mode 100644 docs/changelog/unreleased/2026-12-02-advanced-search-any-keyword.md create mode 100644 docs/whats-new/2026-12-02-advanced-search-any-keyword.md diff --git a/crates/catalog/src/advanced_search.rs b/crates/catalog/src/advanced_search.rs index ec53888818..5876f8d3ed 100644 --- a/crates/catalog/src/advanced_search.rs +++ b/crates/catalog/src/advanced_search.rs @@ -509,7 +509,7 @@ impl AdvancedSearch { } } out.extend(self.pick_rules()); - out.extend(self.field_rules(false)?.into_iter().map(rule_of)); + out.extend(self.field_rules()?.into_iter().map(rule_of)); if let Some(f) = &self.faces { if let Some(spec) = f.count.as_deref().map(str::trim).filter(|c| !c.is_empty()) { let spec = crate::query::parse_face_spec(spec).map_err(|e| format!("faces count: {e}"))?; @@ -526,9 +526,9 @@ impl AdvancedSearch { } /// The categories' field conditions as `{"field", "op", "value"}` triples: everything but the words, the - /// collection, the people and the face count, and the keywords only when `keywords` (a group of one search - /// whose conditions all match lists them here, as it always has). - fn field_rules(&self, keywords: bool) -> Result, String> { + /// keywords, the collection, the people and the face count (those are filter fields or conditions of their own, + /// so the keywords' any / all is said once). + fn field_rules(&self) -> Result, String> { let mut rules: Vec = Vec::new(); if let Some(f) = &self.file && !f.is_empty() @@ -545,11 +545,6 @@ impl AdvancedSearch { if let Some(rule) = text_rule("folder", &f.folder) { rules.push(rule); } - if keywords && let Some(list) = trimmed(&f.keywords) { - for k in list { - rules.push(json!({"field": "keywords", "op": "contains", "value": k})); - } - } } if let Some(p) = &self.properties && !p.is_empty() @@ -698,7 +693,7 @@ impl AdvancedSearch { } fn all_of_one_group(&self) -> Result { - let rules = self.field_rules(true)?; + let rules = self.field_rules()?; let mut filter = Filter { text: self.words.trim().to_string(), ..Filter::default() }; if let Some(f) = &self.file && !f.is_empty() @@ -1209,6 +1204,47 @@ mod tests { assert_eq!(serde_json::to_value(&p).unwrap()["properties"]["fileSizeMb"]["min"], json!(1.0)); } + /// Picked keywords combine as their own any / all says in every shape a query can take: the one-group "all" + /// form (the filter's own keyword list) and the forms lowered to rule groups, with or without another condition + /// in the group. + #[test] + fn keyword_any_and_all_hold_in_every_query_shape() { + let mut c = Catalog::new(); + let mut add = |id: u64, keywords: &[&str], rating: u8| { + let mut p = Photo::new(PhotoId(id), Source::Demo { scene: 1 }, &format!("k{id}.jpg"), "JPEG", 60, 40, "2026-05-01T10:00:00"); + p.rating = rating; + p.meta.keywords = keywords.iter().map(|k| k.to_string()).collect(); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + }; + add(1, &["travel"], 4); + add(2, &["ocean"], 4); + add(3, &["travel", "ocean"], 4); + add(4, &["travel"], 1); + add(5, &[], 4); + let ids = |q: &AdvancedSearch| -> Vec { matches(&c, q).into_iter().map(|p| p.0).collect() }; + let keywords = |op: MatchOp| FileCategory { keywords: vec!["travel".into(), "ocean".into()], keyword_op: op, ..Default::default() }; + // a second group that every photo meets: the query is lowered to rule groups instead + let everything = AdvancedSearch { properties: Some(PropertiesCategory { rating: Some(0), ..Default::default() }), ..q() }; + let rated = PropertiesCategory { rating: Some(3), rating_op: RatingOp::AtLeast, ..Default::default() }; + for (shape, with_group) in [("one group", false), ("one group and a second", true)] { + let query = |op: MatchOp, properties: Option| AdvancedSearch { + file: Some(keywords(op)), + properties, + groups: if with_group { vec![everything.clone()] } else { Vec::new() }, + ..q() + }; + assert_eq!(ids(&query(MatchOp::Any, None)), vec![1, 2, 3, 4], "{shape}: any of the keywords"); + assert_eq!(ids(&query(MatchOp::All, None)), vec![3], "{shape}: all of the keywords"); + assert_eq!(ids(&query(MatchOp::Any, Some(rated.clone()))), vec![1, 2, 3], "{shape}: any of the keywords, and rated"); + assert_eq!(ids(&query(MatchOp::All, Some(rated.clone()))), vec![3], "{shape}: all of the keywords, and rated"); + } + // the group's own match still decides how the keywords meet the other conditions + let either = AdvancedSearch { mode: SearchMatch::Any, file: Some(keywords(MatchOp::Any)), properties: Some(rated.clone()), ..q() }; + assert_eq!(ids(&either), vec![1, 2, 3, 4, 5], "match any: a keyword, or rated"); + let neither = AdvancedSearch { mode: SearchMatch::None, ..either }; + assert!(ids(&neither).is_empty(), "match none: no keyword and not rated"); + } + #[test] fn unsupported_audio_video_conditions_are_rejected_actionably() { let mut query = q(); diff --git a/docs/changelog/unreleased/2026-12-02-advanced-search-any-keyword.md b/docs/changelog/unreleased/2026-12-02-advanced-search-any-keyword.md new file mode 100644 index 0000000000..75830cf5c1 --- /dev/null +++ b/docs/changelog/unreleased/2026-12-02-advanced-search-any-keyword.md @@ -0,0 +1,3 @@ +## Fixes + +- **Advanced Search, any of several keywords:** a search of one group that must match all its conditions treated "any of" the picked keywords as "all of" them; it now lists the photos with at least one keyword. diff --git a/docs/whats-new/2026-12-02-advanced-search-any-keyword.md b/docs/whats-new/2026-12-02-advanced-search-any-keyword.md new file mode 100644 index 0000000000..478d4bd4e8 --- /dev/null +++ b/docs/whats-new/2026-12-02-advanced-search-any-keyword.md @@ -0,0 +1,2 @@ +### Advanced Search: any of the keywords +- In Advanced Search with one group set to match all conditions, picking two or more keywords with "any" now finds the photos that have at least one of them. It used to find only the photos that had every one, as "all" does. From 5a6d7dc7e3a190c80ec8741bef11ed3397ad4b97 Mon Sep 17 00:00:00 2001 From: Brian L Wong Date: Wed, 2 Dec 2026 09:35:13 -0500 Subject: [PATCH 002/244] CT-G7: an On This Day day the filter cannot read matches no photo Filter::capture_month_day that month_day_of could not parse (`garbage`, `02/29`, `feb-29`, an empty string) became None, which skipped the whole month/day block, `capture_before_year` with it, so the filter matched every photo while its description still said "captured on junk". Only the engine's commands checked the day; a smart album's stored filter, a saved view, another build or an MCP argument reached the matcher unchecked. Now one reading of the day lives in the catalog: valid_month_day (two digits, a hyphen, two digits, a day that exists in the leap year 2000 via chrono, so 02-29 is valid and 02-30 and 13-01 are not) and Filter::memories_problem, which also refuses a before-year outside 1..=9999 and a before-year with no day (the same three rules the engine's check_memories_fields applies). A filter with a problem matches no photo, in queries, counts and smart albums. A photo's own date is checked as before. Test: an_unreadable_memories_day_matches_no_photo (fails without the change: "garbage" matched every photo): valid days at both ends of the calendar and 02-29, one past each end and malformed text, before-year alone, out of range and at its boundary, and a smart album carrying a junk day. Version guard: no stored field or its reading changes for a valid value; no VERSION bump. Engine follow-up, not done here (engine not built): valid_memories_day and check_memories_fields in cmd/library.rs can delegate to lcc_catalog::valid_month_day and Filter::memories_problem so the rule has one source. Manual: none, no user-visible change (a day the commands accept is read as before) Co-Authored-By: Claude Sonnet 5.5 --- crates/catalog/src/lib.rs | 2 +- crates/catalog/src/query.rs | 50 +++++++++++++++++++++++++++++++++---- crates/catalog/src/tests.rs | 43 +++++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+), 6 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 8d5f1c1800..9b301759ed 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -66,7 +66,7 @@ use lcc_develop::DevelopSettings; pub use local::{DEFAULT_FORGET_DAYS, ForgetPlan, LocalRecords, folder_of}; pub use lock::{LibraryLock, LockError, LockOwner}; pub use model::*; -pub use query::{DateGroup, Filter, MatchOp, Person, RatingOp, Sort, SortKey, Tally, date_groups_from, mix64}; +pub use query::{DateGroup, Filter, MatchOp, Person, RatingOp, Sort, SortKey, Tally, date_groups_from, mix64, valid_month_day}; pub use remote::{PreviewEntry, RemoteIdentity, RemoteKey, RemoteTable, SyncState}; pub use rules::{Match, Rule, RuleSet}; use serde::{Deserialize, Serialize}; diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index f845157360..58f80feab4 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -650,21 +650,58 @@ pub(crate) struct Prepared { only: Option>, /// A pass over many photos: the catalog's kept search text is made when missing. whole: bool, - /// [`Filter::capture_month_day`] as numbers (month, day); `None` without it. + /// [`Filter::capture_month_day`] as numbers (month, day); `None` without it, or when the Memories fields + /// can't be read ([`Prepared::memories_unreadable`]). month_day: Option<(u32, u32)>, + /// The Memories fields hold something that can't be read ([`Filter::memories_problem`]): no photo matches, + /// rather than the filter dropping what it can't read and matching every one. + memories_unreadable: bool, } impl Prepared { /// What every filter has, whatever the pass: the library folder and the calendar day asked for. fn base(filter: &Filter) -> Self { - Prepared { root: filter.library_root(), only: None, whole: false, month_day: filter.capture_month_day.as_deref().and_then(month_day_of) } + let memories_unreadable = filter.memories_problem().is_some(); + let month_day = filter.capture_month_day.as_deref().filter(|_| !memories_unreadable).and_then(month_day_of); + Prepared { root: filter.library_root(), only: None, whole: false, month_day, memories_unreadable } } } -/// `MM-DD` as (month, day) when it is well-formed (the callers that take it from a command check it first). +/// Whether `day` is a calendar day written `MM-DD`: two digits, a hyphen, two digits, naming a day that exists in a +/// leap year (so `02-29` is one, `02-30` and `13-01` are not). The one reading of the Memories day: the matcher, the +/// catalog's own check ([`Filter::memories_problem`]) and the commands that take one all use it. +pub fn valid_month_day(day: &str) -> bool { + month_day_of(day).is_some() +} + +/// `MM-DD` as (month, day) when it is a calendar day ([`valid_month_day`]). fn month_day_of(day: &str) -> Option<(u32, u32)> { - let (m, d) = day.split_once('-')?; - Some((m.parse().ok()?, d.parse().ok()?)) + let b = day.as_bytes(); + if b.len() != 5 || b.get(2) != Some(&b'-') || !b.iter().enumerate().all(|(i, c)| i == 2 || c.is_ascii_digit()) { + return None; + } + let month = day.get(..2)?.parse::().ok()?; + let date = day.get(3..)?.parse::().ok()?; + chrono::NaiveDate::from_ymd_opt(2000, month, date).map(|_| (month, date)) +} + +impl Filter { + /// What is wrong with the Memories (On This Day) fields, if anything: a day that is not a calendar day + /// (`MM-DD`, February 29 included), a year outside 1 to 9999, or a year without a day. A filter with such a + /// problem matches no photo (a day it can't read must not widen the view to every photo); the engine's commands + /// refuse it with the same words. + pub fn memories_problem(&self) -> Option<&'static str> { + if self.capture_month_day.as_deref().is_some_and(|day| !valid_month_day(day)) { + return Some("captureMonthDay must be a valid MM-DD date"); + } + if self.capture_before_year.is_some_and(|year| !(1..=9999).contains(&year)) { + return Some("captureBeforeYear must be a year from 1 to 9999"); + } + if self.capture_before_year.is_some() && self.capture_month_day.is_none() { + return Some("captureBeforeYear needs captureMonthDay"); + } + None + } } /// A photo's place in the shuffle for `seed`. @@ -1258,6 +1295,9 @@ impl Filter { // strict `YYYY-MM-DD` of ASCII digits (so nothing is allocated per photo, and chrono's // lenient `%Y-%m-%d`, which also reads `+2025-1-3`, lets no oddity through); malformed and // non-ASCII metadata simply won't match. + if prepared.memories_unreadable { + return false; + } if let Some((want_month, want_day)) = prepared.month_day { let Some(c) = p.captured.as_deref().and_then(|c| c.get(..10)) else { return false }; let b = c.as_bytes(); diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index ebf09c3b44..6843ddd6a9 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -64,6 +64,49 @@ fn memories_match_the_calendar_day_only_in_past_years() { assert!(!got.contains(&partial), "a month-only date is not a calendar-day match"); } +/// A day the filter cannot read, or a before-year without a day, matches no photo (it used to drop the whole day +/// block and match every one); the days it can read still find their photos, February 29 included. +#[test] +fn an_unreadable_memories_day_matches_no_photo() { + let mut c = Catalog::new(); + let leap = photo(&mut c, "leap.jpg", "2024-02-29T10:00:00"); + let eve = photo(&mut c, "eve.jpg", "2026-12-31T23:59:59"); + let day1 = photo(&mut c, "day1.jpg", "2027-01-01T00:00:00"); + let day = |s: &str| Filter { capture_month_day: Some(s.to_string()), ..Default::default() }; + let sort = Sort::default(); + // readable days, at the ends of the calendar + assert_eq!(c.query(&day("02-29"), &sort), vec![leap]); + assert_eq!(c.query(&day("12-31"), &sort), vec![eve]); + assert_eq!(c.query(&day("01-01"), &sort), vec![day1]); + assert!(valid_month_day("02-29") && valid_month_day("01-01") && valid_month_day("12-31")); + // one past each end, impossible days, and text that is not `MM-DD` + for bad in + ["02-30", "04-31", "00-10", "13-01", "01-00", "01-32", "garbage", "02/29", "feb-29", "", "2-5", "02-9", "+2-+9", " 02-29", "02-29 ", "002-29"] + { + assert!(!valid_month_day(bad), "{bad:?} is not a day"); + assert!(c.query(&day(bad), &sort).is_empty(), "{bad:?} matches nothing"); + assert_eq!(c.count(&day(bad)), 0, "{bad:?} counts nothing"); + let with_year = Filter { capture_before_year: Some(2030), ..day(bad) }; + assert!(c.query(&with_year, &sort).is_empty(), "{bad:?} before 2030 matches nothing"); + } + // a before-year says "before" only for a day; alone, or out of the years a date has, it matches nothing + let year = |y: i32| Filter { capture_before_year: Some(y), ..Default::default() }; + assert!(c.query(&year(2020), &sort).is_empty()); + assert!(c.query(&year(2030), &sort).is_empty()); + for y in [0, -1, 10_000] { + assert!(c.query(&Filter { capture_before_year: Some(y), ..day("12-31") }, &sort).is_empty(), "year {y}"); + } + // the year is strict: the photo's own year is not before it + assert_eq!(c.query(&Filter { capture_before_year: Some(2027), ..day("12-31") }, &sort), vec![eve]); + assert!(c.query(&Filter { capture_before_year: Some(2026), ..day("12-31") }, &sort).is_empty()); + // a smart album carrying such a filter lists nothing as well + let id = c.alloc_album_id(); + let smart = Album { smart: Some(Box::new(day("garbage"))), ..Album::new(id, "Junk day") }; + c.apply(Op::AddAlbum { album: smart }).unwrap(); + assert!(c.album_photos(id).is_empty()); + assert_eq!(c.album_count(id), 0); +} + #[test] fn date_token_matches_time_part_case_insensitively() { let mut c = Catalog::new(); From 979d6780298ed1396124f03159b171377ef491cf Mon Sep 17 00:00:00 2001 From: Brian L Wong Date: Wed, 2 Dec 2026 09:43:15 -0500 Subject: [PATCH 003/244] CT-G12: a Quality scan retires the kept Quality sort order Op::SetAnalysis (what an Image Quality scan writes) bumped neither list of the sort cache, and the Quality key was not "only structural", so in a library of 2,000 photos or more the order cached before the scan was served until an unrelated rating, develop or content edit, or a restart: scored photos stayed among the unscored ones, and follow() and query() disagreed. SetAnalysis now bumps a new `quality` epoch. A kept Quality order is valid only while the structural and quality epochs match; it no longer retires on a rating, edit-time or size change (it reads none of them), and the rating, edit-date, file-size, file-name and Custom orders are not retired by a scan. Same defect family: Sort::order (which places one new or edited photo among a listed order, in follow()) compared Quality scores as raw floats while the sort a query runs (sort_photos) reads them to a thousandth, clamped to 0..100. Two photos 0.0004 apart tied in one and not in the other. Both now use one quality_rank function (the sort_photos reading, unchanged), so they agree. Tests: a_quality_scan_retires_the_kept_quality_order (2,100 photos, kept order built both ways, five scored, one rescored, one cleared; fails without the change: the kept order starts with unscored photos) and the_quality_order_of_one_photo_agrees_with_the_sort_of_a_query (fails without the change: photos within a thousandth order differently); Quality and Custom added to the sort-cache parity test's keys, with scores and SetAnalysis ops in its fixture. Existing tests unchanged. Version guard: nothing stored changes; no VERSION bump or NEWEST_FIELDS change. Manual: none (no page describes the kept order) Co-Authored-By: Claude Sonnet 5.5 --- crates/catalog/src/lib.rs | 2 + crates/catalog/src/query.rs | 54 +++++++++-------- crates/catalog/src/tests_quality.rs | 22 +++++++ crates/catalog/src/tests_sort_cache.rs | 59 ++++++++++++++++++- .../2026-12-02-quality-sort-after-a-scan.md | 3 + .../2026-12-02-quality-sort-after-a-scan.md | 2 + 6 files changed, 117 insertions(+), 25 deletions(-) create mode 100644 docs/changelog/unreleased/2026-12-02-quality-sort-after-a-scan.md create mode 100644 docs/whats-new/2026-12-02-quality-sort-after-a-scan.md diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 9b301759ed..227a332040 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -1159,6 +1159,8 @@ impl Catalog { self.sort_cache.bump(true) } Op::SetRating { .. } | Op::SetDevelop { .. } | Op::SetContent { .. } => self.sort_cache.bump(false), + // (a scan scores photos by the thousand: the Quality order only, not the rating, edit-time or size orders) + Op::SetAnalysis { .. } => self.sort_cache.bump_quality(), _ => {} } Ok(match op { diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index 58f80feab4..7147368594 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -210,17 +210,7 @@ impl Sort { SortKey::Rating => a.rating.cmp(&b.rating), SortKey::FileSize => a.file_size.cmp(&b.file_size), SortKey::Random => shuffle_rank(self.seed, a.id).cmp(&shuffle_rank(self.seed, b.id)), - SortKey::Quality => { - let qa = a.analysis.and_then(|x| x.quality).map(|q| q.score); - let qb = b.analysis.and_then(|x| x.quality).map(|q| q.score); - match (qa, qb) { - (Some(x), Some(y)) => x.total_cmp(&y), - (None, None) => std::cmp::Ordering::Equal, - // unscanned photos have no place among scores: first when ascending - (None, Some(_)) => std::cmp::Ordering::Less, - (Some(_), None) => std::cmp::Ordering::Greater, - } - } + SortKey::Quality => quality_rank(a).cmp(&quality_rank(b)), } .then_with(|| if self.key.ties_by_name() { cmp_name(&a.file_name, &b.file_name) } else { std::cmp::Ordering::Equal }) .then(a.id.cmp(&b.id)); @@ -228,6 +218,18 @@ impl Sort { } } +/// Where a photo stands among the Image Quality scores: unscanned photos rank below every score (first ascending, +/// last descending); the score is read to a thousandth (the stored score's precision) and one higher, so a measured +/// 0 stays above "no score at all"; a score outside 0..100 counts as the nearest end, a score that is not a number +/// as none. The one reading of a Quality sort: [`Sort::order`] and the sort a query runs both use it, so a photo put +/// among a listed order lands where a fresh sort would put it. +fn quality_rank(p: &Photo) -> u64 { + match p.analysis.and_then(|a| a.quality) { + Some(q) if q.score.is_finite() => (q.score.clamp(0.0, 100.0) * 1_000.0).round() as u64 + 1, + _ => 0, + } +} + impl Default for Sort { /// Capture date, oldest first: Lightroom Classic's default sort, in one grid without date sections as its Grid /// (the fork's: grouping is a choice in the Sort menu). @@ -309,6 +311,7 @@ pub(crate) struct Sorted { seed: u64, structural: u64, other: u64, + quality: u64, len: usize, /// Photo ids by rank. order: Vec, @@ -328,6 +331,8 @@ pub(crate) struct SortCache { structural: u64, /// Any other sort key changed (rating, edit time, file size). other: u64, + /// A photo's Image Quality scan changed (the Quality order reads nothing else of a photo). + quality: u64, entries: std::sync::Mutex>>, } @@ -362,13 +367,19 @@ impl SortCache { } } + /// The Image Quality scans changed: the kept Quality order is retired, the other kept orders are not. + pub(crate) fn bump_quality(&mut self) { + self.quality = self.quality.wrapping_add(1); + } + fn valid(&self, e: &Sorted, key: SortKey, seed: u64, len: usize) -> bool { - let only_structural = matches!(key, SortKey::CaptureDate | SortKey::ImportDate | SortKey::Random); - e.key == key - && (key != SortKey::Random || e.seed == seed) - && e.len == len - && e.structural == self.structural - && (only_structural || e.other == self.other) + // what each key's order reads, beyond which photos exist, their capture times and file names (`structural`) + let current = match key { + SortKey::CaptureDate | SortKey::ImportDate | SortKey::Random => true, + SortKey::Quality => e.quality == self.quality, + SortKey::EditDate | SortKey::FileName | SortKey::Rating | SortKey::FileSize | SortKey::Custom => e.other == self.other, + }; + e.key == key && (key != SortKey::Random || e.seed == seed) && e.len == len && e.structural == self.structural && current } /// The order of `all` (the catalog's photos in id order) by `sort`, built when missing. `None` @@ -396,6 +407,7 @@ impl SortCache { seed: sort.seed, structural: self.structural, other: self.other, + quality: self.quality, len: all.len(), order, rank, @@ -488,13 +500,7 @@ fn sort_photos<'a>(v: Vec<&'a Photo>, sort: &Sort) -> Vec { SortKey::Rating => (none, none, |p, _| u64::from(p.rating)), SortKey::FileSize => (none, none, |p, _| p.file_size), SortKey::Random => (none, none, |p, seed| shuffle_rank(seed, p.id)), - // Unscanned photos rank below every score (first ascending, last descending), as - // `Sort::order` puts them; the score is kept to a thousandth (the stored score's - // precision) and one higher, so a measured 0 stays above "no score at all". - SortKey::Quality => (none, none, |p, _| match p.analysis.and_then(|a| a.quality) { - Some(q) if q.score.is_finite() => (q.score.clamp(0.0, 100.0) * 1_000.0).round() as u64 + 1, - _ => 0, - }), + SortKey::Quality => (none, none, |p, _| quality_rank(p)), SortKey::FileName => { let mut keyed: Vec<(String, u64)> = v.into_iter().map(|p| (p.file_name.to_lowercase(), p.id.0)).collect(); keyed.sort_unstable_by(|a, b| { diff --git a/crates/catalog/src/tests_quality.rs b/crates/catalog/src/tests_quality.rs index 34f31b0c72..60afab789f 100644 --- a/crates/catalog/src/tests_quality.rs +++ b/crates/catalog/src/tests_quality.rs @@ -172,3 +172,25 @@ fn the_rule_fields_read_the_stored_scan() { assert_eq!(rules::field_group(field), Some("Image Quality"), "{field}"); } } + +/// `Sort::order` (which places one new or edited photo among a listed order) and the sort a query runs put photos in +/// the same order by Quality: unscanned first ascending; scores read to a thousandth, so two within it tie and go by +/// file name; a score outside 0..100 is the nearest end (a score that is not a number is refused when stored). +#[test] +fn the_quality_order_of_one_photo_agrees_with_the_sort_of_a_query() { + let mut c = Catalog::new(); + let scores = [Some(50.0001), Some(50.0004), Some(50.0006), Some(50.0), None, None, Some(150.0), Some(100.0), Some(-5.0), Some(0.0), Some(0.0004)]; + for (i, score) in scores.into_iter().enumerate() { + // names run against the ids, so a tie decided by the name differs from one decided by the id + let mut p = photo(i as u64 + 1, score.map(|s| QualityScan { score: s, ..Default::default() })); + p.file_name = format!("IMG_{:04}.jpg", 100 - i); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + for ascending in [true, false] { + let sort = Sort { key: SortKey::Quality, ascending, ..Default::default() }; + let mut by_order: Vec<&Photo> = c.photos().map(|p| &**p).collect(); + by_order.sort_by(|a, b| sort.order(a, b)); + let by_order: Vec = by_order.into_iter().map(|p| p.id).collect(); + assert_eq!(by_order, c.query(&Filter::default(), &sort), "ascending={ascending}"); + } +} diff --git a/crates/catalog/src/tests_sort_cache.rs b/crates/catalog/src/tests_sort_cache.rs index fc0e644468..137e5a5110 100644 --- a/crates/catalog/src/tests_sort_cache.rs +++ b/crates/catalog/src/tests_sort_cache.rs @@ -23,11 +23,26 @@ fn photo(c: &mut Catalog, i: u64) -> Photo { p.rating = (i % 6) as u8; p.file_size = (i * 31) % 1000; p.deleted = i.is_multiple_of(13); + // every fourth photo is unscanned; the scores tie in places and differ by less than a thousandth in others + p.analysis = (!i.is_multiple_of(4)).then(|| Analysis { + quality: Some(QualityScan { score: ((i * 7919) % 500) as f32 / 5.0 + (i % 3) as f32 * 0.0004, ..Default::default() }), + ..Default::default() + }); p } fn sorts() -> Vec { - let keys = [SortKey::CaptureDate, SortKey::ImportDate, SortKey::EditDate, SortKey::FileName, SortKey::Rating, SortKey::FileSize, SortKey::Random]; + let keys = [ + SortKey::CaptureDate, + SortKey::ImportDate, + SortKey::EditDate, + SortKey::FileName, + SortKey::Rating, + SortKey::FileSize, + SortKey::Random, + SortKey::Quality, + SortKey::Custom, + ]; keys.iter().flat_map(|k| [true, false].map(|asc| Sort { key: *k, ascending: asc, seed: 7, ..Default::default() })).collect() } @@ -78,6 +93,14 @@ fn kept_orders_match_a_fresh_sort_across_ops() { preview_checked: String::new(), }, ), + ( + "analysis", + Op::SetAnalysis { + id: ids[14], + analysis: Some(Analysis { quality: Some(QualityScan { score: 99.9, ..Default::default() }), ..Default::default() }), + }, + ), + ("analysis cleared", Op::SetAnalysis { id: ids[15], analysis: None }), ("remove", Op::RemovePhoto { id: ids[10] }), ("deleted", Op::SetDeleted { id: ids[11], deleted: true }), ("batch", Op::Batch { ops: vec![Op::SetRating { id: ids[12], rating: 0 }, Op::SetCaptured { id: ids[13], captured: None }] }), @@ -94,3 +117,37 @@ fn kept_orders_match_a_fresh_sort_across_ops() { // a clone starts without kept orders and agrees too check(&c.clone(), "clone"); } + +/// An Image Quality scan writes scores with `SetAnalysis`: a Quality order kept before it is not served after it, in +/// either direction, though no other sort key changed; and the orders of the other keys are not given up for it. +#[test] +fn a_quality_scan_retires_the_kept_quality_order() { + let mut c = Catalog::new(); + for i in 0..2100 { + let mut p = photo(&mut c, i); + p.analysis = None; + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let f = Filter::default(); + let ids: Vec = c.photos().map(|p| p.id).collect(); + let sort = |ascending| Sort { key: SortKey::Quality, ascending, ..Default::default() }; + let scored = |score: f32| Analysis { quality: Some(QualityScan { score, ..Default::default() }), ..Default::default() }; + for ascending in [false, true] { + let _ = c.query(&f, &sort(ascending)); // builds the kept order + } + for (k, id) in ids[1000..1005].iter().enumerate() { + c.apply(Op::SetAnalysis { id: *id, analysis: Some(scored(90.0 + k as f32)) }).unwrap(); + } + for ascending in [false, true] { + let kept = c.query(&f, &sort(ascending)); + let fresh = c.query_with(&f, &sort(ascending), false); + assert_eq!(kept[..8], fresh[..8], "ascending={ascending}: the first photos of the kept order are the fresh sort's"); + assert_eq!(kept, fresh, "ascending={ascending}: kept Quality order after the scan"); + } + // a scan that scores again, and one that clears a score, are as visible + c.apply(Op::SetAnalysis { id: ids[1000], analysis: Some(scored(10.0)) }).unwrap(); + c.apply(Op::SetAnalysis { id: ids[1004], analysis: None }).unwrap(); + for ascending in [false, true] { + assert_eq!(c.query(&f, &sort(ascending)), c.query_with(&f, &sort(ascending), false), "ascending={ascending}: rescored and cleared"); + } +} diff --git a/docs/changelog/unreleased/2026-12-02-quality-sort-after-a-scan.md b/docs/changelog/unreleased/2026-12-02-quality-sort-after-a-scan.md new file mode 100644 index 0000000000..1aa459c9a2 --- /dev/null +++ b/docs/changelog/unreleased/2026-12-02-quality-sort-after-a-scan.md @@ -0,0 +1,3 @@ +## Fixes + +- **Sort by Quality after an Image Quality scan:** in a library of 2,000 photos or more the grid kept the Quality order it had before the scan, so scored photos stayed among the unscored ones. A scan now retires that order (and only that one), and a photo placed among a listed order by Quality lands where a fresh sort puts it. diff --git a/docs/whats-new/2026-12-02-quality-sort-after-a-scan.md b/docs/whats-new/2026-12-02-quality-sort-after-a-scan.md new file mode 100644 index 0000000000..0bccbc1973 --- /dev/null +++ b/docs/whats-new/2026-12-02-quality-sort-after-a-scan.md @@ -0,0 +1,2 @@ +### Sort by Quality after a scan +- In a library of 2,000 photos or more, sorting by Quality right after an Image Quality scan now puts the photos the scan scored in place. It used to keep the order from before the scan until you rated or edited a photo or restarted. From d3aea608f2c2779b98b6c236bb8b46a206b6af0c Mon Sep 17 00:00:00 2001 From: Brian L Wong Date: Wed, 2 Dec 2026 09:50:44 -0500 Subject: [PATCH 004/244] CT-G6: a smart-album rule the matcher cannot read matches no photo The matcher failed open. A rule field this build does not know evaluated to false, so inside a none group (or for "isn't") it matched every photo; an operator that did not fit the field (`flag startsWith pick`, `hasGps isNot true`) was read as "isn't"/yes; a blank `contains` matched all. RuleSet::check refuses those, but only commands call it: replay, an import, an MCP call or a catalog from a newer build carried them in. Behaviour chosen: a rule set with a rule it cannot give a meaning matches NO photo, whatever the match of the group it is in (so no none/not-all/isn't wrapper turns it into "everyone"). RuleSet::unreadable (new) says it once for the whole set: an unknown field, an operator the field lacks, a value that is none of its kind (blank or non-text for text, a non-number, a date or unit that doesn't read, yes/no that is neither, between without two values), and an Album rule whose value names no collection or which names a smart album that cannot be read in turn (looked at once each, no deeper than evaluation goes, loops left as they are). Kept as they were: a rating no photo has, reversed dates and a value that is none of a choice (they match nothing, a meaning), the legacy Album operators that always meant "isn't" (RuleSet::upgrade), a plug-in number field tested with a text operator, and an empty group. It is worked out once per pass (Filter::prepare/prepare_one now take the catalog), not per photo; RuleSet::matches and Rule::matches (public, single calls) do it themselves. Counts, queries, smart-album listing, the tally and the album a filter names all go through it. Replay/undo/load: the matcher fix, not refusal. A refusal in apply() would drop, at replay, a smart album that an older or newer build stored (the next checkpoint would save the loss), and one in apply_new() would roll back whole imports for one odd rule (the Lightroom importer commits one batch), which cannot be checked without building the engine. So the album is kept and lists nothing, and Catalog::smart_album_problems still reports what is wrong with it. Deterministic: replay and live agree. Tests (tests_rule_readability.rs; the first and third and fourth fail without the change): sixteen unreadable rules, each alone and in six wrappers (any, none, none of a group, beside a good rule); readable rules keeping their meaning; an Album rule through a smart album that cannot be read; a journal replay of such an album. Version guard: no stored field or its reading changes; the rules are kept as written, so no VERSION bump or NEWEST_FIELDS change. (G8, which asks for a check that sees new rule fields, is a separate finding.) Manual: library/collections.mdx (smart collections: a rule that can't be read shows no photos). Co-Authored-By: Claude Sonnet 5.5 --- crates/catalog/src/lib.rs | 44 ++++- crates/catalog/src/query.rs | 41 ++-- crates/catalog/src/rules.rs | 133 ++++++++++++- crates/catalog/src/tally.rs | 10 +- crates/catalog/src/tests_rule_readability.rs | 184 ++++++++++++++++++ ...2-02-smart-collections-unreadable-rules.md | 3 + .../src/content/docs/library/collections.mdx | 1 + ...2-02-smart-collections-unreadable-rules.md | 2 + 8 files changed, 390 insertions(+), 28 deletions(-) create mode 100644 crates/catalog/src/tests_rule_readability.rs create mode 100644 docs/changelog/unreleased/2026-12-02-smart-collections-unreadable-rules.md create mode 100644 docs/whats-new/2026-12-02-smart-collections-unreadable-rules.md diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 227a332040..090d4e45a1 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -200,6 +200,11 @@ pub enum Op { AddAlbum { album: Album, }, + /// Removes a collection. The smart albums that test it (`album isNot X`) are left as they are and list nothing + /// from then on: a rule that names a collection that is gone can't be read ([`RuleSet::unreadable`]), so it is not + /// "in no collection" for every photo. Undo brings the collection back, and with it what they list. The removal is + /// never refused for them, so that an undo, a replayed log and the commands that remove several collections at + /// once end the same way; [`Catalog::smart_albums_testing`] says who is affected, for a command that wants to ask. RemoveAlbum { id: AlbumId, }, @@ -724,8 +729,26 @@ impl Catalog { /// Whether album `id` contains `p` (a smart album evaluates its rules; deleted photos are in /// no smart album; a collection set holds what the collections inside it hold, at any depth). pub fn album_contains(&self, id: AlbumId, p: &Photo) -> bool { + self.album_test(id)(p) + } + + /// [`Catalog::album_contains`] asked once for many photos: the smart album's rules are looked at once, here. + pub(crate) fn album_test(&self, id: AlbumId) -> impl Fn(&Photo) -> bool + '_ { + let smart = match self.albums.get(&id) { + Some(Album { smart: Some(rules), .. }) => Some((&**rules, rules.prepare_one(self))), + _ => None, + }; + move |p| match &smart { + Some((rules, prepared)) => self.smart_album_has(id, rules, prepared, p), + None => self.album_contains_nested(id, p), + } + } + + /// [`Catalog::album_contains`] for the Album rule of a rule set that was read as a whole already + /// ([`RuleSet::unreadable`] looks through the smart albums it tests). + pub(crate) fn album_contains_nested(&self, id: AlbumId, p: &Photo) -> bool { match self.albums.get(&id) { - Some(Album { smart: Some(rules), .. }) => self.smart_album_has(id, rules, &rules.prepare_one(), p), + Some(Album { smart: Some(rules), .. }) => self.smart_album_has(id, rules, &rules.prepare_nested(), p), // a folder (a collection set) holds what its collections hold, at any depth Some(a) if a.folder => self.folder_collections(a.id).iter().any(|c| self.album_contains(*c, p)), Some(a) => self.album_lists(a.id, p.id), @@ -790,7 +813,7 @@ impl Catalog { pub fn album_photos(&self, id: AlbumId) -> Vec { match self.albums.get(&id) { Some(Album { smart: Some(rules), .. }) => { - let prepared = rules.prepare(); + let prepared = rules.prepare(self); self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).map(|p| p.id).collect() } Some(a) if a.folder => { @@ -808,7 +831,7 @@ impl Catalog { match self.albums.get(&id) { // counted in place: no id list is built just for its length Some(Album { smart: Some(rules), .. }) => { - let prepared = rules.prepare(); + let prepared = rules.prepare(self); self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).count() } Some(a) => a.photos.iter().filter(|p| self.photos.get(p).is_some_and(|p| !p.deleted)).count(), @@ -816,6 +839,19 @@ impl Catalog { } } + /// The smart albums that test collection `id`, by their rules or their album field, in id order: what a removal of + /// it leaves listing nothing (see [`Op::RemoveAlbum`]). + pub fn smart_albums_testing(&self, id: AlbumId) -> Vec { + let mut out: Vec = self + .albums + .values() + .filter(|a| a.id != id && a.smart.as_deref().is_some_and(|f| f.albums_tested().contains(&id))) + .map(|a| a.id) + .collect(); + out.sort(); + out + } + /// Smart-album rules must not reference another smart album (no recursion) or deleted photos. fn validate_rules(&self, rules: &Filter) -> Result<()> { if rules.deleted { @@ -2088,6 +2124,8 @@ mod tests_repair; #[cfg(test)] mod tests_robust; #[cfg(test)] +mod tests_rule_readability; +#[cfg(test)] mod tests_search_text; #[cfg(test)] mod tests_sort_cache; diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index 7147368594..26923092f2 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -662,14 +662,17 @@ pub(crate) struct Prepared { /// The Memories fields hold something that can't be read ([`Filter::memories_problem`]): no photo matches, /// rather than the filter dropping what it can't read and matching every one. memories_unreadable: bool, + /// The rules, or the smart album the filter's album field names, can't be read ([`crate::rules::filter_unreadable`]): + /// no photo matches. + rules_unreadable: bool, } impl Prepared { /// What every filter has, whatever the pass: the library folder and the calendar day asked for. - fn base(filter: &Filter) -> Self { + fn base(filter: &Filter, rules_unreadable: bool) -> Self { let memories_unreadable = filter.memories_problem().is_some(); let month_day = filter.capture_month_day.as_deref().filter(|_| !memories_unreadable).and_then(month_day_of); - Prepared { root: filter.library_root(), only: None, whole: false, month_day, memories_unreadable } + Prepared { root: filter.library_root(), only: None, whole: false, month_day, memories_unreadable, rules_unreadable } } } @@ -1159,18 +1162,24 @@ impl Filter { } pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool { - self.matches_in(p, cat, &self.prepare_one()) + self.matches_in(p, cat, &self.prepare_one(cat)) } /// [`Filter::prepare`] for testing one photo (the `only` ids are looked through, not hashed). - pub(crate) fn prepare_one(&self) -> Prepared { - Prepared::base(self) + pub(crate) fn prepare_one(&self, cat: &Catalog) -> Prepared { + Prepared::base(self, crate::rules::filter_unreadable(self, cat)) + } + + /// [`Filter::prepare_one`] for the filter of a smart album tested by an Album rule: the rule set that holds the + /// rule was read as a whole, the smart albums it leads to with it. + pub(crate) fn prepare_nested(&self) -> Prepared { + Prepared::base(self, 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 { only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()), whole: true, ..Prepared::base(self) } + pub(crate) fn prepare(&self, cat: &Catalog) -> Prepared { + Prepared { only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()), whole: true, ..self.prepare_one(cat) } } /// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice. @@ -1183,7 +1192,7 @@ impl Filter { /// [`Filter::matches`] with what [`Filter::prepare`] works out done already, so a query over a /// big library does that once, not once per photo. pub(crate) fn matches_in(&self, p: &Photo, cat: &Catalog, prepared: &Prepared) -> bool { - if p.deleted != self.deleted { + if prepared.rules_unreadable || p.deleted != self.deleted { return false; } if self.in_library.is_some_and(|want| p.in_library() != want) { @@ -1220,7 +1229,7 @@ impl Filter { return false; } if let Some(rs) = &self.rule_set - && !rs.matches(p, cat) + && !rs.eval(p, cat) { return false; } @@ -1275,7 +1284,7 @@ impl Filter { } } if let Some(a) = self.album - && !cat.album_contains(a, p) + && !cat.album_contains_nested(a, p) { return false; } @@ -1459,7 +1468,7 @@ impl Catalog { } let listed: std::collections::HashSet = was.iter().copied().filter(|id| touched.binary_search(id).is_ok()).collect(); let mut ids: Vec = was.iter().copied().filter(|id| !listed.contains(id)).collect(); - let (prepared, within_prepared) = (filter.prepare_one(), within.map(Filter::prepare_one)); + let (prepared, within_prepared) = (filter.prepare_one(self), within.map(|w| w.prepare_one(self))); for id in touched { let Some(p) = self.photo(*id) else { continue }; let kept = within.zip(within_prepared.as_ref()).is_some_and(|(w, wp)| listed.contains(id) && w.matches_in(p, self, wp)); @@ -1474,7 +1483,7 @@ impl Catalog { /// How many of the photos matching `filter` carry each culling mark (the filter bar's counts). pub fn tally(&self, filter: &Filter) -> Tally { - let prepared = filter.prepare(); + let prepared = filter.prepare(self); let mut t = Tally::default(); for p in self.photos().filter(|p| filter.matches_in(p, self, &prepared)) { t.total += 1; @@ -1517,7 +1526,7 @@ impl Catalog { /// How many photos match `filter`: [`Catalog::query`]'s length without its sorting. pub fn count(&self, filter: &Filter) -> usize { - let prepared = filter.prepare(); + let prepared = filter.prepare(self); self.photos().filter(|p| filter.matches_in(p, self, &prepared)).count() } @@ -1534,9 +1543,9 @@ impl Catalog { cached: bool, keeping: Option<(&std::collections::HashSet, &Filter)>, ) -> Vec { - let prepared = filter.prepare(); + let prepared = filter.prepare(self); // `within` only decides for the few kept photos: worked out per photo, not hashed - let within_prepared = keeping.map(|(_, within)| within.prepare_one()); + let within_prepared = keeping.map(|(_, within)| within.prepare_one(self)); let keep = |p: &&Photo| { filter.matches_in(p, self, &prepared) || keeping.zip(within_prepared.as_ref()).is_some_and(|((kept, within), wp)| kept.contains(&p.id) && within.matches_in(p, self, wp)) @@ -1691,7 +1700,7 @@ impl Catalog { pub fn people_in(&self, filter: &Filter) -> Vec { let filter = Filter { person: None, people: Vec::new(), ..filter.clone() }; let mut m: std::collections::HashMap = Default::default(); - let prepared = filter.prepare(); + let prepared = filter.prepare(self); for p in self.photos().filter(|p| filter.matches_in(p, self, &prepared)) { let mut seen: Vec = Vec::new(); for r in p.meta.regions.iter().filter(|r| r.kind == lcc_meta::RegionKind::Face) { diff --git a/crates/catalog/src/rules.rs b/crates/catalog/src/rules.rs index 854dcd7717..b9df2616c0 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -1291,10 +1291,113 @@ fn date_op(op: &str, have: Option<&str>, value: &Value) -> bool { } } +/// Whether the matcher can give a rule a meaning, from the rule alone (see [`RuleSet::unreadable`]; the collections an +/// Album rule names are looked at there). +fn unreadable_rule(field: &str, op: &str, value: &Value) -> bool { + let Some(kind) = field_kind(field) else { return true }; + // an Album rule saved when Album was a number field (≥, between…) always matched as "isn't": `upgrade` rewrites + // it, and the matcher keeps reading it that way; a plug-in's number field tested with a text operator is + // tested as text + let text_on_plugin = kind == Kind::Number && plugin_field(field).is_some() && ops_for(Kind::Text).iter().any(|o| o.0 == op); + if kind != Kind::Album && !text_on_plugin && !ops_for(kind).iter().any(|o| o.0 == op) { + return true; + } + if !takes_value(op) { + return false; + } + match kind { + Kind::Bool => bool_value(value).is_none(), + Kind::Album => album_rule_id(value).is_none(), + Kind::Number if !text_on_plugin => match value { + Value::Array(a) if op == "between" && a.len() == 2 => a.iter().any(|v| number_problem(field, v).is_some()), + _ if op == "between" => true, + v => number_problem(field, v).is_some(), + }, + // (reversed dates are a rule that matches nothing, which is a meaning) + Kind::Date => date_problem(field, op, value).is_some_and(|(issue, _)| issue != Issue::DatesReversed), + // a value that is none of the choices names no photo, which is a meaning too + Kind::Choice(_) => false, + Kind::Text | Kind::Keywords | Kind::Number => match value { + Value::String(s) => s.trim().is_empty(), + Value::Number(_) => false, + _ => true, + }, + } +} + +/// One look at whether a rule set can be read ([`RuleSet::unreadable`]): the smart albums its Album rules lead to are +/// looked at once each, and never deeper than the evaluation goes ([`MAX_ALBUM_DEPTH`]). +#[derive(Default)] +struct Walk { + /// The smart albums being looked at, outermost first (a loop is not looked at again). + chain: Vec, + /// What was found of each album already looked at. + done: std::collections::HashMap, +} + +impl Walk { + fn set_unreadable(&mut self, rules: &RuleSet, cat: &Catalog) -> bool { + rules.rules.iter().any(|r| self.rule_unreadable(r, cat)) + } + + fn rule_unreadable(&mut self, rule: &Rule, cat: &Catalog) -> bool { + match rule { + Rule::Group { group } => self.set_unreadable(group, cat), + Rule::Field { field, op, value } => { + unreadable_rule(field, op, value) || (field == "album" && album_rule_id(value).is_some_and(|id| self.album_unreadable(id, cat))) + } + } + } + + /// Whether collection `id` is gone, or is a smart album whose own rules can't be read: it then holds nothing, + /// and "isn't in it" would hold for every photo. + fn album_unreadable(&mut self, id: crate::AlbumId, cat: &Catalog) -> bool { + let Some(album) = cat.album(id) else { return false }; + let Some(filter) = album.smart.as_deref() else { return false }; + if let Some(known) = self.done.get(&id) { + return *known; + } + // a loop is evaluated as holding nothing, and refused when edited: it is not looked at again here + if self.chain.contains(&id) { + return false; + } + if self.chain.len() >= MAX_ALBUM_DEPTH { + return true; + } + self.chain.push(id); + let bad = filter.memories_problem().is_some() || filter.rule_set.as_ref().is_some_and(|rs| self.set_unreadable(rs, cat)); + self.chain.pop(); + self.done.insert(id, bad); + bad + } + + /// Whether `filter` can't be read: its rules, or the smart album its album field names ([`Filter::album`]). + fn filter_unreadable(&mut self, filter: &crate::Filter, cat: &Catalog) -> bool { + filter.rule_set.as_ref().is_some_and(|rs| self.set_unreadable(rs, cat)) || filter.album.is_some_and(|a| self.album_unreadable(a, cat)) + } +} + +/// Whether `filter`'s rules, or the album its album field names, can't be read, so that it matches no photo +/// ([`RuleSet::unreadable`]). +pub(crate) fn filter_unreadable(filter: &crate::Filter, cat: &Catalog) -> bool { + Walk::default().filter_unreadable(filter, cat) +} + impl Rule { + /// Whether `p` meets the rule: false for every photo when the rule, or a rule inside it, can't be read + /// ([`RuleSet::unreadable`]). pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool { + let unreadable = match self { + Rule::Group { group } => group.unreadable(cat), + Rule::Field { .. } => Walk::default().rule_unreadable(self, cat), + }; + !unreadable && self.eval(p, cat) + } + + /// [`Rule::matches`] for rules already known to be readable (a pass over many photos asks once). + pub(crate) fn eval(&self, p: &Photo, cat: &Catalog) -> bool { let (field, op, value) = match self { - Rule::Group { group } => return group.matches(p, cat), + Rule::Group { group } => return group.eval(p, cat), Rule::Field { field, op, value } => (field.as_str(), op.as_str(), value), }; let m = &p.meta; @@ -1494,7 +1597,8 @@ impl Rule { "album" => { let id = album_rule_id(value); // a smart album's photos are its matches; one being evaluated (a loop) holds none - id.is_some_and(|a| cat.album_contains(a, p)) == (op == "is") + // (read once with the rule set: a collection that is gone or unreadable makes the set unreadable) + id.is_some_and(|a| cat.album_contains_nested(a, p)) == (op == "is") } f => match plugin_field(f) { // a number field compares as a number (a rule saved with a text operator still @@ -1511,17 +1615,36 @@ impl Rule { } impl RuleSet { + /// Whether `p` meets the rules. A rule set with a rule that can't be read ([`RuleSet::unreadable`]) is met by no + /// photo, whatever its mode: a rule that can't say who it describes is not turned into "everyone" by a `none` + /// group around it. pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool { + !self.unreadable(cat) && self.eval(p, cat) + } + + /// [`RuleSet::matches`] for a rule set already known to be readable (a pass over many photos asks once). + pub(crate) fn eval(&self, p: &Photo, cat: &Catalog) -> bool { if self.rules.is_empty() { return self.mode != Match::Any; } match self.mode { - Match::All => self.rules.iter().all(|r| r.matches(p, cat)), - Match::Any => self.rules.iter().any(|r| r.matches(p, cat)), - Match::None => !self.rules.iter().any(|r| r.matches(p, cat)), + Match::All => self.rules.iter().all(|r| r.eval(p, cat)), + Match::Any => self.rules.iter().any(|r| r.eval(p, cat)), + Match::None => !self.rules.iter().any(|r| r.eval(p, cat)), } } + /// Whether some rule (nested groups included) can't be given a meaning, so that the set matches no photo: a + /// field this build doesn't know (a newer build's, a hand edit), an operator the field doesn't have, a value + /// that is no value of its kind (text with nothing to look for, a number, date or yes/no that isn't one), or + /// an Album rule whose collection is gone, whose value names none, or which is a smart album that can't be + /// read in turn. The matcher can only say "not this one" for such a rule, which inside a `none` group, or for + /// "isn't", would list every photo. [`RuleSet::check`] reports these (and more) to people; this is what the + /// matcher itself needs, so it holds for rules from a replayed log, an import or another build too. + pub fn unreadable(&self, cat: &Catalog) -> bool { + Walk::default().set_unreadable(self, cat) + } + /// Whether matches depend on the clock ("in the last…" rules, nested groups included): the /// same photos can enter or leave the set without any catalog change. pub fn depends_on_now(&self) -> bool { diff --git a/crates/catalog/src/tally.rs b/crates/catalog/src/tally.rs index cbdbf92ea3..54d5c09f76 100644 --- a/crates/catalog/src/tally.rs +++ b/crates/catalog/src/tally.rs @@ -152,7 +152,8 @@ impl AlbumTally { smart.sort_by_key(|id| height_of(*id).unwrap_or(usize::MAX)); let held_by = |id: AlbumId| { let mut held = Members::none(); - for p in cat.photos().filter(|p| cat.album_contains(id, p)) { + let holds = cat.album_test(id); + for p in cat.photos().filter(|p| holds(p)) { held.set(p.id, true); } held @@ -217,8 +218,9 @@ impl AlbumTally { /// is an op on the album, and not followed). fn follow(&mut self, cat: &Catalog, touched: &[PhotoId], changed: Aspects) { for (album, held) in &mut self.members { + let holds = cat.album_test(*album); for id in touched { - held.set(*id, cat.photo(*id).is_some_and(|p| cat.album_contains(*album, p))); + held.set(*id, cat.photo(*id).is_some_and(|p| holds(p))); } self.counts.insert(*album, held.len()); } @@ -245,7 +247,7 @@ pub struct FilterTally { impl FilterTally { /// Counted from every photo. pub fn of(cat: &Catalog, filter: &Filter) -> FilterTally { - let prepared = filter.prepare(); + let prepared = filter.prepare(cat); let mut members = Members::none(); for p in cat.photos().filter(|p| filter.matches_in(p, cat, &prepared)) { members.set(p.id, true); @@ -283,7 +285,7 @@ impl FilterTally { return true; } let Some(touched) = cat.touched_since(self.revision).filter(|touched| touched.len() <= MAX_FOLLOWED) else { return false }; - let prepared = filter.prepare_one(); + let prepared = filter.prepare_one(cat); for id in touched { self.members.set(id, cat.photo(id).is_some_and(|p| filter.matches_in(p, cat, &prepared))); } diff --git a/crates/catalog/src/tests_rule_readability.rs b/crates/catalog/src/tests_rule_readability.rs new file mode 100644 index 0000000000..b50bd79344 --- /dev/null +++ b/crates/catalog/src/tests_rule_readability.rs @@ -0,0 +1,184 @@ +//! A smart album's rule that the matcher can't give a meaning (a field this build doesn't know, an operator the field +//! doesn't have, text with nothing to look for, a collection that is gone) makes the whole rule set list no photo, +//! whatever group it sits in: it is never "everyone" because a `none` group or an `isn't` wraps it. The same +//! after a replayed log, an undo and a collection removed. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; + +use crate::*; + +fn photo(c: &mut Catalog, name: &str) -> PhotoId { + let id = c.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: format!("/pics/{name}") }, name, "JPEG", 60, 40, "2026-05-01T10:00:00"); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id +} + +fn smart(c: &mut Catalog, name: &str, rule_set: Value) -> AlbumId { + let id = c.alloc_album_id(); + let filter: Filter = serde_json::from_value(json!({ "ruleSet": rule_set })).unwrap(); + c.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(filter)), ..Album::new(id, name) } }).unwrap(); + id +} + +fn plain(c: &mut Catalog, name: &str, photos: &[PhotoId]) -> AlbumId { + let id = c.alloc_album_id(); + c.apply(Op::AddAlbum { album: Album::new(id, name) }).unwrap(); + c.apply(Op::SetAlbumPhotos { id, photos: photos.to_vec() }).unwrap(); + id +} + +fn listed(c: &Catalog, album: AlbumId) -> BTreeSet { + c.album_photos(album).iter().map(|p| p.0).collect() +} + +fn all_of(rules: Value) -> Value { + json!({"match": "all", "rules": rules}) +} + +/// Three photos: 1 picked with GPS and a title, 2 rejected, 3 plain. +fn library() -> (Catalog, [PhotoId; 3]) { + let mut c = Catalog::new(); + let ids = [photo(&mut c, "picked.jpg"), photo(&mut c, "rejected.jpg"), photo(&mut c, "plain.jpg")]; + c.apply(Op::SetFlag { id: ids[0], flag: Flag::Pick }).unwrap(); + c.apply(Op::SetFlag { id: ids[1], flag: Flag::Reject }).unwrap(); + let mut meta = c.photo(ids[0]).unwrap().meta.clone(); + meta.gps = Some((45.0, 9.0)); + meta.title = "Harbour at dawn".into(); + c.apply(Op::SetMeta { id: ids[0], meta: Box::new(meta) }).unwrap(); + (c, ids) +} + +/// Every rule below is one the check refuses and the matcher can't evaluate: no photo comes of it, alone or wrapped +/// in a group of any match (the none group and the "not all" shape are the ones that turned it into everyone). +#[test] +fn a_rule_that_cannot_be_read_lists_no_photo_whatever_group_it_is_in() { + let (mut c, _) = library(); + let unreadable = [ + ("unknown field", json!({"field": "aFieldFromANewerBuild", "op": "contains", "value": "x"})), + ("operator the field lacks, choice", json!({"field": "flag", "op": "startsWith", "value": "pick"})), + ("operator the field lacks, yes/no", json!({"field": "hasGps", "op": "isNot", "value": true})), + ("operator the field lacks, number", json!({"field": "rating", "op": "contains", "value": 3})), + ("operator the field lacks, text", json!({"field": "title", "op": "gte", "value": "a"})), + ("blank text", json!({"field": "title", "op": "contains", "value": " "})), + ("empty text", json!({"field": "title", "op": "startsWith", "value": ""})), + ("no text", json!({"field": "title", "op": "notContains", "value": null})), + ("blank keyword", json!({"field": "keywords", "op": "contains", "value": " "})), + ("yes/no that is neither", json!({"field": "hasGps", "op": "is", "value": "maybe"})), + ("number that is none", json!({"field": "rating", "op": "gte", "value": "lots"})), + ("between with one value", json!({"field": "rating", "op": "between", "value": [1]})), + ("date that is none", json!({"field": "captureDate", "op": "after", "value": "someday"})), + ("unknown unit", json!({"field": "captureDate", "op": "inLast", "value": {"n": 3, "unit": "fortnights"}})), + ("album with no collection", json!({"field": "album", "op": "isNot", "value": null})), + ("album that is not a number", json!({"field": "album", "op": "isNot", "value": "the one"})), + ]; + let wrap = |rule: &Value| -> Vec<(&'static str, Value)> { + vec![ + ("alone", all_of(json!([rule]))), + ("any", json!({"match": "any", "rules": [rule]})), + ("none", json!({"match": "none", "rules": [rule]})), + ("none of a group", json!({"match": "none", "rules": [{"group": all_of(json!([rule]))}]})), + ( + "beside a rule that matches", + all_of(json!([{"field": "rating", "op": "gte", "value": 0}, {"group": {"match": "none", "rules": [rule]}}])), + ), + ("any beside a rule that matches", json!({"match": "any", "rules": [{"field": "rating", "op": "gte", "value": 0}, rule]})), + ] + }; + let mut wrong = Vec::new(); + for (what, rule) in &unreadable { + for (shape, set) in wrap(rule) { + let id = smart(&mut c, &format!("{what}, {shape}"), set); + let found = listed(&c, id); + if !found.is_empty() { + wrong.push(format!("{what}, {shape}: lists {found:?}")); + } + assert_eq!(c.album_count(id), 0, "{what}, {shape}: counts none"); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); +} + +/// What the matcher could always read keeps its meaning, in the same shapes, so the change takes away nothing else: +/// `isn't` on a choice, a rating no photo has, reversed dates, a value that is none of the choices, the legacy +/// Album operators, an empty group. +#[test] +fn rules_that_can_be_read_keep_their_meaning() { + let (mut c, ids) = library(); + let lists = |c: &mut Catalog, set: Value| { + let id = smart(c, "readable", set); + listed(c, id) + }; + let all: BTreeSet = ids.iter().map(|p| p.0).collect(); + let set = |ids: &[PhotoId]| ids.iter().map(|p| p.0).collect::>(); + assert_eq!(lists(&mut c, all_of(json!([{"field": "flag", "op": "isNot", "value": "pick"}]))), set(&ids[1..])); + assert_eq!(lists(&mut c, json!({"match": "none", "rules": [{"field": "flag", "op": "is", "value": "pick"}]})), set(&ids[1..])); + assert_eq!(lists(&mut c, all_of(json!([{"field": "hasGps", "op": "is", "value": true}]))), set(&ids[..1])); + assert_eq!(lists(&mut c, all_of(json!([{"field": "title", "op": "contains", "value": "harbour dawn"}]))), set(&ids[..1])); + // a rating no photo has is a rule that matches none, and its opposite every photo + assert!(lists(&mut c, all_of(json!([{"field": "rating", "op": "is", "value": 9}]))).is_empty()); + assert_eq!(lists(&mut c, all_of(json!([{"field": "rating", "op": "isNot", "value": 9}]))), all); + // a value that is none of the choices names no photo + assert!(lists(&mut c, all_of(json!([{"field": "flag", "op": "is", "value": "banana"}]))).is_empty()); + // reversed dates are a span no photo is in + assert!(lists(&mut c, all_of(json!([{"field": "captureDate", "op": "between", "value": ["2026-12", "2026-01"]}]))).is_empty()); + // "is empty" takes no value + assert_eq!(lists(&mut c, all_of(json!([{"field": "title", "op": "isEmpty", "value": null}]))), set(&ids[1..])); + // an empty group constrains nothing under all + assert_eq!(lists(&mut c, all_of(json!([]))), all); + // an Album rule saved when Album was a number field (it always meant "isn't") still does + let first = plain(&mut c, "First", &ids[..1]); + assert_eq!(lists(&mut c, all_of(json!([{"field": "album", "op": "gte", "value": first.0}]))), set(&ids[1..])); +} + +/// The rule set is read as a whole, so a problem found through a smart album an Album rule tests reaches every photo +/// too, for "is" and for "isn't" (a smart album that can't be read holds nothing, and not being in it is not everyone). +#[test] +fn an_album_rule_through_a_smart_album_that_cannot_be_read_lists_no_photo() { + let (mut c, ids) = library(); + let broken = smart(&mut c, "From a newer build", all_of(json!([{"field": "aFieldFromANewerBuild", "op": "is", "value": "x"}]))); + let tests = |c: &mut Catalog, op: &str| smart(c, op, all_of(json!([{"field": "album", "op": op, "value": broken.0}]))); + let (is, is_not) = (tests(&mut c, "is"), tests(&mut c, "isNot")); + assert!(listed(&c, broken).is_empty()); + assert!(listed(&c, is).is_empty()); + assert!(listed(&c, is_not).is_empty(), "not in an album that lists nothing because it can't be read is not everyone"); + // a smart album that can be read is a different matter + let readable = smart(&mut c, "Picks", all_of(json!([{"field": "flag", "op": "is", "value": "pick"}]))); + let not_picks = smart(&mut c, "Not picks", all_of(json!([{"field": "album", "op": "isNot", "value": readable.0}]))); + assert_eq!(listed(&c, not_picks), BTreeSet::from([ids[1].0, ids[2].0])); + // and the filter's own album field, for a view of one + assert!(c.query(&Filter { album: Some(broken), ..Default::default() }, &Sort::default()).is_empty()); +} + +/// A log that carries such a rule replays to the same state as the live apply (the album is neither refused nor +/// dropped, so a catalog from a newer build keeps its smart album), and the rule lists nothing in both. +#[test] +fn replay_keeps_a_smart_album_with_a_rule_it_cannot_read_and_lists_nothing() { + let m = MemStore::new(); + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + let mut ops = Vec::new(); + for i in 0..3 { + let id = c.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: format!("/pics/{i}.jpg") }, &format!("{i}.jpg"), "JPEG", 60, 40, "2026-05-01T10:00:00"); + let add = Op::AddPhoto { photo: Box::new(p) }; + c.apply(add.clone()).unwrap(); + ops.push(add); + } + let id = c.alloc_album_id(); + let filter: Filter = + serde_json::from_value(json!({"ruleSet": {"match": "none", "rules": [{"field": "aFieldFromANewerBuild", "op": "is", "value": 1}]}})).unwrap(); + let add = Op::AddAlbum { album: Album { smart: Some(Box::new(filter)), ..Album::new(id, "From a newer build") } }; + c.apply(add.clone()).unwrap(); + ops.push(add); + j.append(&ops).unwrap(); + j.flush().unwrap(); + drop(j); + let (_, loaded, report) = Journal::open(Box::new(m)).unwrap(); + assert_eq!(report.failed, 0, "no record is refused"); + assert!(loaded.album(id).is_some_and(Album::is_smart), "the album is kept"); + assert_eq!(loaded.album_photos(id), c.album_photos(id)); + assert!(loaded.album_photos(id).is_empty()); + assert_eq!(loaded.smart_album_problems(id).len(), 1, "and the check still says what is wrong with it"); +} diff --git a/docs/changelog/unreleased/2026-12-02-smart-collections-unreadable-rules.md b/docs/changelog/unreleased/2026-12-02-smart-collections-unreadable-rules.md new file mode 100644 index 0000000000..e41dc8f425 --- /dev/null +++ b/docs/changelog/unreleased/2026-12-02-smart-collections-unreadable-rules.md @@ -0,0 +1,3 @@ +## Fixes + +- **Smart collections fail closed:** a rule the matcher can't read (a field this version doesn't know, an operator the field doesn't have, blank text, a yes/no, number or date that is none) made a "none of" group, or an "isn't", list every photo. A smart collection with such a rule now lists no photo, whatever its match, in the grid, the counts and the collections it is tested by; Edit Smart Collection still marks the rule. diff --git a/docs/manual-site/src/content/docs/library/collections.mdx b/docs/manual-site/src/content/docs/library/collections.mdx index 9d130d34ca..b9a11daca6 100644 --- a/docs/manual-site/src/content/docs/library/collections.mdx +++ b/docs/manual-site/src/content/docs/library/collections.mdx @@ -27,6 +27,7 @@ import Shot from '../../../components/Shot.astro'; - Match **all**, **any** or **none** of the rules; **+ Rule**, **+ Group** (nested), 103 fields in groups: Rating, Pick Flag, Color Label, Label Text, Suggested Stars (from Assisted Culling), camera, lens, keyword, capture date, capture month and day of the month (any year), last exported, file path, file size, size before the crop (long edge, short edge, width, height, megapixels), Bits Per Channel, Source Color Mode and Source Color Profile, Has Snapshots, Has Smart Preview, Has Adjustments, Develop Preset, Has Point Color, Has AI, AI Edit, Masking, Manual Remove, Published Via, Publish Collection, and more. The AI fields see only the AI edits the photo itself records (Denoise and Generative Fill); Raw Details and Super Resolution make a separate photo and are not counted. Width, Height and the other size fields follow the crop, as in Lightroom; the "uncropped" ones give the size of the oriented photo before it. Bit depth, colour mode (RGB, grey, CMYK, Lab, raw) and colour profile come from the file itself and are read once in the background for photos imported earlier (a **Reading source colours** row; Metadata ▸ Read Source Colour); a photo not read yet matches no colour rule, and a file with no profile has the profile "Untagged", as in Lightroom. Published Via and Publish Collection match by name (the publish service's, the published collection's) against the photo's publish links, so a photo taken out of a published collection still matches until the next publish removes it; Lightroom's own publish links are not imported, so only photos published from Chromaforge match. - A smart collection updates itself as photos change. +- A smart collection with a rule the app can't read (a field a newer version added, an operator the field doesn't have, text with nothing to look for) shows no photos, whatever its match, until you fix or remove the rule: Edit Smart Collection marks it. It never shows every photo because of it. - **New Smart Collection from Filter…** (`Cmd/Ctrl+Alt+N`) turns the current filter bar into one; **Edit Smart Collection** changes the rules; double-click a smart collection in the Collections panel to open Edit Smart Collection….