Cotton code
566 lines · 27.1 KB · RustRaw
//! The Photos page, decided on the Mac over the importer's own copy//! (`cotton_mac::photos`), as the Worker's `/v1/import/photos` decided it//! (apps/business/test/import-photos.test.ts, ported case by case): one//! asset, the four rules of who each cluster is, one page. Every picture is a//! handful of invented bytes and every name is invented.mod support;use std::path::PathBuf;use std::sync::Arc;use cotton_client::ingest::sources::photos::apple::AppleFaceRow;use cotton_client::ingest::sources::photos::PhotoWork;use cotton_client::ingest::{IngestBatch, IngestNotes, IngestWork};use cotton_client::seal::HeldDataKeys;use cotton_mac::copy::{Change, Copy};use cotton_mac::ids;use cotton_mac::object::{Act, ObjectClient};use cotton_mac::photos;use cotton_mac::sink::{ObjectSink, Sent};use cotton_store::protocol::derived_id::{media_face_id, media_sighting_id, photo_record_id};use serde_json::{json, Map, Value};use support::fixture;use support::object::{kit_table, FakeObject};const DB: &str = "00000000-0000-4000-8000-000000000001";fn tables() -> Vec<Value> {    [        "person",        "person_handle",        "message_contact",        "message_contact_handle",        "thread",        "thread_member",        "message",        "message_reaction",        "call",        "photo",        "video",        "sighting",        "face",        "person_source",        "seal_key",    ]    .into_iter()    .map(kit_table)    .collect()}fn uuid_of(n: u64) -> String {    format!("00000000-0000-4000-8000-{:012X}", n)}/// Core Data seconds of `2026-08-14T09:00:00.000Z`.const AUG_14: f64 = (1_786_698_000_000.0 - 978_307_200_000.0) / 1000.0;/// One asset's row, as the Worker test's `row(n, over)`.fn row(n: u64, over: Value) -> Value {    let mut row = json!({        "pk": n, "uuid": uuid_of(n), "kind": 0, "kindSubtype": 0, "uti": "public.jpeg", "directory": "0",        "filename": format!("{}.jpeg", uuid_of(n)), "savedAssetType": 6, "dateCreated": AUG_14, "timezoneOffset": 19_800,        "latitude": -180, "longitude": -180, "width": 4000, "height": 3000, "orientation": 1, "favorite": 0, "hdrType": 0,        "depthType": 0, "adjustmentsState": 0, "avalancheUuid": null, "isDetectedScreenshot": 0, "cameraCaptureDevice": 0,        "cameraMake": null, "cameraModel": null, "originalFilename": null, "overallAestheticScore": 0.5, "curationScore": 0.5,        "sceneAnalysisVersion": 0, "title": null, "longDescription": null,    });    for (key, value) in over.as_object().cloned().unwrap_or_default() {        row[key] = value;    }    row}fn face(uuid: &str, person_uuid: Option<&str>, over: Value) -> Value {    let mut face = json!({        "uuid": uuid, "assetPk": 1, "centerX": 0.5, "centerY": 0.6, "size": 0.1, "quality": 0.51,        "personPk": person_uuid.map(|_| 10), "personUuid": person_uuid, "isInTrash": 0, "hidden": 0,    });    for (key, value) in over.as_object().cloned().unwrap_or_default() {        face[key] = value;    }    face}fn cluster(uuid: &str, full_name: Option<&str>, contact: Option<&str>) -> Value {    json!({ "person": { "pk": 1, "uuid": uuid, "fullName": full_name, "displayName": null, "faceCount": 1, "mergeTargetPk": null }, "contactIdentifier": contact })}fn sha(text: &str) -> String {    ids::sha256_hex(text.as_bytes())}struct World {    object: FakeObject,    client: ObjectClient,    copy: Copy,    library: PathBuf,    _dir: tempfile::TempDir,}impl World {    fn new() -> World {        let object = FakeObject::start(DB, "+919800000000", tables());        let keys = HeldDataKeys::new();        keys.hold(DB, &cotton_core::seal::DataKey::from_bytes([7; 32]));        let files = Arc::new(cotton_client::media::sealed::PersonFiles::new(DB, keys.clone()));        let client = ObjectClient::new(object.server.url.clone(), Some("device-token".into())).unwrap().sealing_files(files);        let dir = tempfile::tempdir().unwrap();        let copy = Copy::open(&dir.path().join("copy.db"), DB, keys).unwrap();        let library = dir.path().join("library");        std::fs::create_dir_all(&library).unwrap();        World { object, client, copy, library, _dir: dir }    }    /// The asset's original on this Mac, holding `text`.    fn original(&self, row: &Value, text: &str) {        let dir = self.library.join("originals").join(row["directory"].as_str().unwrap_or("0"));        std::fs::create_dir_all(&dir).unwrap();        std::fs::write(dir.join(row["filename"].as_str().unwrap()), text).unwrap();    }    /// One asset, its original written when `text` is given.    fn asset(&self, row: Value, faces: Vec<Value>, text: Option<&str>) -> Value {        if let Some(text) = text {            self.original(&row, text);        }        json!({ "row": row, "place": { "labels": [] }, "faces": faces })    }    fn post(&self, assets: Vec<Value>, clusters: Value) -> Sent {        let mut work: PhotoWork = serde_json::from_value(json!({ "library": "/nowhere", "assets": assets, "clusters": clusters })).unwrap();        work.library_path = self.library.clone();        self.send(work)    }    fn send(&self, work: PhotoWork) -> Sent {        let sink = ObjectSink::new(&self.client, DB).with_copy(&self.copy);        sink.send(IngestBatch { work: IngestWork::Photos(Box::new(work)), read: 1, cursor: None }).unwrap()    }    fn rows(&self, table: &str) -> Vec<(String, Map<String, Value>)> {        self.object.state.lock().unwrap().live(table).into_iter().map(|(id, held)| (id, held.data)).collect()    }    fn row(&self, table: &str, id: &str) -> Option<Map<String, Value>> {        self.rows(table).into_iter().find(|(held, _)| held == id).map(|(_, data)| data)    }    fn face_by_source(&self, source_id: &str) -> Map<String, Value> {        self.rows("face").into_iter().map(|(_, d)| d).find(|d| d["source_id"] == source_id).expect("the face landed")    }}fn notes(pairs: &[(&str, i64)]) -> IngestNotes {    pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect()}// ── the ids the Rust and the Worker both pin ───────────────────────────────#[test]fn derives_the_ids_the_worker_pins() {    assert_eq!(media_face_id("photo", "photo:abc", "photos", "face-1"), "99c1ec2f-36e9-8b84-a0ec-44d2c08cdd42");    assert_eq!(media_sighting_id("photo", "photo:abc", "photos", Some("asset-1")), "01498773-468c-f700-b661-2a96d59cb37b");    assert_eq!(photos::normalise_name("  Test \t  Person "), "test person");}// ── one face ───────────────────────────────────────────────────────────────fn apple_face(uuid: &str, person_uuid: Option<&str>, over: Value) -> AppleFaceRow {    serde_json::from_value(face(uuid, person_uuid, over)).unwrap()}#[test]fn a_face_lands_with_its_box_its_cluster_and_its_person() {    let record = format!("photo:{}", "a".repeat(64));    let now = "2026-09-08T09:00:00.000Z";    let changes = photos::face_changes("photo", &record, &apple_face("F1", Some("P-A"), json!({})), Some("P-A"), Some("p-a"), now);    assert_eq!(changes.len(), 1);    assert_eq!(changes[0].id, media_face_id("photo", &record, "apple", "F1"));    let patch = changes[0].patch.as_ref().unwrap();    for (key, want) in [("record_kind", json!("photo")), ("record_id", json!(record)), ("source", json!("apple")), ("source_id", json!("F1")), ("quality", json!(0.51)), ("cluster_id", json!("P-A")), ("person_id", json!("p-a"))] {        assert_eq!(patch[key], want, "{key}");    }    assert!((patch["x"].as_f64().unwrap() - 0.4).abs() < 1e-9 && (patch["y"].as_f64().unwrap() - 0.3).abs() < 1e-9);    assert!((patch["w"].as_f64().unwrap() - 0.2).abs() < 1e-9 && (patch["h"].as_f64().unwrap() - 0.2).abs() < 1e-9);    // Nobody has named it: it still lands, pointing at no one, and -1 is not a quality.    let unnamed = photos::face_changes("photo", &record, &apple_face("F1", None, json!({ "quality": -1 })), None, None, now);    assert_eq!(unnamed.len(), 1);    let patch = unnamed[0].patch.as_ref().unwrap();    assert_eq!((&patch["person_id"], &patch["cluster_id"], &patch["quality"]), (&Value::Null, &Value::Null, &Value::Null));    // In the bin or hidden is not written at all, and one with no area is dropped.    for over in [json!({ "isInTrash": 1 }), json!({ "hidden": 1 }), json!({ "size": 0 })] {        assert!(photos::face_changes("photo", &record, &apple_face("F1", None, over), None, None, now).is_empty());    }}#[test]fn keeps_the_first_change_for_a_row_reached_twice() {    let change = |table: &str, n: i64| Change { table: table.into(), id: "x".into(), patch: Some(json!({ "n": n }).as_object().cloned().unwrap()) };    let kept = photos::one_per_row(vec![change("photo", 1), change("sighting", 2), change("photo", 3)]);    assert_eq!(kept.iter().map(|c| c.patch.as_ref().unwrap()["n"].as_i64().unwrap()).collect::<Vec<_>>(), vec![1, 2]);}// ── one page ───────────────────────────────────────────────────────────────#[test]fn the_fixture_page_lands_its_photo_sighting_face_and_person_and_never_posts_the_import() {    let w = World::new();    let mut work: PhotoWork = serde_json::from_value(fixture("photos")).unwrap();    let filename = work.assets[0].row.filename.clone().unwrap();    std::fs::create_dir_all(w.library.join("originals/B")).unwrap();    std::fs::write(w.library.join("originals/B").join(&filename), "foo").unwrap();    work.library_path = w.library.clone();    let sent = w.send(work.clone());    assert_eq!(sent.notes, notes(&[("read:photosImported", 1), ("read:photosLabelled", 1), ("read:photosPerson:created", 1)]));    assert!(w.object.server.lines().iter().all(|line| !line.contains("/v1/import/")), "{:?}", w.object.server.lines());    let sha = sha("foo");    let id = photo_record_id(&sha);    let key = format!("{DB}/photos/{sha}.heic");    let photo = w.row("photo", &id).expect("the photo landed");    let want = json!({        "key": key, "sha256": sha, "content_type": "image/heic", "size_bytes": 3, "width": 4032, "height": 3024,        "taken_at": cotton_client::ingest::sources::photos::apple::apple_date_to_iso(Some(782000000.5)), "favourite": true,        "latitude": 30.4532, "longitude": 78.0712, "place_name": "Trailhead", "place_city": "Mussoorie", "camera_model": "iPhone 17 Pro",        "original_filename": "IMG_0101.HEIC", "aesthetic_score": 0.81, "curation_score": 0.6, "subtypes": [], "labels": ["Mountain", "Sky"], "caption": null,    });    for (k, v) in want.as_object().unwrap() {        assert_eq!(&photo[k], v, "photo.{k}");    }    let uuid = "B0B0B0B0-0000-4000-8000-000000000101";    let sightings = w.rows("sighting");    assert_eq!(sightings.len(), 1);    assert_eq!(sightings[0].0, media_sighting_id("photo", &id, "apple_library", Some(uuid)));    assert_eq!(Value::Object(sightings[0].1.clone()), json!({ "record_kind": "photo", "record_id": id, "source": "apple_library", "source_id": uuid, "key": key, "seen_at": photo["taken_at"] }));    let people = w.rows("person");    assert_eq!(people.len(), 1);    assert_eq!(people[0].1["full_name"], "Asha Example");    assert_eq!(people[0].1["contact_source"], "apple_library");    assert_eq!(people[0].1["device_contact_id"], "C0C0C0C0-0000-4000-8000-0000000000C7:ABPerson");    let faces = w.rows("face");    assert_eq!(faces.len(), 1);    assert_eq!(faces[0].0, media_face_id("photo", &id, "apple", "F0F0F0F0-0000-4000-8000-000000000F01"));    assert_eq!(faces[0].1["cluster_id"], "A7C1D2E3-0000-4000-8000-0000000000A7");    assert_eq!(faces[0].1["person_id"], json!(people[0].0));    assert_eq!(faces[0].1["quality"], 0.73);    // The same page again writes no second row.    let again = w.send(work.clone());    // Found again by the source the first pass kept (PEOPLE BUILD 2: the source first).    assert_eq!(again.notes, notes(&[("read:photosAlready", 1), ("read:photosLabelled", 1), ("read:photosPerson:bySource", 1)]));    assert_eq!((w.rows("photo").len(), w.rows("sighting").len(), w.rows("person").len()), (1, 1, 1));    // What Apple learned between runs is re-written, but never its star.    let mut moved = work.clone();    moved.assets[0].row.favorite = Some(0);    moved.assets[0].row.overall_aesthetic_score = Some(0.9);    assert_eq!(w.send(moved).notes["read:photosAlready"], 1);    let photo = w.row("photo", &id).unwrap();    assert_eq!((&photo["favourite"], &photo["aesthetic_score"]), (&json!(true), &json!(0.9)));    // A star the phone took off stays off while the Mac's library still holds it.    w.client.act(Act::Update, "photo", &id, &json!({ "favourite": false })).unwrap();    assert_eq!(w.send(work).notes["read:photosAlready"], 1);    assert_eq!(w.row("photo", &id).unwrap()["favourite"], false);}#[test]fn an_empty_page_asks_nothing_and_writes_nothing() {    let w = World::new();    let sent = w.post(vec![], json!({}));    assert_eq!(sent, Sent::default());    assert!(w.object.server.lines().is_empty());}#[test]fn an_original_not_on_this_mac_is_counted_rather_than_failed() {    let w = World::new();    let sent = w.post(vec![w.asset(row(2, json!({})), vec![], None)], json!({}));    assert_eq!(sent.notes, notes(&[("notDownloaded", 1)]));    assert!(w.rows("photo").is_empty());    // A sha the page carried in is not bytes this pass put.    let mut work: PhotoWork = serde_json::from_value(json!({ "library": "/nowhere", "assets": [w.asset(row(3, json!({})), vec![], None)], "clusters": {} })).unwrap();    work.assets[0].sha256 = Some(sha("never put"));    work.library_path = w.library.clone();    assert_eq!(w.send(work).notes, notes(&[("notDownloaded", 1)]));    assert!(w.rows("photo").is_empty());}#[test]fn a_type_the_limits_do_not_admit_is_counted_by_its_own_name_and_so_is_a_kind_that_disagrees() {    let w = World::new();    let text = Some("a synthetic picture");    let sent = w.post(        vec![            w.asset(row(4, json!({ "uti": "public.tiff" })), vec![], text),            w.asset(row(5, json!({ "uti": null })), vec![], text),            w.asset(row(6, json!({ "kind": 1 })), vec![], text),        ],        json!({}),    );    assert_eq!(sent.notes, notes(&[("unsupported:public.tiff", 1), ("unsupported:(no type)", 1), ("unsupported:public.jpeg", 1)]));    assert!(w.rows("photo").is_empty());    // Nothing refused before its bytes was read or put.    assert!(w.object.server.lines().iter().all(|line| !line.starts_with("PUT")));}#[test]fn an_unrecognised_directory_shape_is_named_rather_than_guessed() {    let w = World::new();    let sent = w.post(vec![w.asset(row(7, json!({ "directory": "??" })), vec![], None)], json!({}));    assert_eq!(sent.notes, notes(&[("unlocatable:an unrecognised directory shape \"??\"", 1)]));}#[test]fn an_unknown_subtype_is_counted_and_the_asset_still_imports() {    let w = World::new();    let sent = w.post(vec![w.asset(row(8, json!({ "kindSubtype": 100 })), vec![], Some("a synthetic picture"))], json!({}));    assert_eq!(sent.notes, notes(&[("read:photosUnknownSubtype", 1), ("read:photosImported", 1)]));    let sha = sha("a synthetic picture");    let photo = w.row("photo", &photo_record_id(&sha)).unwrap();    assert_eq!(photo["key"], format!("{DB}/photos/{sha}.jpg"));    assert_eq!(photo["content_type"], "image/jpeg");    assert_eq!(photo["size_bytes"], 19);    assert_eq!(photo["taken_at"], "2026-08-14T09:00:00.000Z");    assert_eq!(photo["subtypes"], json!([]));}#[test]fn a_second_sighting_of_bytes_already_here_makes_no_second_row() {    let w = World::new();    let text = Some("a synthetic picture");    w.post(vec![w.asset(row(8, json!({})), vec![], text)], json!({}));    let sent = w.post(vec![w.asset(row(9, json!({})), vec![], text)], json!({}));    assert_eq!(sent.notes, notes(&[("read:photosMerged", 1)]));    let id = photo_record_id(&sha("a synthetic picture"));    assert_eq!(w.rows("photo").len(), 1);    assert_eq!(w.rows("sighting").iter().filter(|(_, s)| s["record_id"] == id).count(), 2);}#[test]fn a_picture_the_owner_removed_stays_removed_by_its_sighting_and_by_its_bytes() {    let w = World::new();    let text = Some("a picture to remove");    w.post(vec![w.asset(row(10, json!({})), vec![], text)], json!({}));    let id = photo_record_id(&sha("a picture to remove"));    w.client.act(Act::Delete, "photo", &id, &json!({})).unwrap();    let again = w.post(vec![w.asset(row(10, json!({})), vec![face("F9", None, json!({}))], text)], json!({}));    assert_eq!(again.notes, notes(&[("read:photosRemoved", 1)]));    let elsewhere = w.post(vec![w.asset(row(11, json!({})), vec![], text)], json!({}));    assert_eq!(elsewhere.notes, notes(&[("read:photosRemoved", 1)]));    assert!(w.row("photo", &id).is_none());    assert!(w.rows("face").iter().all(|(_, f)| f["source_id"] != "F9"));}#[test]fn a_video_is_filed_under_videos_as_a_video() {    let w = World::new();    let sent = w.post(vec![w.asset(row(12, json!({ "kind": 1, "uti": "com.apple.quicktime-movie", "filename": "film.mov" })), vec![], Some("a synthetic film"))], json!({}));    assert_eq!(sent.notes, notes(&[("read:photosImported", 1)]));    let sha = sha("a synthetic film");    let key = format!("{DB}/videos/{sha}.mov");    let video = w.row("video", &format!("video:{sha}")).expect("the video landed");    assert_eq!((&video["key"], &video["content_type"]), (&json!(key), &json!("video/quicktime")));    assert!(w.rows("photo").is_empty());    // Its original went up sealed under the key its row names.    assert!(w.object.state.lock().unwrap().media.contains_key(&key));}// ── faces and people on one page ───────────────────────────────────────────#[test]fn two_faces_of_one_person_in_one_picture_write_two_faces_and_one_person() {    let w = World::new();    let sent = w.post(        vec![w.asset(row(1, json!({})), vec![face("face-1", Some("cluster-a"), json!({})), face("face-2", Some("cluster-a"), json!({ "centerX": 0.2 }))], Some("a synthetic picture"))],        json!({ "cluster-a": cluster("cluster-a", Some("Nila Rao"), None) }),    );    let people = w.rows("person");    assert_eq!(people.len(), 1);    let faces = w.rows("face");    assert_eq!(faces.len(), 2);    assert!(faces.iter().all(|(_, f)| f["person_id"] == json!(people[0].0)));    // Counted per face, decided once per cluster.    assert_eq!(sent.notes["read:photosPerson:created"], 2);}#[test]fn a_cluster_nobody_named_lands_its_faces_pointing_at_no_one() {    let w = World::new();    let sent = w.post(vec![w.asset(row(1, json!({})), vec![face("face-1", Some("cluster-a"), json!({}))], Some("a synthetic picture"))], json!({ "cluster-a": cluster("cluster-a", None, None) }));    assert_eq!(sent.notes["read:photosPerson:unnamed"], 1);    assert!(w.rows("person").is_empty());    let f = w.face_by_source("face-1");    assert_eq!((&f["person_id"], &f["cluster_id"]), (&Value::Null, &json!("cluster-a")));}#[test]fn a_face_whose_cluster_the_page_does_not_carry_lands_with_no_cluster_and_no_person() {    let w = World::new();    w.post(vec![w.asset(row(1, json!({})), vec![face("face-1", Some("elsewhere"), json!({}))], Some("a synthetic picture"))], json!({}));    let f = w.face_by_source("face-1");    assert_eq!((&f["person_id"], &f["cluster_id"]), (&Value::Null, &Value::Null));}// ── who each cluster is ────────────────────────────────────────────────────struct People {    w: World,    asset: std::cell::Cell<u64>,}impl People {    /// A fresh object holding `people` and Apple faces `(cluster, person)`.    fn new(people: &[(&str, Value)], faces: &[(&str, Option<&str>)]) -> People {        let w = World::new();        for (id, data) in people {            let mut data = data.clone();            data["contact_source"] = json!("manual");            w.object.put_row("person", id, data);        }        for (i, (cluster, person)) in faces.iter().enumerate() {            w.object.put_row(                "face",                &format!("face-{i}"),                json!({ "record_kind": "photo", "record_id": format!("photo:{}", "a".repeat(64)), "source": "apple", "source_id": format!("F{i}"), "x": 0.1, "y": 0.1, "w": 0.2, "h": 0.2, "cluster_id": cluster, "person_id": person }),            );        }        People { w, asset: std::cell::Cell::new(100) }    }    /// One picture whose face carries `uuid`: the answer and the person its face names.    fn resolve(&self, uuid: &str, name: Option<&str>, contact: Option<&str>) -> (Sent, Value) {        let n = self.asset.get() + 1;        self.asset.set(n);        let face_id = format!("face-{n}");        let sent = self.w.post(vec![self.w.asset(row(n, json!({})), vec![face(&face_id, Some(uuid), json!({}))], Some(&format!("picture {n}")))], json!({ uuid: cluster(uuid, name, contact) }));        let person = self.w.face_by_source(&face_id)["person_id"].clone();        (sent, person)    }}// RULE (PEOPLE BUILD 2): a Photos person kept before is found by its source// first (`person_source`), even after the owner renamed the contact and a// namesake now carries Apple's name; a person the pass names keeps its source.#[test]fn rule_0_a_photos_person_kept_before_is_found_by_its_source() {    let p = People::new(&[("p-a", json!({ "full_name": "Renamed By Hand" })), ("p-b", json!({ "full_name": "Test Person" }))], &[]);    p.w.object.put_row("person_source", "src-1", json!({ "person": "p-a", "kind": "apple_photos", "device": "", "source_id": "C", "name": "Test Person" }));    let (sent, person) = p.resolve("C", Some("Test Person"), None);    assert_eq!(person, "p-a");    assert_eq!(sent.notes["read:photosPerson:bySource"], 1);    assert_eq!(p.w.rows("person_source").len(), 1, "a source found is not written again");    let (_, made) = p.resolve("D", Some("Someone New"), None);    let kept: Vec<_> = p.w.rows("person_source").into_iter().map(|(_, d)| d).filter(|d| d["source_id"] == "D").collect();    assert_eq!(kept.len(), 1);    assert_eq!((&kept[0]["person"], &kept[0]["kind"], &kept[0]["device"]), (&made, &json!("apple_photos"), &json!("")));    let (again, person) = p.resolve("D", Some("Someone New"), None);    assert_eq!(person, made);    assert_eq!(again.notes["read:photosPerson:bySource"], 1);}#[test]fn rule_1_reuses_the_person_its_faces_already_point_at_the_majority_when_the_owner_split_it() {    let p = People::new(&[("p-a", json!({ "full_name": "Someone" })), ("p-b", json!({ "full_name": "Somebody Else" }))], &[("C", Some("p-a")), ("C", Some("p-b")), ("C", Some("p-a"))]);    let (sent, person) = p.resolve("C", Some("Whatever Apple Says"), None);    assert_eq!(person, "p-a");    assert_eq!(sent.notes["read:photosPerson:existing"], 1);}#[test]fn rule_2_the_contacts_card_photos_matched() {    let p = People::new(&[("p-a", json!({ "full_name": "A Different Spelling", "device_contact_id": "CARD-1" }))], &[]);    let (sent, person) = p.resolve("C", Some("Some Name"), Some("CARD-1"));    assert_eq!(person, "p-a");    assert_eq!(sent.notes["read:photosPerson:byContact"], 1);    assert_eq!(p.w.rows("person").len(), 1);}#[test]fn rule_3_exactly_one_active_person_with_that_name_spelled_anyhow() {    let p = People::new(&[("p-a", json!({ "full_name": "test   person" })), ("p-old", json!({ "full_name": "Test Person", "archived_at": "2026-08-02T00:00:00.000Z" }))], &[]);    let (sent, person) = p.resolve("C", Some("Test Person"), None);    assert_eq!(person, "p-a");    assert_eq!(sent.notes["read:photosPerson:byName"], 1);    assert_eq!(p.w.rows("person").len(), 2);}#[test]fn rule_4_creates_the_person_from_the_library_with_the_card_when_there_is_one() {    let p = People::new(&[], &[]);    let (sent, person) = p.resolve("C", Some("New Person"), Some("CARD-9"));    assert_eq!(sent.notes["read:photosPerson:created"], 1);    let people = p.w.rows("person");    assert_eq!(people.len(), 1);    assert_eq!(json!(people[0].0), person);    assert_eq!((&people[0].1["full_name"], &people[0].1["contact_source"], &people[0].1["device_contact_id"]), (&json!("New Person"), &json!("apple_library"), &json!("CARD-9")));}#[test]fn an_exact_name_tie_creates_the_person() {    let p = People::new(        &[            ("p-a", json!({ "full_name": "Test Person" })),            ("p-b", json!({ "full_name": "test  person" })),            ("p-old", json!({ "full_name": "Test Person", "archived_at": "2026-08-02T00:00:00.000Z" })),        ],        &[],    );    let (sent, person) = p.resolve("C", Some("Test Person"), None);    assert_eq!(sent.notes["read:photosPerson:ambiguous"], 1);    let person = person.as_str().unwrap();    assert!(!["p-a", "p-b", "p-old"].contains(&person), "a new person: {person}");    assert_eq!(p.w.rows("person").len(), 4);}#[test]fn the_person_it_created_for_a_tie_answers_the_next_cluster_with_that_name() {    let p = People::new(&[("p-a", json!({ "full_name": "Test Person" })), ("p-b", json!({ "full_name": "Test Person" }))], &[]);    let sent = p.w.post(        vec![p.w.asset(row(1, json!({})), vec![face("f-c", Some("C"), json!({})), face("f-d", Some("D"), json!({ "centerX": 0.2 }))], Some("one picture, two clusters"))],        json!({ "C": cluster("C", Some("Test Person"), None), "D": cluster("D", Some("test person"), None) }),    );    assert_eq!((sent.notes["read:photosPerson:ambiguous"], sent.notes["read:photosPerson:byName"]), (1, 1));    assert_eq!(p.w.face_by_source("f-c")["person_id"], p.w.face_by_source("f-d")["person_id"]);    assert_eq!(p.w.rows("person").len(), 3);}#[test]fn a_name_nobody_is_called_creates_one_person() {    let p = People::new(&[("p-a", json!({ "full_name": "Ravi Kumar" }))], &[]);    p.resolve("C", Some("Zeenat Quraishi"), None);    assert_eq!(p.w.rows("person").len(), 2);}#[test]fn the_next_pass_meets_a_cluster_by_the_source_the_first_pass_kept() {    let p = People::new(&[("p-a", json!({ "full_name": "Ravi Kumar" }))], &[]);    let (_, person) = p.resolve("C", Some("Ravi K"), None);    // The next pass meets the cluster again: the source the first pass kept answers (rule 0).    let (sent, again) = p.resolve("C", Some("Ravi K"), None);    assert_eq!(again, person);    assert_eq!(sent.notes["read:photosPerson:bySource"], 1);    assert_eq!(p.w.rows("person").len(), 2);}#[test]fn decides_once_per_cluster_however_many_faces_carry_it_and_a_second_cluster_of_the_name_is_answered_by_the_first() {    let p = People::new(&[], &[]);    let sent = p.w.post(        vec![p.w.asset(            row(1, json!({})),            vec![face("f-1", Some("C"), json!({})), face("f-2", Some("C"), json!({ "centerX": 0.2 })), face("f-3", Some("D"), json!({ "centerX": 0.8 }))],            Some("a family picture"),        )],        json!({ "C": cluster("C", Some("New Person"), None), "D": cluster("D", Some("new  person"), None) }),    );    assert_eq!((sent.notes["read:photosPerson:created"], sent.notes["read:photosPerson:byName"]), (2, 1));    assert_eq!(p.w.rows("person").len(), 1);    let people: std::collections::BTreeSet<String> = p.w.rows("face").iter().map(|(_, f)| f["person_id"].to_string()).collect();    assert_eq!(people.len(), 1);}