//! What may enter, where home is, how a day's pictures fall into events, when //! days away are a trip, what a title says, and when a fresh proposal is //! suppressed by a decision the person already made. //! //! Plus the vectors — every string- and date-valued function pinned against //! what Node printed, and twelve WHOLE derivations pinned as JSON in //! `tests/fixtures/media_albums.json`. A clustering rule is not a thing three //! assertions can hold still; the answer is. use std::collections::HashMap; use serde_json::Value; use super::*; const IST: i64 = 5 * 3600 + 1800; /// Bengaluru, roughly. const HOME_LAT: f64 = 12.97; const HOME_LNG: f64 = 77.59; /// Hampi — ~290 km from Bengaluru. const HAMPI_LAT: f64 = 15.335; const HAMPI_LNG: f64 = 76.46; /// `new Date("2026-09-01T00:00:00.000Z")`. const NOW_MS: i64 = 1_787_875_200_000; const DAY: i64 = 86_400_000; fn home() -> AlbumHome { AlbumHome { latitude: HOME_LAT, longitude: HOME_LNG, label: Some("Bengaluru, India".to_string()), country: Some("India".to_string()), located: 40, } } fn names(id: &str) -> Option { match id { "person-a" => Some("Asha".to_string()), "person-b" => Some("Bala".to_string()), "person-c" => Some("Chitra".to_string()), "person-blank" => Some(String::new()), _ => None, } } fn strings(values: &[&str]) -> Vec { values.iter().map(|value| (*value).to_string()).collect() } /// The test file's own `candidate()` factory, counter included — the ids are /// `photo:` and a zero-padded serial, and several assertions below name them. struct Candidates { counter: usize, } impl Candidates { fn new() -> Self { Self { counter: 0 } } fn one(&mut self) -> AlbumCandidate { self.counter += 1; AlbumCandidate { id: format!("photo:{:0>64}", self.counter), kind: MediaFamily::Photo, taken_at: "2026-03-14T10:00:00.000Z".to_string(), taken_offset: Some(IST), latitude: Some(HOME_LAT), longitude: Some(HOME_LNG), place_name: None, place_city: Some("Bengaluru".to_string()), place_country: Some("India".to_string()), is_utility: None, subtypes: Vec::new(), own_library: true, camera_make: Some("Apple".to_string()), confirmed_copy: false, people: Vec::new(), aesthetic_score: None, favourite: false, } } /// `n` pictures `step_minutes` apart from `start` (UTC instants). fn burst(&mut self, n: usize, start: &str, step_minutes: i64, over: F) -> Vec where F: Fn(&mut AlbumCandidate), { let base = parse_date_ms(start).expect("a test instant parses"); (0..n) .map(|i| { let mut candidate = self.one(); candidate.taken_at = to_iso_string(base + i as i64 * step_minutes * 60_000).expect("in range"); over(&mut candidate); candidate }) .collect() } /// A day away at Hampi. fn day(&mut self, date: &str, n: usize, over: F) -> Vec where F: Fn(&mut AlbumCandidate), { self.burst(n, &format!("{date}T05:00:00.000Z"), 20, |c| { c.latitude = Some(HAMPI_LAT); c.longitude = Some(HAMPI_LNG); c.place_city = Some("Hampi".to_string()); over(c); }) } /// Enough located home pictures over the year for an inferred home. fn home_year(&mut self, n: usize) -> Vec { (0..n) .map(|i| { let mut candidate = self.one(); candidate.taken_at = to_iso_string(NOW_MS - (i as i64 + 10) * 7 * DAY).expect("in range"); candidate }) .collect() } } fn derive(candidates: &[AlbumCandidate], home: Option<&AlbumHome>) -> DeriveAlbumsResult { derive_albums(candidates, home, |_| IST, names).expect("every instant is readable") } fn anchors(result: &DeriveAlbumsResult) -> Vec<&str> { result.proposals.iter().map(|p| p.anchor.as_str()).collect() } fn titles(result: &DeriveAlbumsResult) -> Vec { result.proposals.iter().map(|p| p.title.say(&[])).collect() } /// An album title in the kit's words. fn said(kind: MediaAlbumKind, places: &[String], names: &[String]) -> String { album_title(kind, places, names).say(&[]) } // ── albumEligibility — D1 ──────────────────────────────────────────────────── #[test] fn admits_the_persons_own_picture_and_refuses_the_rest_each_with_its_reason() { let mut c = Candidates::new(); assert_eq!(album_eligibility(&c.one()), AlbumEligibility::Eligible); // Own by metadata alone: no library sighting, but a camera or a location. let mut own_by_camera = c.one(); own_by_camera.own_library = false; own_by_camera.camera_make = Some("Sony".to_string()); own_by_camera.latitude = None; own_by_camera.longitude = None; assert_eq!( album_eligibility(&own_by_camera), AlbumEligibility::Eligible ); let mut own_by_place = c.one(); own_by_place.own_library = false; own_by_place.camera_make = None; assert_eq!(album_eligibility(&own_by_place), AlbumEligibility::Eligible); // Arrived by chat or email, nothing else known: its time is the sent time. let mut sent = c.one(); sent.own_library = false; sent.camera_make = None; sent.latitude = None; sent.longitude = None; assert_eq!( album_eligibility(&sent), AlbumEligibility::Ineligible(AlbumIneligibleReason::NotOwn) ); let mut utility = c.one(); utility.is_utility = Some(1); assert_eq!( album_eligibility(&utility), AlbumEligibility::Ineligible(AlbumIneligibleReason::Utility) ); let mut shot = c.one(); shot.subtypes = strings(&["screenshot"]); assert_eq!( album_eligibility(&shot), AlbumEligibility::Ineligible(AlbumIneligibleReason::Screenshot) ); let mut copy = c.one(); copy.confirmed_copy = true; assert_eq!( album_eligibility(©), AlbumEligibility::Ineligible(AlbumIneligibleReason::DuplicateCopy) ); // Utility beats ownership in the report: the reason names the rule that // bit first. let mut both = c.one(); both.is_utility = Some(1); both.own_library = false; both.camera_make = None; both.latitude = None; both.longitude = None; assert_eq!( album_eligibility(&both).reason(), Some(AlbumIneligibleReason::Utility) ); } #[test] fn lets_a_person_add_a_sent_picture_by_hand_never_a_screenshot() { assert!(album_admits_by_hand(None, &[])); assert!(!album_admits_by_hand(Some(1), &[])); assert!(!album_admits_by_hand(Some(0), &strings(&["screenshot"]))); } /// Twelve eligibility verdicts and four by-hand answers, read out of Node. /// /// Three of them are the reason this table exists rather than a paragraph. /// `is_utility` is an INTEGER column and the test is `=== 1`, so a `2` is /// eligible — truthiness would have refused it. `subtypes.includes` is /// case-SENSITIVE, so `"SCREENSHOT"` sails through, which is a real shape if /// an importer ever upper-cases Apple's vocabulary. And a picture that is both /// a screenshot and a confirmed copy is reported as a SCREENSHOT: the order of /// the clauses is the order of the answers. #[test] fn album_eligibility_matches_the_typescript_on_every_clause() { let mut c = Candidates::new(); let cases: Vec<(&str, AlbumCandidate, AlbumEligibility)> = vec![ ("plain", c.one(), AlbumEligibility::Eligible), ( "own by camera", AlbumCandidate { own_library: false, camera_make: Some("Sony".to_string()), latitude: None, longitude: None, ..c.one() }, AlbumEligibility::Eligible, ), ( "own by location", AlbumCandidate { own_library: false, camera_make: None, ..c.one() }, AlbumEligibility::Eligible, ), ( "sent to me", AlbumCandidate { own_library: false, camera_make: None, latitude: None, longitude: None, ..c.one() }, AlbumEligibility::Ineligible(AlbumIneligibleReason::NotOwn), ), ( "is_utility = 1", AlbumCandidate { is_utility: Some(1), ..c.one() }, AlbumEligibility::Ineligible(AlbumIneligibleReason::Utility), ), ( "is_utility = 0", AlbumCandidate { is_utility: Some(0), ..c.one() }, AlbumEligibility::Eligible, ), ( "screenshot", AlbumCandidate { subtypes: strings(&["screenshot"]), ..c.one() }, AlbumEligibility::Ineligible(AlbumIneligibleReason::Screenshot), ), ( "screenshot among others", AlbumCandidate { subtypes: strings(&["hdr", "screenshot"]), ..c.one() }, AlbumEligibility::Ineligible(AlbumIneligibleReason::Screenshot), ), ( "SCREENSHOT is a different string", AlbumCandidate { subtypes: strings(&["SCREENSHOT"]), ..c.one() }, AlbumEligibility::Eligible, ), ( "confirmed copy", AlbumCandidate { confirmed_copy: true, ..c.one() }, AlbumEligibility::Ineligible(AlbumIneligibleReason::DuplicateCopy), ), ( "utility beats not_own", AlbumCandidate { is_utility: Some(1), own_library: false, camera_make: None, latitude: None, longitude: None, ..c.one() }, AlbumEligibility::Ineligible(AlbumIneligibleReason::Utility), ), ( "screenshot beats duplicate_copy", AlbumCandidate { confirmed_copy: true, subtypes: strings(&["screenshot"]), ..c.one() }, AlbumEligibility::Ineligible(AlbumIneligibleReason::Screenshot), ), ]; for (label, candidate, expected) in cases { assert_eq!(album_eligibility(&candidate), expected, "{label}"); } assert!(album_admits_by_hand(None, &[])); assert!(!album_admits_by_hand(Some(1), &[])); assert!(!album_admits_by_hand(Some(0), &strings(&["screenshot"]))); // `!== 1`, not truthiness. assert!(album_admits_by_hand(Some(2), &[])); } // ── clocks and distances ───────────────────────────────────────────────────── #[test] fn shifts_an_instant_into_its_own_local_day_and_hour() { // 22:30 UTC is 04:00 IST the next day. let shifted = local_instant("2026-03-14T22:30:00.000Z", IST).expect("parses"); assert_eq!(shifted.date, "2026-03-15"); assert_eq!(shifted.hour, "2026-03-15T04"); let flat = local_instant("2026-03-14T22:30:00.000Z", 0).expect("parses"); assert_eq!(flat.date, "2026-03-14"); assert_eq!(flat.hour, "2026-03-14T22"); } /// Ten readings run through the TypeScript. /// /// The last three are the ones a hand-written expectation would have got /// wrong: an instant that already carries its own offset (`…+05:30`) is /// parsed and then shifted AGAIN by the row's `taken_offset`, a date with no /// time at all is UTC midnight before the shift, and sub-second precision /// survives into `ms` while the date and hour ignore it. #[test] fn local_instant_matches_the_typescript() { let cases: &[(&str, i64, i64, &str, &str)] = &[ ( "2026-03-14T22:30:00.000Z", IST, 1_773_547_200_000, "2026-03-15", "2026-03-15T04", ), ( "2026-03-14T22:30:00.000Z", 0, 1_773_527_400_000, "2026-03-14", "2026-03-14T22", ), ( "2026-03-14T18:30:00.000Z", IST, 1_773_532_800_000, "2026-03-15", "2026-03-15T00", ), ( "2026-01-01T00:00:00.000Z", -18000, 1_767_207_600_000, "2025-12-31", "2025-12-31T19", ), ( "2026-12-31T23:59:59.999Z", 1, 1_798_761_600_999, "2027-01-01", "2027-01-01T00", ), ( "2026-06-15T12:00:00.000Z", -43200, 1_781_481_600_000, "2026-06-15", "2026-06-15T00", ), ( "2026-06-15T12:00:00.000Z", 50400, 1_781_575_200_000, "2026-06-16", "2026-06-16T02", ), ( "2026-03-14T10:00:00+05:30", IST, 1_773_482_400_000, "2026-03-14", "2026-03-14T10", ), ( "2026-03-14", IST, 1_773_466_200_000, "2026-03-14", "2026-03-14T05", ), ( "2026-03-14T05:00:00.500Z", 2700, 1_773_467_100_500, "2026-03-14", "2026-03-14T05", ), ]; for (taken_at, offset, ms, date, hour) in cases { assert_eq!( local_instant(taken_at, *offset), Ok(LocalInstant { ms: *ms, date: (*date).to_string(), hour: (*hour).to_string(), }), "local_instant({taken_at:?}, {offset})" ); } // Where the TypeScript throws `RangeError: Invalid time value`. assert_eq!( local_instant("not-a-date", 0), Err(AlbumsError::InvalidTimeValue) ); assert_eq!( local_instant("not-a-date", 0).unwrap_err().to_string(), "Invalid time value" ); } #[test] fn reads_a_zones_offset_and_treats_an_unknown_zone_as_utc() { assert_eq!(zone_offset_seconds("Asia/Kolkata", NOW_MS), IST); assert_eq!( zone_offset_seconds( "Europe/London", parse_date_ms("2026-07-01T12:00:00.000Z").unwrap() ), 3600 ); assert_eq!( zone_offset_seconds( "Europe/London", parse_date_ms("2026-01-01T12:00:00.000Z").unwrap() ), 0 ); assert_eq!(zone_offset_seconds("Mars/Olympus", NOW_MS), 0); } /// Twelve offsets read out of Node, across DST edges, a 45-minute zone, a /// 15-minute one, and a zone whose DST rule was abolished in 2019 (probed in /// 1999, when it still had one). /// /// This crate reads `chrono-tz` where the TypeScript reads ICU — the same IANA /// database, two copies of it — so a tzdata skew shows up here as a red test /// rather than as an album on the wrong day. The empty zone and `Mars/Olympus` /// both answer 0: the TypeScript catches the `Intl` constructor throwing and /// falls back to UTC, deliberately, so a workspace with a nonsense zone still /// gets albums. #[test] fn zone_offset_seconds_matches_the_typescript() { let cases: &[(&str, &str, i64)] = &[ ("Asia/Kolkata", "2026-09-01T00:00:00.000Z", 19800), ("Europe/London", "2026-07-01T12:00:00.000Z", 3600), ("Europe/London", "2026-01-01T12:00:00.000Z", 0), ("Mars/Olympus", "2026-09-01T00:00:00.000Z", 0), ("UTC", "2026-09-01T00:00:00.000Z", 0), // A minute either side of the American spring-forward. ("America/New_York", "2026-03-08T06:59:00.000Z", -18000), ("America/New_York", "2026-03-08T07:01:00.000Z", -14400), ("Pacific/Chatham", "2026-01-15T00:00:00.000Z", 49500), ("Australia/Adelaide", "2026-06-15T00:00:00.000Z", 34200), // A sub-second instant, to prove the flooring does not shift the // answer. ("Asia/Kathmandu", "2026-06-15T00:00:00.123Z", 20700), ("America/Sao_Paulo", "1999-01-15T00:00:00.000Z", -7200), ("", "2026-09-01T00:00:00.000Z", 0), ]; for (zone, at, expected) in cases { let at_ms = parse_date_ms(at).expect("a test instant parses"); assert_eq!( zone_offset_seconds(zone, at_ms), *expected, "zone_offset_seconds({zone:?}, {at})" ); } } #[test] fn measures_the_great_circle() { assert_eq!(distance_km(HOME_LAT, HOME_LNG, HOME_LAT, HOME_LNG), 0.0); let to_hampi = distance_km(HOME_LAT, HOME_LNG, HAMPI_LAT, HAMPI_LNG); assert!(to_hampi > 280.0); assert!(to_hampi < 300.0); } /// Seven distances read out of Node. /// /// Compared to within a nanometre rather than bit for bit: `sin`, `cos` and /// `asin` are the platform's libm on both sides and are permitted to disagree /// in the last unit of the last place. Every threshold this feeds — 2 km, /// 50 km, the 10 km home cell — has a margin measured in kilometres, so an /// ulp is not a decision anywhere. #[test] fn distance_km_matches_the_typescript() { let cases: &[(f64, f64, f64, f64, f64)] = &[ (HOME_LAT, HOME_LNG, HOME_LAT, HOME_LNG, 0.0), (HOME_LAT, HOME_LNG, HAMPI_LAT, HAMPI_LNG, 289.8240685060125), ( HOME_LAT, HOME_LNG, 13.020000000000001, HOME_LNG, 5.559746332228015, ), (HOME_LAT, HOME_LNG, 13.07, HOME_LNG, 11.119492664455834), // Antipodes: the haversine root lands a hair over 1 and the clamp is // what keeps `asin` from answering NaN. (0.0, 0.0, 0.0, 180.0, 20015.086796020572), (90.0, 0.0, -90.0, 0.0, 20015.086796020572), (51.5, -0.12, 40.71, -74.0, 5570.794265822577), ]; for (a_lat, a_lng, b_lat, b_lng, expected) in cases { let value = distance_km(*a_lat, *a_lng, *b_lat, *b_lng); assert!( (value - expected).abs() < 1e-9, "distance_km({a_lat}, {a_lng}, {b_lat}, {b_lng}) = {value}, expected {expected}" ); } } // ── inferHome — D2 ─────────────────────────────────────────────────────────── #[test] fn home_is_the_modal_cell_of_the_years_located_pictures() { let mut c = Candidates::new(); let year = c.home_year(ALBUM_HOME_MIN_LOCATED + 5); // A trip's worth of away pictures does not move home. let away = c.burst(12, "2026-06-01T05:00:00.000Z", 30, |candidate| { candidate.latitude = Some(HAMPI_LAT); candidate.longitude = Some(HAMPI_LNG); candidate.place_city = Some("Hampi".to_string()); }); let mut all = year.clone(); all.extend(away.clone()); let found = infer_home(&all, NOW_MS).expect("enough located pictures"); assert_eq!(found.label.as_deref(), Some("Bengaluru, India")); assert_eq!(found.country.as_deref(), Some("India")); assert_eq!(found.located, year.len() + away.len()); assert!((found.latitude - HOME_LAT).abs() < 0.01); } #[test] fn home_is_nothing_when_too_few_pictures_are_located_or_they_are_too_old() { let mut c = Candidates::new(); assert_eq!( infer_home(&c.home_year(ALBUM_HOME_MIN_LOCATED - 1), NOW_MS), None ); let old: Vec = c .home_year(ALBUM_HOME_MIN_LOCATED + 5) .into_iter() .map(|mut candidate| { candidate.taken_at = "2020-01-01T00:00:00.000Z".to_string(); candidate }) .collect(); assert_eq!(infer_home(&old, NOW_MS), None); // Unlocated and ineligible pictures do not count. let blind: Vec = c .home_year(ALBUM_HOME_MIN_LOCATED + 5) .into_iter() .map(|mut candidate| { candidate.latitude = None; candidate.longitude = None; candidate }) .collect(); assert_eq!(infer_home(&blind, NOW_MS), None); let shots: Vec = c .home_year(ALBUM_HOME_MIN_LOCATED + 5) .into_iter() .map(|mut candidate| { candidate.subtypes = strings(&["screenshot"]); candidate }) .collect(); assert_eq!(infer_home(&shots, NOW_MS), None); } /// Four whole `AlbumHome` answers as Node printed them, the mean latitude /// included to its last digit. /// /// Compared field by field rather than against a JSON golden ON PURPOSE: /// `serde_json` is built here WITHOUT its `float_roundtrip` feature, so its /// fast float parser reads `12.970000000000013` back as the neighbouring /// double. A Rust float LITERAL is correctly rounded, so the expectations are /// written as literals and the fixture-shaped comparison is kept for /// `derive_albums`, whose answer holds no floats at all. /// /// The tie is the rule with teeth: two cells of sixteen pictures each, the /// LATER one listed second, and home is the cell whose most recent picture is /// more recent — not the first one seen. The unnamed case shows the one way /// `label` comes back null: `[].join(", ")` is `""`, which is falsy. #[test] fn infer_home_matches_the_typescript() { let mut c = Candidates::new(); let year = c.home_year(35); let away = c.burst(12, "2026-06-01T05:00:00.000Z", 30, |candidate| { candidate.latitude = Some(HAMPI_LAT); candidate.longitude = Some(HAMPI_LNG); candidate.place_city = Some("Hampi".to_string()); }); let mut all = year.clone(); all.extend(away); assert_eq!( infer_home(&all, NOW_MS), Some(AlbumHome { latitude: 12.970000000000013, longitude: 77.59000000000002, label: Some("Bengaluru, India".to_string()), country: Some("India".to_string()), located: 47, }) ); assert_eq!(infer_home(&c.home_year(29), NOW_MS), None); let unnamed: Vec = c .home_year(35) .into_iter() .map(|mut candidate| { candidate.place_city = None; candidate.place_country = None; candidate }) .collect(); assert_eq!( infer_home(&unnamed, NOW_MS), Some(AlbumHome { latitude: 12.970000000000013, longitude: 77.59000000000002, label: None, country: None, located: 35, }) ); let mut c = Candidates::new(); let cell_a: Vec = (0..16) .map(|i| { let mut candidate = c.one(); candidate.taken_at = to_iso_string(NOW_MS - (i + 1) * DAY).expect("in range"); candidate.place_city = Some("Aville".to_string()); candidate }) .collect(); let cell_b: Vec = (0..16) .map(|i| { let mut candidate = c.one(); candidate.taken_at = to_iso_string(NOW_MS - (i + 1) * DAY - 3_600_000).expect("in range"); candidate.latitude = Some(HOME_LAT + 0.5); candidate.place_city = Some("Bville".to_string()); candidate }) .collect(); let mut tied = cell_b; tied.extend(cell_a); assert_eq!( infer_home(&tied, NOW_MS), Some(AlbumHome { latitude: 12.97, longitude: 77.59, label: Some("Aville, India".to_string()), country: Some("India".to_string()), located: 32, }) ); } // ── deriveAlbums — events (D3) ─────────────────────────────────────────────── #[test] fn proposes_a_dense_cluster_on_one_day_anchored_on_its_first_local_hour() { let mut c = Candidates::new(); let party = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T13:30:00.000Z", 10, |candidate| candidate.place_name = Some("Koramangala".to_string()), ); let mut shot = c.one(); shot.taken_at = "2026-03-14T14:00:00.000Z".to_string(); shot.subtypes = strings(&["screenshot"]); let mut all = party.clone(); all.push(shot); let out = derive(&all, Some(&home())); assert_eq!(out.eligible, ALBUM_EVENT_MIN_MEMBERS); assert_eq!( out.ineligible, AlbumIneligibleCounts { not_own: 0, utility: 0, screenshot: 1, duplicate_copy: 0, } ); assert_eq!(out.proposals.len(), 1); let event = &out.proposals[0]; assert_eq!(event.kind, MediaAlbumKind::Event); // 13:30 UTC is 19:00 IST. assert_eq!(event.anchor, "2026-03-14T19"); assert_eq!(event.title.say(&[]), "Koramangala"); assert_eq!(event.starts_at, "2026-03-14"); assert_eq!(event.ends_at, "2026-03-14"); assert_eq!(event.home_label, None); assert_eq!(event.people, Vec::::new()); assert_eq!( event .members .iter() .map(|m| m.id.as_str()) .collect::>(), party.iter().map(|c| c.id.as_str()).collect::>() ); } #[test] fn nothing_under_the_floor_and_a_gap_of_more_than_three_hours_is_two_clusters() { let mut c = Candidates::new(); let thin = c.burst( ALBUM_EVENT_MIN_MEMBERS - 1, "2026-03-14T05:00:00.000Z", 5, |_| {}, ); assert_eq!(derive(&thin, Some(&home())).proposals, vec![]); let mut c = Candidates::new(); let morning = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T04:00:00.000Z", 5, |_| {}, ); let evening = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T12:00:00.000Z", 5, |_| {}, ); let mut both = morning; both.extend(evening); assert_eq!( anchors(&derive(&both, Some(&home()))), vec!["2026-03-14T09", "2026-03-14T17"] ); // Four pictures at each end of a five-hour gap: neither side is an event. let mut c = Candidates::new(); let mut short = c.burst(4, "2026-03-14T04:00:00.000Z", 5, |_| {}); short.extend(c.burst(4, "2026-03-14T09:00:00.000Z", 5, |_| {})); assert_eq!(derive(&short, Some(&home())).proposals, vec![]); } #[test] fn splits_on_a_two_kilometre_jump_even_inside_the_gap() { let mut c = Candidates::new(); let here = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T05:00:00.000Z", 5, |_| {}, ); let there = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T06:00:00.000Z", 5, |candidate| { candidate.latitude = Some(HOME_LAT + 0.05); candidate.longitude = Some(HOME_LNG); }, ); let mut both = here.clone(); both.extend(there); assert_eq!(derive(&both, Some(&home())).proposals.len(), 2); // Unlocated pictures in between never split anything. let blind = c.burst(3, "2026-03-14T05:45:00.000Z", 3, |candidate| { candidate.latitude = None; candidate.longitude = None; }); let mut mixed = here; mixed.extend(blind); assert_eq!(derive(&mixed, Some(&home())).proposals.len(), 1); } #[test] fn splits_two_disjoint_companies_across_an_hours_gap_and_keeps_one_company_together() { let mut c = Candidates::new(); let lunch = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T07:00:00.000Z", 5, |candidate| candidate.people = strings(&["person-a"]), ); let dinner = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T09:00:00.000Z", 5, |candidate| candidate.people = strings(&["person-b"]), ); let mut apart = lunch.clone(); apart.extend(dinner.clone()); assert_eq!( titles(&derive(&apart, Some(&home()))), vec!["Bengaluru with Asha", "Bengaluru with Bala"] ); // Same people both sides: one event, both named. let mut together = lunch.clone(); together.extend(dinner.iter().cloned().map(|mut candidate| { candidate.people = strings(&["person-a", "person-b"]); candidate })); assert_eq!( titles(&derive(&together, Some(&home()))), vec!["Bengaluru with Asha and Bala"] ); // Nobody linked on one side: nothing to be disjoint from. let mut strangers = lunch; strangers.extend(dinner.into_iter().map(|mut candidate| { candidate.people = Vec::new(); candidate })); assert_eq!(derive(&strangers, Some(&home())).proposals.len(), 1); } #[test] fn names_up_to_two_people_on_at_least_half_the_members_and_picks_the_cover_by_score() { let mut c = Candidates::new(); let mut party = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T13:00:00.000Z", 10, |candidate| candidate.people = strings(&["person-a", "person-b", "person-c"]), ); party[3].aesthetic_score = Some(0.9); let cover_id = party[3].id.clone(); // Chitra on only two of eight: not named. An unknown id is skipped. let thinned: Vec = party .into_iter() .enumerate() .map(|(i, mut candidate)| { candidate.people = if i < 2 { strings(&["person-a", "person-b", "person-c", "ghost"]) } else { strings(&["person-a", "person-b"]) }; candidate }) .collect(); let out = derive(&thinned, Some(&home())); let event = &out.proposals[0]; assert_eq!(event.title.say(&[]), "Bengaluru with Asha and Bala"); assert_eq!(event.people, strings(&["person-a", "person-b"])); assert_eq!(event.cover_id, cover_id); } /// 18:00 UTC is 23:30 IST, ten minutes apart, so the last four fall on the /// next local day. An event is a DAY, and its id is a day. #[test] fn does_not_propose_a_cluster_that_crosses_midnight_as_an_event() { let mut c = Candidates::new(); let across = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T17:50:00.000Z", 10, |_| {}, ); assert_eq!(derive(&across, Some(&home())).proposals, vec![]); } // ── deriveAlbums — trips (D3) ──────────────────────────────────────────────── #[test] fn a_trip_is_consecutive_days_away_naming_the_home_it_was_judged_against() { let mut c = Candidates::new(); let mut days = c.day("2026-04-10", 5, |_| {}); days.extend(c.day("2026-04-11", 5, |_| {})); days.extend(c.day("2026-04-12", 2, |_| {})); let out = derive(&days, Some(&home())); assert_eq!(out.proposals.len(), 1); let trip = &out.proposals[0]; assert_eq!(trip.kind, MediaAlbumKind::Trip); assert_eq!(trip.anchor, "2026-04-10"); assert_eq!(trip.title.say(&[]), "Hampi"); assert_eq!(trip.starts_at, "2026-04-10"); assert_eq!(trip.ends_at, "2026-04-12"); assert_eq!(trip.home_label.as_deref(), Some("Bengaluru, India")); assert_eq!(trip.members.len(), 12); } #[test] fn a_trip_needs_two_days_and_ten_members_and_no_home_means_no_trip() { let mut c = Candidates::new(); let one_day = c.day("2026-04-10", 12, |_| {}); assert_eq!( derive(&one_day, Some(&home())) .proposals .iter() .map(|p| p.kind) .collect::>(), vec![MediaAlbumKind::Event] ); let mut c = Candidates::new(); let mut thin = c.day("2026-04-10", 5, |_| {}); thin.extend(c.day("2026-04-11", 4, |_| {})); assert_eq!(derive(&thin, Some(&home())).proposals, vec![]); let mut c = Candidates::new(); let mut enough = c.day("2026-04-10", 5, |_| {}); enough.extend(c.day("2026-04-11", 5, |_| {})); assert_eq!(derive(&enough, None).proposals, vec![]); } #[test] fn bridges_one_unlocated_day_and_breaks_on_a_day_spent_at_home() { let mut c = Candidates::new(); let mut bridged = c.day("2026-04-10", 5, |_| {}); bridged.extend(c.burst(2, "2026-04-11T05:00:00.000Z", 20, |candidate| { candidate.latitude = None; candidate.longitude = None; candidate.place_city = None; })); bridged.extend(c.day("2026-04-12", 5, |_| {})); let out = derive(&bridged, Some(&home())); assert_eq!( out.proposals .iter() .map(|p| (p.kind, p.starts_at.as_str(), p.ends_at.as_str())) .collect::>(), vec![(MediaAlbumKind::Trip, "2026-04-10", "2026-04-12")] ); // Two empty days between: two separate runs, neither long enough. let mut c = Candidates::new(); let mut far_apart = c.day("2026-04-10", 5, |_| {}); far_apart.extend(c.day("2026-04-13", 5, |_| {})); assert_eq!(derive(&far_apart, Some(&home())).proposals, vec![]); // A located day at home between: home broke the trip. let mut c = Candidates::new(); let mut broken = c.day("2026-04-10", 5, |_| {}); broken.extend(c.burst(2, "2026-04-11T05:00:00.000Z", 20, |_| {})); broken.extend(c.day("2026-04-12", 5, |_| {})); assert_eq!(derive(&broken, Some(&home())).proposals, vec![]); } #[test] fn counts_another_country_as_away_names_two_places_and_subsumes_its_events() { let mut c = Candidates::new(); let mut abroad = c.day("2026-05-01", ALBUM_EVENT_MIN_MEMBERS, |candidate| { candidate.latitude = Some(HOME_LAT + 0.1); candidate.longitude = Some(HOME_LNG); candidate.place_city = Some("Colombo".to_string()); candidate.place_country = Some("Sri Lanka".to_string()); }); abroad.extend(c.day("2026-05-02", 4, |candidate| { candidate.latitude = Some(HOME_LAT + 0.1); candidate.longitude = Some(HOME_LNG); candidate.place_city = Some("Galle".to_string()); candidate.place_country = Some("Sri Lanka".to_string()); })); let out = derive(&abroad, Some(&home())); assert_eq!( out.proposals.iter().map(|p| p.kind).collect::>(), vec![MediaAlbumKind::Trip] ); assert_eq!(out.proposals[0].title.say(&[]), "Colombo and Galle"); assert_eq!(out.proposals[0].members.len(), ALBUM_EVENT_MIN_MEMBERS + 4); } #[test] fn orders_proposals_oldest_first() { let mut c = Candidates::new(); let later = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-06-01T05:00:00.000Z", 5, |_| {}, ); let mut all = later; all.extend(c.day("2026-04-10", 5, |_| {})); all.extend(c.day("2026-04-11", ALBUM_TRIP_MIN_MEMBERS, |_| {})); assert_eq!( anchors(&derive(&all, Some(&home()))), vec!["2026-04-10", "2026-06-01T10"] ); } // ── albumTitle ─────────────────────────────────────────────────────────────── #[test] fn says_the_place_then_the_company_and_has_a_plain_fallback() { assert_eq!( said(MediaAlbumKind::Event, &strings(&["Koramangala"]), &[]), "Koramangala" ); assert_eq!( said(MediaAlbumKind::Event, &[], &strings(&["Asha"])), "With Asha" ); assert_eq!(said(MediaAlbumKind::Event, &[], &[]), "A day out"); assert_eq!( said( MediaAlbumKind::Trip, &strings(&["Hampi", "Goa"]), &strings(&["Asha", "Bala"]) ), "Hampi and Goa with Asha and Bala" ); assert_eq!( said(MediaAlbumKind::Trip, &[], &strings(&["Asha"])), "A trip with Asha" ); assert_eq!(said(MediaAlbumKind::Trip, &[], &[]), "A trip"); } /// Eleven titles read out of Node. /// /// Two are worth the trip. An EVENT names only its first place even when two /// were passed, while a TRIP joins every place it was given with " and " — /// `ALBUM_TITLE_MAX_PLACES` is applied by the caller, not by the formatter, so /// a third place would appear. And an EMPTY first place falls through to the /// people (`if (place)` is falsy for `""`), which is what stops a place column /// that was written and says nothing from titling an album `""`. #[test] fn album_title_matches_the_typescript() { let cases: &[(MediaAlbumKind, &[&str], &[&str], &str)] = &[ (MediaAlbumKind::Event, &["Koramangala"], &[], "Koramangala"), (MediaAlbumKind::Event, &[], &["Asha"], "With Asha"), (MediaAlbumKind::Event, &[], &[], "A day out"), ( MediaAlbumKind::Event, &["Koramangala"], &["Asha", "Bala"], "Koramangala with Asha and Bala", ), ( MediaAlbumKind::Event, &["Koramangala", "Indiranagar"], &["Asha"], "Koramangala with Asha", ), ( MediaAlbumKind::Trip, &["Hampi", "Goa"], &["Asha", "Bala"], "Hampi and Goa with Asha and Bala", ), (MediaAlbumKind::Trip, &[], &["Asha"], "A trip with Asha"), (MediaAlbumKind::Trip, &[], &[], "A trip"), (MediaAlbumKind::Trip, &["Hampi"], &[], "Hampi"), ( MediaAlbumKind::Trip, &["Hampi", "Goa", "Mysuru"], &[], "Hampi and Goa and Mysuru", ), (MediaAlbumKind::Event, &[""], &["Asha"], "With Asha"), ]; for (kind, places, people, expected) in cases { assert_eq!( said(*kind, &strings(places), &strings(people)), *expected, "album_title({kind}, {places:?}, {people:?})" ); } } /// Seven `albumPeople` answers read out of Node. /// /// The two that a hand-written expectation gets wrong: an id the caller cannot /// NAME is skipped rather than counted against the cap, so a member set where /// `ghost` is the most frequent still names Asha; and a person whose display /// name is the EMPTY string is treated as unnamed, because `if (!name)` is /// falsy for `""`. #[test] fn album_people_matches_the_typescript() { type PeopleCase<'a> = (&'a [&'a [&'a str]], &'a [&'a str], &'a [&'a str]); let cases: &[PeopleCase<'_>] = &[ ( &[&["person-a"], &["person-a"], &["person-b"]], &["person-a"], &["Asha"], ), ( &[ &["person-a", "person-b"], &["person-a", "person-b"], &["person-a", "person-b"], &["person-c"], ], &["person-a", "person-b"], &["Asha", "Bala"], ), // A person linked twice on one picture counts once. ( &[&["person-a", "person-a"], &["person-a"]], &["person-a"], &["Asha"], ), ( &[&["ghost"], &["ghost"], &["person-a"], &["person-a"]], &["person-a"], &["Asha"], ), // Three on every member, but only two may be named. ( &[ &["person-a", "person-b", "person-c"], &["person-a", "person-b", "person-c"], ], &["person-a", "person-b"], &["Asha", "Bala"], ), ( &[ &["person-blank"], &["person-blank"], &["person-b"], &["person-b"], ], &["person-b"], &["Bala"], ), (&[&[], &[]], &[], &[]), ]; for (per_member, expected_ids, expected_names) in cases { let members: Vec> = per_member.iter().map(|ids| strings(ids)).collect(); let (ids, people) = album_people(&members, names); assert_eq!( (ids, people), (strings(expected_ids), strings(expected_names)), "album_people({per_member:?})" ); } } // ── suppression — D4 ───────────────────────────────────────────────────────── #[test] fn measures_overlap_against_the_smaller_set() { assert_eq!( overlap_share(&strings(&["a", "b", "c", "d"]), &strings(&["c", "d"])), 1.0 ); assert_eq!( overlap_share( &strings(&["a", "b", "c", "d"]), &strings(&["d", "e", "f", "g"]) ), 0.25 ); assert_eq!(overlap_share(&[], &strings(&["a"])), 0.0); // A repeated member counts once: both sides are SETS. assert_eq!( overlap_share(&strings(&["a", "a", "b"]), &strings(&["a"])), 1.0 ); assert_eq!( overlap_share(&strings(&["a", "b", "c"]), &strings(&["a", "b", "c"])), 1.0 ); } #[test] fn names_the_decided_album_a_fresh_proposal_is_suppressed_by() { let decided = vec![ DecidedAlbum { id: "album:event:2026-03-14T19".to_string(), members: strings(&["a", "b", "c", "d"]), }, DecidedAlbum { id: "album:trip:2026-04-10".to_string(), members: strings(&["p", "q", "r", "s", "t", "u"]), }, ]; // Drift: the cluster grew by four and lost none — half of the old set. assert_eq!( suppressed_by(&strings(&["a", "b", "e", "f", "g", "h"]), &decided).as_deref(), Some("album:event:2026-03-14T19") ); // The new one is small and mostly old. assert_eq!( suppressed_by(&strings(&["p", "q", "z"]), &decided).as_deref(), Some("album:trip:2026-04-10") ); // One shared picture out of many: a different thing. assert_eq!( suppressed_by(&strings(&["a", "x", "y", "z", "w"]), &decided), None ); assert_eq!(suppressed_by(&strings(&["n"]), &[]), None); } // ── the whole derivation, as Node printed it ──────────────────────────────── /// Twelve whole `deriveAlbums` answers, pinned as the JSON the TypeScript /// produced (`tests/fixtures/media_albums.json`). /// /// A clustering rule is not something three assertions hold still: the anchors, /// the titles, the covers, the member LISTS in their order, the eligible count /// and the four refusal counts all have to agree at once, and any one of them /// drifting is an album the owner is offered twice or not at all. Regenerate /// the fixture in the same PR as any change to the TypeScript. /// /// `wide` is the one that earns its keep: a video among the photos, a row with /// no offset of its own falling back to the workspace zone, a `taken_at` /// nothing can parse (stepped over WITHOUT a refusal count, because a broken /// row is not a reason the owner could act on), and one of each of the three /// counted refusals. #[test] fn every_derivation_matches_the_golden_read_out_of_node() { let raw = include_str!("../../../tests/fixtures/media_albums.json"); let fixture: HashMap = serde_json::from_str(raw).expect("the albums fixture parses"); let mut scenarios: Vec<(&str, Vec, Option)> = Vec::new(); let mut c = Candidates::new(); let mut party = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T13:30:00.000Z", 10, |candidate| candidate.place_name = Some("Koramangala".to_string()), ); let mut shot = c.one(); shot.taken_at = "2026-03-14T14:00:00.000Z".to_string(); shot.subtypes = strings(&["screenshot"]); party.push(shot); scenarios.push(("party", party, Some(home()))); let mut c = Candidates::new(); let mut two = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T04:00:00.000Z", 5, |_| {}, ); two.extend(c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T12:00:00.000Z", 5, |_| {}, )); scenarios.push(("twoClusters", two, Some(home()))); let mut c = Candidates::new(); let mut jump = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T05:00:00.000Z", 5, |_| {}, ); jump.extend(c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T06:00:00.000Z", 5, |candidate| { candidate.latitude = Some(HOME_LAT + 0.05); candidate.longitude = Some(HOME_LNG); }, )); scenarios.push(("placeJump", jump, Some(home()))); let mut c = Candidates::new(); let mut split = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T07:00:00.000Z", 5, |candidate| candidate.people = strings(&["person-a"]), ); split.extend(c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T09:00:00.000Z", 5, |candidate| candidate.people = strings(&["person-b"]), )); scenarios.push(("peopleSplit", split, Some(home()))); let mut c = Candidates::new(); let mut cover = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T13:00:00.000Z", 10, |candidate| candidate.people = strings(&["person-a", "person-b", "person-c"]), ); cover[3].aesthetic_score = Some(0.9); let cover: Vec = cover .into_iter() .enumerate() .map(|(i, mut candidate)| { candidate.people = if i < 2 { strings(&["person-a", "person-b", "person-c", "ghost"]) } else { strings(&["person-a", "person-b"]) }; candidate }) .collect(); scenarios.push(("cover", cover, Some(home()))); let mut c = Candidates::new(); let mut trip = c.day("2026-04-10", 5, |_| {}); trip.extend(c.day("2026-04-11", 5, |_| {})); trip.extend(c.day("2026-04-12", 2, |_| {})); scenarios.push(("trip", trip, Some(home()))); let mut c = Candidates::new(); let mut bridged = c.day("2026-04-10", 5, |_| {}); bridged.extend(c.burst(2, "2026-04-11T05:00:00.000Z", 20, |candidate| { candidate.latitude = None; candidate.longitude = None; candidate.place_city = None; })); bridged.extend(c.day("2026-04-12", 5, |_| {})); scenarios.push(("tripBridged", bridged, Some(home()))); let mut c = Candidates::new(); let mut abroad = c.day("2026-05-01", ALBUM_EVENT_MIN_MEMBERS, |candidate| { candidate.latitude = Some(HOME_LAT + 0.1); candidate.longitude = Some(HOME_LNG); candidate.place_city = Some("Colombo".to_string()); candidate.place_country = Some("Sri Lanka".to_string()); }); abroad.extend(c.day("2026-05-02", 4, |candidate| { candidate.latitude = Some(HOME_LAT + 0.1); candidate.longitude = Some(HOME_LNG); candidate.place_city = Some("Galle".to_string()); candidate.place_country = Some("Sri Lanka".to_string()); })); scenarios.push(("abroad", abroad, Some(home()))); let mut c = Candidates::new(); let mut ordering = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-06-01T05:00:00.000Z", 5, |_| {}, ); ordering.extend(c.day("2026-04-10", 5, |_| {})); ordering.extend(c.day("2026-04-11", ALBUM_TRIP_MIN_MEMBERS, |_| {})); scenarios.push(("ordering", ordering, Some(home()))); let mut c = Candidates::new(); let midnight = c.burst( ALBUM_EVENT_MIN_MEMBERS, "2026-03-14T17:50:00.000Z", 10, |_| {}, ); scenarios.push(("midnight", midnight, Some(home()))); let mut c = Candidates::new(); let mut wide = c.burst(4, "2026-07-04T03:00:00.000Z", 7, |candidate| { candidate.people = strings(&["person-a"]); candidate.aesthetic_score = Some(0.5); }); wide.extend(c.burst(4, "2026-07-04T03:30:00.000Z", 7, |candidate| { candidate.kind = MediaFamily::Video; candidate.people = strings(&["person-a"]); candidate.aesthetic_score = Some(0.5); candidate.favourite = true; })); let mut unreadable = c.one(); unreadable.taken_at = "not-a-date".to_string(); wide.push(unreadable); let mut no_offset = c.one(); no_offset.taken_at = "2026-07-04T04:10:00.000Z".to_string(); no_offset.taken_offset = None; no_offset.people = strings(&["person-a"]); no_offset.place_name = Some("Cubbon Park".to_string()); wide.push(no_offset); let mut copy = c.one(); copy.taken_at = "2026-07-04T04:20:00.000Z".to_string(); copy.confirmed_copy = true; wide.push(copy); let mut utility = c.one(); utility.taken_at = "2026-07-04T04:30:00.000Z".to_string(); utility.is_utility = Some(1); wide.push(utility); let mut sent = c.one(); sent.taken_at = "2026-07-04T04:40:00.000Z".to_string(); sent.own_library = false; sent.camera_make = None; sent.latitude = None; sent.longitude = None; wide.push(sent); scenarios.push(("wide", wide, Some(home()))); let mut c = Candidates::new(); let mut no_home = c.day("2026-04-10", 5, |_| {}); no_home.extend(c.day("2026-04-11", 5, |_| {})); scenarios.push(("noHome", no_home, None)); assert_eq!( scenarios.len(), fixture.len(), "every fixture scenario is built here" ); for (name, candidates, album_home) in scenarios { let expected = fixture .get(name) .unwrap_or_else(|| panic!("the fixture holds a `{name}` scenario")); let result = derive(&candidates, album_home.as_ref()); // The fixture holds each title as Node said it; ours is a typed fact, // compared in the kit's words. let mut value = serde_json::to_value(&result).expect("serialises"); for (proposal, said) in value["proposals"].as_array_mut().into_iter().flatten().zip(&result.proposals) { proposal["title"] = Value::from(said.title.say(&[])); } assert_eq!( &value, expected, "deriveAlbums({name})" ); } } #[test] fn the_wire_shape_is_the_typescript_object() { let proposal = AlbumProposal { kind: MediaAlbumKind::Event, anchor: "2026-03-14T19".to_string(), title: AlbumTitle::Place { places: vec!["Koramangala".to_string()], names: Vec::new() }, starts_at: "2026-03-14".to_string(), ends_at: "2026-03-14".to_string(), home_label: None, cover_id: "photo:a".to_string(), people: Vec::new(), members: vec![AlbumMember { id: "photo:a".to_string(), kind: MediaFamily::Photo, sort_at: "2026-03-14T13:30:00.000Z".to_string(), }], }; assert_eq!( serde_json::to_string(&proposal).expect("serialises"), r#"{"kind":"event","anchor":"2026-03-14T19","title":{"form":"place","places":["Koramangala"],"names":[]},"startsAt":"2026-03-14","endsAt":"2026-03-14","homeLabel":null,"coverId":"photo:a","people":[],"members":[{"id":"photo:a","kind":"photo","sortAt":"2026-03-14T13:30:00.000Z"}]}"# ); } /// RULE: an album's title is said in the database's `albums` lines — a /// rewording or a different joining word is a row, never a build. #[test] fn an_album_title_is_said_in_the_databases_words() { use crate::rules::shell_lines::LineRow; let row = |line: &str, words: &str| LineRow { set: "albums".into(), line: line.into(), words: words.into() }; let rows = [row("join", "{a} & {b}"), row("title.trip_with", "Away with {names}")]; let title = album_title(MediaAlbumKind::Trip, &[], &strings(&["Asha", "Bala"])); assert_eq!(title.say(&rows), "Away with Asha & Bala"); assert_eq!(title.say(&[]), "A trip with Asha and Bala"); }