Cotton code
988 lines · 68.7 KB · RustRaw
//! RULE (sealing plan L8): the Mac decides messages over its own copy and the//! object only keeps them. A WhatsApp batch arrives sealed with its blind//! tokens, a second read of it lands no new message (dedupe by the message's//! own id over the opened copy, even a copy made fresh from the object's//! sealed rows), and no word of it reaches anything the object holds or//! heard. Synthetic rows only.mod support;use std::sync::Arc;use cotton_client::ingest::{IngestBatch, IngestWork};use cotton_client::seal::HeldDataKeys;use cotton_core::import::envelope::ImportBatch;use cotton_core::import::messages_engine::MessageChange;use cotton_core::seal::{blind, blind_key, DataKey};use cotton_mac::copy::{Copy, SealDoor};use cotton_mac::object::{Act, ObjectClient, ObjectError};use cotton_mac::sink::{ObjectSink, SinkError};use serde_json::{json, Value};use support::fixture;use support::object::{kit_sealed_table, kit_table, sealed_messages, FakeObject};const DB: &str = "00000000-0000-4000-8000-000000000001";const OWNER: &str = "+919800000099";/// Every word of the fixture batch that must never reach the object.const WORDS: &[&str] = &["Leaving at six", "trailhead", "Asha Example", "Ravi Example", "Hill walk", "919800000001", "919800000002", "3EB0A1B2C3D4E5F60001", "120363000000000001"];fn key(byte: u8) -> Arc<HeldDataKeys> {    let keys = HeldDataKeys::new();    keys.hold(DB, &DataKey::from_bytes([byte; 32]));    keys}fn batch() -> IngestBatch {    let mut messages: ImportBatch = serde_json::from_value(fixture("messages")).unwrap();    // The reader hands bytes beside the batch, never keys inside it.    messages.messages[1].media = None;    IngestBatch { work: IngestWork::Messages { request: Box::new(messages), media: vec![] }, read: 2, cursor: None }}fn acts(object: &FakeObject) -> usize {    object.server.requests().iter().filter(|r| r.path == "/v1/act").count()}#[test]fn a_whatsapp_batch_arrives_sealed_with_its_tokens_and_no_word_of_it_reaches_the_object() {    let object = FakeObject::start(DB, OWNER, sealed_messages());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    let copy = Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap();    let sent = ObjectSink::new(&client, DB).with_copy(&copy).send(batch()).unwrap();    assert_eq!(sent.rows, 2);    let state = object.state.lock().unwrap();    let messages = state.live("message");    assert_eq!(messages.len(), 2, "both messages landed");    assert_eq!(state.live("thread").len(), 1);    assert_eq!(state.live("message_contact").len(), 2);    assert_eq!(state.live("thread_member").len(), 2);    assert_eq!(state.live("message_reaction").len(), 1);    let bk = blind_key(&DataKey::from_bytes([7; 32]), DB, "message").unwrap();    for (_, held) in &messages {        for column in ["sealed_enc", "dek_enc", "seal_v", "sent_at", "thread_id", "channel"] {            assert!(held.data.contains_key(column), "a message keeps {column}");        }        for column in ["body", "external_id", "direction", "meta", "reply_to_external_id"] {            assert!(!held.data.contains_key(column), "a message never keeps {column} in the clear");        }        assert!(!held.blind.is_empty(), "a sealed message carries its blind tokens");    }    // The message's own id travels as its exact (xid) token, its body as word tokens.    let xid = blind::wire(&[blind::exact_token(&bk, "external_id", "3EB0A1B2C3D4E5F60001").unwrap()]).remove(0);    assert!(messages.iter().any(|(_, held)| held.blind.contains(&xid)), "the xid token is stored");    let six = blind::wire(&[blind::word_token(&bk, "body", "leaving")]).remove(0);    assert!(messages.iter().any(|(_, held)| held.blind.contains(&six)), "a body word's token is stored");    // The handle is matched by its exact token too, never by the number.    let hbk = blind_key(&DataKey::from_bytes([7; 32]), DB, "message_contact_handle").unwrap();    let handle = state.live("message_contact_handle");    assert!(!handle.is_empty());    assert!(handle.iter().all(|(_, held)| !held.data.contains_key("value") && held.blind.len() == 1));    let token = blind::wire(&[blind::exact_token(&hbk, "value", "919800000001").unwrap()]).remove(0);    assert!(handle.iter().any(|(_, held)| held.blind.contains(&token)), "the handle's exact token is stored");    drop(state);    let everything = object.everything();    for word in WORDS {        assert!(!everything.contains(word), "{word} reached the object");    }    // The copy holds them opened, as the phone's does.    assert_eq!(copy.count("message").unwrap(), 2);}#[test]fn a_second_read_lands_no_new_message_even_over_a_copy_made_fresh_from_the_sealed_rows() {    let object = FakeObject::start(DB, OWNER, sealed_messages());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    let copy = Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap();    ObjectSink::new(&client, DB).with_copy(&copy).send(batch()).unwrap();    let ids: Vec<String> = object.state.lock().unwrap().live("message").into_iter().map(|(id, _)| id).collect();    ObjectSink::new(&client, DB).with_copy(&copy).send(batch()).unwrap();    let again: Vec<String> = object.state.lock().unwrap().live("message").into_iter().map(|(id, _)| id).collect();    assert_eq!(again, ids, "the same batch twice keeps the same two messages");    // Another Mac (or this one, its copy lost) reads the object's sealed rows,    // opens them with the key, and dedupes by the message's own id.    let fresh = Copy::open(&dir.path().join("fresh.db"), DB, key(7)).unwrap();    ObjectSink::new(&client, DB).with_copy(&fresh).send(batch()).unwrap();    let after: Vec<String> = object.state.lock().unwrap().live("message").into_iter().map(|(id, _)| id).collect();    assert_eq!(after, ids, "a fresh copy finds the sealed messages and adds none");    assert_eq!(fresh.count("message").unwrap(), 2);    assert_eq!(fresh.row("message", &ids[0]).unwrap().unwrap()["channel"], "whatsapp");}#[test]fn with_no_key_or_the_wrong_key_nothing_is_planned_and_nothing_goes_in_the_clear() {    let object = FakeObject::start(DB, OWNER, sealed_messages());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    let keyless = Copy::open(&dir.path().join("none.db"), DB, HeldDataKeys::new()).unwrap();    let refused = ObjectSink::new(&client, DB).with_copy(&keyless).send(batch()).unwrap_err();    assert!(matches!(&refused, SinkError::Copy(error) if error.code() == Some("seal_key_missing")), "{refused:?}");    assert_eq!(acts(&object), 0, "no row was sent");    assert_eq!(keyless.count("message").unwrap(), 0, "the copy kept nothing of the refused landing");    let copy = Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap();    ObjectSink::new(&client, DB).with_copy(&copy).send(batch()).unwrap();    let before = acts(&object);    // A copy whose key does not open the object's rows stops by name: an    // engine that could not see them would make them again.    let wrong = Copy::open(&dir.path().join("wrong.db"), DB, key(9)).unwrap();    let refused = ObjectSink::new(&client, DB).with_copy(&wrong).send(batch()).unwrap_err();    assert!(matches!(&refused, SinkError::Copy(error) if error.code() == Some("seal_does_not_open")), "{refused:?}");    assert_eq!(acts(&object), before, "nothing more was sent");    for word in WORDS {        assert!(!object.everything().contains(word), "{word} reached the object");    }}#[test]fn an_edit_and_a_reaction_on_a_sealed_message_reseal_it_and_say_nothing_in_the_clear() {    let object = FakeObject::start(DB, OWNER, sealed_messages());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    let copy = Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap();    let sink = ObjectSink::new(&client, DB).with_copy(&copy);    sink.send(batch()).unwrap();    let changes = vec![        MessageChange::Edit { external_id: "3EB0A1B2C3D4E5F60001".into(), body: "Leaving at seven, quokka".into(), at: "2026-10-20T00:40:00Z".into() },        MessageChange::Reaction { external_id: "3EB0A1B2C3D4E5F60001".into(), actor: "self".into(), emoji: "🎉".into(), at: "2026-10-20T00:41:00Z".into() },    ];    sink.send(IngestBatch { work: IngestWork::MessageChanges { workspace_id: DB.into(), channel: "whatsapp".into(), changes }, read: 2, cursor: None }).unwrap();    let state = object.state.lock().unwrap();    let (id, _) = state.live("message").into_iter().find(|(id, _)| copy.row("message", id).unwrap().unwrap()["external_id"] == "3EB0A1B2C3D4E5F60001").unwrap();    drop(state);    let opened = copy.row("message", &id).unwrap().unwrap();    assert_eq!(opened["body"], "Leaving at seven, quokka");    assert!(!object.everything().contains("quokka"), "the edit reached the object only sealed");    // A fresh copy opens the edited row from the object.    let fresh = Copy::open(&dir.path().join("fresh.db"), DB, key(7)).unwrap();    fresh.refresh(&client).unwrap();    assert_eq!(fresh.row("message", &id).unwrap().unwrap()["body"], "Leaving at seven, quokka");}#[test]fn open_tables_take_the_engines_patches_as_they_did() {    let tables: Vec<Value> = ["thread", "message", "thread_member", "message_reaction", "message_contact", "message_contact_handle", "person", "person_handle", "call", "seal_key"]        .into_iter()        .map(kit_table)        .collect();    let object = FakeObject::start(DB, OWNER, tables);    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    // No key is needed while no table is sealed.    let copy = Copy::open(&dir.path().join("copy.db"), DB, HeldDataKeys::new()).unwrap();    ObjectSink::new(&client, DB).with_copy(&copy).send(batch()).unwrap();    let state = object.state.lock().unwrap();    let messages = state.live("message");    assert_eq!(messages.len(), 2);    assert!(messages.iter().any(|(_, held)| held.data.get("body") == Some(&json!("Leaving at six?"))));    assert!(messages.iter().all(|(_, held)| !held.data.contains_key("sealed_enc") && held.blind.is_empty()));    // The reply links to the message it quotes, planned over the rows that just landed.    let quoted = messages.iter().find(|(_, h)| h.data.get("external_id") == Some(&json!("3EB0A1B2C3D4E5F60001"))).unwrap().0.clone();    assert!(messages.iter().any(|(_, h)| h.data.get("reply_to_id") == Some(&json!(quoted))));}/// The mail and outbox tables sealed as the plan's §1 says (and stories),/// beside the messages kit's.fn sealed_mail() -> Vec<Value> {    use support::object::{kit_sealed_table, sealed_table};    let mut tables = sealed_messages();    for table in ["email", "email_thread", "email_participant", "story"] {        tables.push(kit_sealed_table(table));    }    tables.push(sealed_table("outbox", &["status", "channel", "sent_at"], &[], &[]));    tables.push(kit_table("event"));    tables}// RULE (sealing plan L8): the Mac's plain writes (mail, stories, the// outbox's marks) to a sealed table go sealed whole over the copy's row, an// update merged onto what the copy holds; a write to an open table goes as// it always did; the object's refusals stay the object's.#[test]fn plain_writes_to_sealed_tables_go_sealed_and_a_partial_update_is_sealed_whole() {    let object = FakeObject::start(DB, OWNER, sealed_mail());    let dir = tempfile::tempdir().unwrap();    let copy = Arc::new(Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::clone(&copy)));    let mail = json!({ "thread_id": null, "external_id": "<m1@example.test>", "subject": "Zanzibar invoice", "from_email": "bills@example.test", "body": "quokka lantern", "sent_at": "2026-11-10T08:00:00.000Z", "labels": "[\"INBOX\"]", "unread": true });    client.upsert("email", "e1", &mail).unwrap();    // The importer's label patch names one column; the object gets the whole row sealed.    client.act(Act::Update, "email", "e1", &json!({ "labels": "[\"INBOX\",\"STARRED\"]", "starred": true })).unwrap();    let opened = copy.row("email", "e1").unwrap().unwrap();    assert_eq!(opened["subject"], "Zanzibar invoice");    assert_eq!(opened["labels"], "[\"INBOX\",\"STARRED\"]");    let held = object.state.lock().unwrap().live("email");    assert_eq!(held.len(), 1);    // The kit seals the email's marks too: the phone files its inbox over its own opened copy.    assert!(held[0].1.data.contains_key("sealed_enc") && !held[0].1.data.contains_key("starred"));    assert_eq!(opened["starred"], json!(true));    assert!(!held[0].1.data.contains_key("labels") && !held[0].1.data.contains_key("subject"));    let ebk = blind_key(&DataKey::from_bytes([7; 32]), DB, "email").unwrap();    let from = blind::wire(&[blind::exact_token(&ebk, "from_email", "bills@example.test").unwrap()]).remove(0);    assert!(held[0].1.blind.contains(&from), "the sender's exact token is stored");    // The object's refusals, said the object's way.    assert!(matches!(client.act(Act::Create, "email", "e1", &mail), Err(ObjectError::Refused { status: 409, ref code, .. }) if code == "duplicate_id"));    assert!(matches!(client.act(Act::Update, "email", "nope", &json!({ "unread": false })), Err(ObjectError::Refused { status: 404, .. })));    assert!(matches!(client.act(Act::Update, "email", "e1", &json!({ "colour": "red" })), Err(ObjectError::Refused { status: 400, ref code, .. }) if code == "bad_column"));    // An open table's write is the plain act it always was.    client.upsert("event", "ev1", &json!({ "title": "Open dinner" })).unwrap();    assert_eq!(object.state.lock().unwrap().live("event")[0].1.data["title"], "Open dinner");    // A story the WhatsApp reader saw lands sealed through the sink's own write.    client.upsert("story", "s1", &json!({ "source": "whatsapp", "external_id": "3EB0STATUS", "caption": "Sunrise over Zanzibar", "posted_at": "2026-11-10T06:00:00.000Z" })).unwrap();    let everything = object.everything();    for word in ["Zanzibar", "quokka", "bills@example.test", "INBOX", "Sunrise", "3EB0STATUS"] {        assert!(!everything.contains(word), "{word} reached the object");    }}#[test]fn a_sealed_outbox_row_opens_on_the_mac_and_its_marks_go_sealed() {    let object = FakeObject::start(DB, OWNER, sealed_mail());    let dir = tempfile::tempdir().unwrap();    let copy = Arc::new(Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::clone(&copy)));    // The phone queued it sealed (here, a Mac with the same key stands in for the phone).    client.upsert("outbox", "o1", &json!({ "channel": "whatsapp", "to": "+919800000001", "body": "Meet at the quokka gate", "status": "queued" })).unwrap();    assert!(!object.everything().contains("quokka"));    let queued = client.outbox("queued").unwrap();    assert_eq!(queued.len(), 1);    let row = cotton_mac::outbox::Queued::from_row(&queued[0]).unwrap();    assert_eq!((row.body.as_str(), row.to.as_str()), ("Meet at the quokka gate", "+919800000001"));    // The send's mark names the status; the row goes sealed whole, still queued no longer.    client.act(Act::Update, "outbox", "o1", &json!({ "status": "sent", "sent_external_id": "3EB0SENT" })).unwrap();    assert!(client.outbox("queued").unwrap().is_empty());    assert_eq!(copy.row("outbox", "o1").unwrap().unwrap()["body"], "Meet at the quokka gate");    let everything = object.everything();    assert!(!everything.contains("quokka") && !everything.contains("919800000001") && !everything.contains("3EB0SENT"));    // A row the phone queued after this pass's door read the object is still marked, sealed.    let phone = ObjectClient::new(object.server.url.clone(), Some("phone".into())).unwrap().sealing_with(SealDoor::over(Arc::new(Copy::open(&dir.path().join("phone.db"), DB, key(7)).unwrap())));    phone.upsert("outbox", "o2", &json!({ "channel": "whatsapp", "to": "+919800000002", "body": "Second quokka", "status": "queued" })).unwrap();    client.act(Act::Update, "outbox", "o2", &json!({ "status": "sent" })).unwrap();    assert_eq!(copy.row("outbox", "o2").unwrap().unwrap()["body"], "Second quokka");    // A Mac whose key does not open it sends nothing, by name.    let other = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::new(Copy::open(&dir.path().join("other.db"), DB, key(9)).unwrap())));    client.act(Act::Update, "outbox", "o1", &json!({ "status": "queued" })).unwrap();    assert!(matches!(other.outbox("queued"), Err(ObjectError::Refused { ref code, .. }) if code == "seal_does_not_open"));}// RULE (sealing plan L8; PEOPLE BUILD 2): calls are decided on the Mac over// its copy: a number matches the person holding it in a sealed person_handle// (who), a number nobody holds names nobody even when the phone gave a name// one person carries (never by exact name), a re-read writes the same rows,// and no number or name reaches the object.#[test]fn calls_match_people_over_the_sealed_copy_and_say_no_number_to_the_object() {    use cotton_client::ingest::DeviceCall;    let object = FakeObject::start(DB, OWNER, sealed_mail());    let dir = tempfile::tempdir().unwrap();    let copy = Arc::new(Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::clone(&copy)));    // The phone's people, sealed.    client.upsert("person", "11111111-1111-4111-8111-111111111111", &json!({ "full_name": "Asha Zanzibar" })).unwrap();    client.upsert("person", "22222222-2222-4222-8222-222222222222", &json!({ "full_name": "Ravi Quokka" })).unwrap();    client        .upsert("person_handle", "33333333-3333-4333-8333-333333333333", &json!({ "person_id": "11111111-1111-4111-8111-111111111111", "kind": "phone", "value": "+91 98000 00001", "normalised": "919800000001" }))        .unwrap();    let calls: Vec<DeviceCall> = serde_json::from_value(json!([        { "source": "callHistory", "externalId": "C1", "provider": "phone", "direction": "in", "outcome": "answered", "startedAt": "2026-10-21T04:15:00Z", "durationS": 312, "handle": "+919800000001", "handleKind": "phone", "name": null, "device": "mac-d", "meta": {} },        { "source": "callHistory", "externalId": "C2", "provider": "phone", "direction": "out", "outcome": "missed", "startedAt": "2026-10-21T05:00:00Z", "durationS": 0, "handle": "+919800000777", "handleKind": "phone", "name": "Ravi  Quokka", "device": "mac-d", "meta": {} }    ]))    .unwrap();    let sink = ObjectSink::new(&client, DB).with_copy(&copy);    sink.send(IngestBatch { work: IngestWork::Calls { calls: calls.clone() }, read: 2, cursor: None }).unwrap();    sink.send(IngestBatch { work: IngestWork::Calls { calls }, read: 2, cursor: None }).unwrap();    let held = object.state.lock().unwrap().live("call");    assert_eq!(held.len(), 2, "a re-read writes the same two rows");    let person_of = |external: &str| {        held.iter().map(|(id, _)| copy.row("call", id).unwrap().unwrap()).find(|row| row["external_id"] == external).unwrap()["person_id"].clone()    };    assert_eq!(person_of("C1"), "11111111-1111-4111-8111-111111111111", "the number's person, through the sealed handle");    assert_eq!(person_of("C2"), Value::Null, "a number nobody holds names nobody, whatever name the phone gave");    // The person link stays clear for the object's links; the number never does.    assert!(held.iter().all(|(_, h)| h.data.contains_key("person_id") && !h.data.contains_key("handle")));    let hbk = blind_key(&DataKey::from_bytes([7; 32]), DB, "call").unwrap();    let token = blind::wire(&[blind::exact_token(&hbk, "handle", "919800000001").unwrap()]).remove(0);    assert!(held.iter().any(|(_, h)| h.blind.contains(&token)), "the call's handle is found again by its exact token");    let everything = object.everything();    for word in ["919800000001", "919800000777", "Zanzibar", "Quokka", "C1\"", "callHistory"] {        assert!(!everything.contains(word), "{word} reached the object");    }}// RULE: a call imported before `call` was sealed// (an open row under its plain-namespace id) is the row a re-read lands on// once the table is sealed: its id is kept, no second row is made beside it,// and the row goes up sealed.#[test]fn a_call_imported_before_the_seal_keeps_its_row_when_read_again() {    use cotton_client::ingest::DeviceCall;    let object = FakeObject::start(DB, OWNER, sealed_mail());    let plain = cotton_mac::calls::call_id(DB, "callHistory", "C9");    object.put_row("call", &plain, json!({ "source": "callHistory", "external_id": "C9", "started_at": "2026-10-20T04:00:00Z", "direction": "in", "outcome": "answered" }));    let dir = tempfile::tempdir().unwrap();    let copy = Arc::new(Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::clone(&copy)));    let calls: Vec<DeviceCall> = serde_json::from_value(json!([        { "source": "callHistory", "externalId": "C9", "provider": "phone", "direction": "in", "outcome": "answered", "startedAt": "2026-10-20T04:00:00Z", "durationS": 60, "handle": "+919800000009", "handleKind": "phone", "name": null, "device": "mac-d", "meta": {} }    ]))    .unwrap();    let sink = ObjectSink::new(&client, DB).with_copy(&copy);    sink.send(IngestBatch { work: IngestWork::Calls { calls }, read: 1, cursor: None }).unwrap();    let held = object.state.lock().unwrap().live("call");    assert_eq!(held.len(), 1, "one row for the call: {:?}", held.iter().map(|(id, _)| id).collect::<Vec<_>>());    assert_eq!(held[0].0, plain, "the held call keeps its id");    assert!(held[0].1.data.contains_key("sealed_enc") && !held[0].1.data.contains_key("handle"), "and goes up sealed");}// RULE (sealing plan L8): a sealed message's file is sealed per file before// its PUT and kept under a random key; its file key lives only in the// message's sealed blob; the bytes the object holds open with it and say// nothing (no plaintext, no hash, no name); a re-read never puts it again.#[test]fn a_sealed_messages_file_goes_up_sealed_under_a_random_key_and_opens_with_its_row() {    use cotton_client::ingest::IngestMediaFile;    use cotton_core::seal::file;    let object = FakeObject::start(DB, OWNER, sealed_messages());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    let copy = Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap();    let picture = dir.path().join("zanzibar-beach.jpg");    let bytes: Vec<u8> = b"synthetic jpeg: quokka on the beach ".iter().cycle().take(200_000).copied().collect();    std::fs::write(&picture, &bytes).unwrap();    let with_file = || {        let mut messages: ImportBatch = serde_json::from_value(fixture("messages")).unwrap();        messages.messages[1].media = None;        let external_id = messages.messages[1].external_id.clone();        IngestBatch {            work: IngestWork::Messages {                request: Box::new(messages),                media: vec![IngestMediaFile { external_id, path: picture.clone(), name: Some("zanzibar-beach.jpg".into()), content_type: Some("image/jpeg".into()) }],            },            read: 2,            cursor: None,        }    };    let sent = ObjectSink::new(&client, DB).with_copy(&copy).send(with_file()).unwrap();    assert_eq!(sent.uploaded, 1);    let state = object.state.lock().unwrap();    assert_eq!(state.media.len(), 1);    let (key, held) = state.media.iter().next().map(|(k, v)| (k.clone(), v.clone())).unwrap();    drop(state);    assert!(file::is_sealed_key(&key), "{key}");    assert!(!held.windows(16).any(|w| w == &bytes[..16]), "the object holds no plaintext run");    // The row (opened on the Mac) names the key and carries the file key; the object's row does not.    let row = object        .state        .lock()        .unwrap()        .live("message")        .into_iter()        .map(|(id, _)| copy.row("message", &id).unwrap().unwrap())        .find(|row| row["media"].as_array().is_some_and(|m| !m.is_empty()))        .unwrap();    let media = &row["media"][0];    assert_eq!(media["key"], json!(key));    assert_eq!(media["contentType"], "image/jpeg");    let fk = file::FileKey::read(media["fileKey"].as_str().unwrap()).unwrap();    let mut opened = Vec::new();    file::open_file(&fk, &key, &mut &held[..], &mut opened).unwrap();    assert_eq!(opened, bytes, "the object's bytes open with the row's file key");    // A second read of the same batch puts nothing.    let again = ObjectSink::new(&client, DB).with_copy(&copy).send(with_file()).unwrap();    assert_eq!(again.uploaded, 0);    assert_eq!(again.notes.get("media:held"), Some(&1));    assert_eq!(object.state.lock().unwrap().media.len(), 1);    let everything = object.everything();    let sha = cotton_mac::ids::sha256_hex(&bytes);    for word in ["zanzibar-beach", "quokka", sha.as_str(), media["fileKey"].as_str().unwrap()] {        assert!(!everything.contains(word), "{word} reached the object");    }}#[test]fn one_sealed_row_opens_by_its_id_from_the_version_its_ask_named() {    let object = FakeObject::start(DB, OWNER, vec![kit_sealed_table("film"), kit_sealed_table("film_episode")]);    let dir = tempfile::tempdir().unwrap();    let phone = ObjectClient::new(object.server.url.clone(), Some("phone".into())).unwrap().sealing_with(SealDoor::over(Arc::new(Copy::open(&dir.path().join("phone.db"), DB, key(7)).unwrap())));    for (id, title) in [("f-quiet", "The Quiet Engines"), ("f-ferry", "Night Ferry"), ("f-comets", "Paper Comets")] {        phone.upsert("film", id, &json!({ "title": title, "kind": "film", "file": format!("{DB}/films/{id}/master.m3u8") })).unwrap();    }    phone.act(Act::Update, "film", "f-ferry", &json!({ "subtitle_work": "find" })).unwrap();    phone.upsert("film", "f-later", &json!({ "title": "Lowmarsh", "kind": "series" })).unwrap();    let asked_at = object.state.lock().unwrap().rows[&("film".to_string(), "f-ferry".to_string())].version;    assert!(!object.everything().contains("Night Ferry"), "the film's title is sealed on the object");    // The Mac's run: a door whose copy is fresh and empty, as seal-files opens one with no data dir.    let mac = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::new(Copy::open(&dir.path().join("mac.db"), DB, key(7)).unwrap())));    let before = object.server.requests().len();    let row = mac.device_row("film", "f-ferry", asked_at - 1).unwrap().unwrap().unwrap();    assert_eq!(row["id"], "f-ferry");    assert_eq!(row["data"]["title"], "Night Ferry");    assert_eq!(row["data"]["subtitle_work"], "find");    let heard: Vec<String> = object.server.requests()[before..].iter().map(|r| r.path.clone()).collect();    assert_eq!(heard.len(), 1, "one read, no refresh of the copy: {heard:?}");    assert!(heard[0].starts_with("/v1/sync?") && heard[0].contains(&format!("since={}", asked_at - 1)) && heard[0].contains("tables=film"), "{heard:?}");    // From nothing it still finds it; a row not there, or deleted, is none.    assert_eq!(mac.device_row("film", "f-ferry", 0).unwrap().unwrap().unwrap()["data"]["title"], "Night Ferry");    assert!(mac.device_row("film", "f-nobody", 0).unwrap().unwrap().is_none());    phone.act(Act::Delete, "film", "f-comets", &json!({})).unwrap();    assert!(mac.device_row("film", "f-comets", 0).unwrap().unwrap().is_none());    // A Mac whose key does not open it says so by name.    let other = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::new(Copy::open(&dir.path().join("other.db"), DB, key(9)).unwrap())));    assert!(other.device_row("film", "f-ferry", 0).unwrap().is_err());}/// RULE (owner, FEEDBACK-2 B, 23 Nov 2026): a message erased from his Cotton (a chat's own timer, or any delete) is/// never brought back by a later import: the Mac remembers its channel and WhatsApp id (never its words) when the/// erase reaches its copy, and a new run, Bring everything in again or WhatsApp's history pass it over. Only that/// message: the other one in the same page stays as it was. A message restored to life leaves the list.#[test]fn an_erased_message_is_never_brought_back_and_only_it_is_passed_over() {    let object = FakeObject::start(DB, OWNER, sealed_messages());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    let copy = Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap();    ObjectSink::new(&client, DB).with_copy(&copy).send(batch()).unwrap();    let held = |external: &str| copy.held_message_id("whatsapp", external).unwrap();    let gone = held("3EB0A1B2C3D4E5F60001").expect("the first message landed");    let kept = held("3EB0A1B2C3D4E5F60002").expect("the second message landed");    // Nothing erased: a second read lands nothing and passes nothing over.    let again = ObjectSink::new(&client, DB).with_copy(&copy).send(batch()).unwrap();    assert_eq!(again.notes.get("erased:passedOver"), None);    // His phone erases the first (its moment came); the erase reaches the object as a tombstone holding nothing.    object.erase_row("message", &gone);    let read = ObjectSink::new(&client, DB).with_copy(&copy).send(batch()).unwrap();    assert_eq!(read.notes.get("erased:passedOver"), Some(&1), "{:?}", read.notes);    assert_eq!(read.new, 0, "nothing is new");    let live: Vec<String> = object.state.lock().unwrap().live("message").into_iter().map(|(id, _)| id).collect();    assert_eq!(live, vec![kept.clone()], "the erased message is not brought back, and the other stays");    assert!(copy.erased_of("whatsapp", &["3EB0A1B2C3D4E5F60001", "3EB0A1B2C3D4E5F60002"]).unwrap().contains("3EB0A1B2C3D4E5F60001"));    assert_eq!(copy.erased_of("whatsapp", &["3EB0A1B2C3D4E5F60002"]).unwrap().len(), 0, "only the erased one is listed");    assert_eq!(copy.erased_of("mail", &["3EB0A1B2C3D4E5F60001"]).unwrap().len(), 0, "by channel");    assert!(copy.row("message", &gone).unwrap().is_none());    // Restored (the bin gives it back): it lives again and leaves the list.    object.put_row("message", &gone, json!({ "channel": "whatsapp", "external_id": "3EB0A1B2C3D4E5F60001", "body": "restored", "thread_id": "t" }));    copy.refresh(&client).unwrap();    assert!(copy.erased_of("whatsapp", &["3EB0A1B2C3D4E5F60001"]).unwrap().is_empty());}/// RULE (CONTRACT "Disappearing messages on a WhatsApp chat", the Mac's half): a row the person erased keeps nothing/// of its words in the Mac's copy (ERASES what an older build kept there, on opening); the phones' marker for it is/// not counted as a message held, and never takes the message off the erased list.#[test]fn an_erased_row_keeps_nothing_on_the_mac_and_its_marker_is_not_a_message() {    let object = FakeObject::start(DB, OWNER, sealed_messages());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    let path = dir.path().join("copy.db");    let copy = Copy::open(&path, DB, key(7)).unwrap();    ObjectSink::new(&client, DB).with_copy(&copy).send(batch()).unwrap();    let gone = copy.held_message_id("whatsapp", "3EB0A1B2C3D4E5F60001").unwrap().unwrap();    assert_eq!(copy.held_from("whatsapp").unwrap(), Some(2));    object.erase_row("message", &gone);    object.put_row(        "message",        "marker-1",        json!({ "channel": "whatsapp", "external_id": "3EB0A1B2C3D4E5F60001", "thread_id": "t", "body": "", "deleted_at": "2026-11-23T10:00:00Z", "hidden_at": "2026-11-23T10:00:00Z", "meta": { "cotton": { "erased": "disappeared" } } }),    );    copy.refresh(&client).unwrap();    let raw = |id: &str| -> String {        let conn = rusqlite::Connection::open(&path).unwrap();        conn.query_row("SELECT data FROM rows WHERE table_id = 'message' AND id = ?1", [id], |r| r.get(0)).unwrap()    };    assert_eq!(raw(&gone), "{}", "the erased row keeps nothing");    assert!(!copy.erased_of("whatsapp", &["3EB0A1B2C3D4E5F60001"]).unwrap().is_empty(), "the marker does not lift the erase");    assert_eq!(copy.held_from("whatsapp").unwrap(), Some(1), "the marker is not a message held");    drop(copy);    // What an older build kept of a removed row goes when the copy opens.    let conn = rusqlite::Connection::open(&path).unwrap();    conn.execute("UPDATE rows SET data = '{\"body\":\"old words\"}' WHERE table_id = 'message' AND id = ?1", [&gone]).unwrap();    drop(conn);    let _copy = Copy::open(&path, DB, key(7)).unwrap();    assert_eq!(raw(&gone), "{}");    assert_ne!(raw("marker-1"), "{}", "a live row is untouched");}/// RULE (owner, FEEDBACK-2 A, 23 Nov 2026): a first text Comms sends to a number with no WhatsApp chat yet lands in the/// chat the phone named for it (the outbox row's thread), found by the WhatsApp id fixed at the tap: one chat.#[test]fn a_first_text_to_a_number_lands_in_the_chat_the_phone_named() {    let mut tables = sealed_messages();    tables.push(kit_sealed_table("outbox"));    let object = FakeObject::start(DB, OWNER, tables);    let dir = tempfile::tempdir().unwrap();    let copy = Arc::new(Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::clone(&copy)));    let phone_thread = "7d3f0c1e-9a51-4c8e-b2f4-0c6a1d5e9b01";    client        .upsert("outbox", "o-first", &json!({ "channel": "whatsapp", "to": "+919800000003", "thread_id": phone_thread, "body": "Hello from Comms", "status": "sent", "sent_external_id": "3EB0FIRSTTOANUMBER01" }))        .unwrap();    let request: ImportBatch = serde_json::from_value(json!({        "workspaceId": DB, "channel": "whatsapp",        "dm": { "label": "+919800000003", "phone": "+919800000003" },        "messages": [{ "direction": "out", "body": "Hello from Comms", "sentAt": "2026-11-23T10:00:00Z", "externalId": "3EB0FIRSTTOANUMBER01" }]    }))    .unwrap();    let work = IngestBatch { work: IngestWork::Messages { request: Box::new(request), media: vec![] }, read: 1, cursor: None };    ObjectSink::new(&client, DB).with_copy(&copy).send(work).unwrap();    let threads: Vec<String> = object.state.lock().unwrap().live("thread").into_iter().map(|(id, _)| id).collect();    assert_eq!(threads, vec![phone_thread.to_string()], "the chat is the one the phone showed");}/// RULE (owner, FEEDBACK-3, 23 Nov 2026; CONTRACT "Polls shown"): a WhatsApp poll in Cotton counts who picked what/// as votes arrive. Each vote's picks are read as the poll's options over the Mac's copy and go as/// `MessageChange::Vote`; the poll lands again sealed whole with its counts and voters; a vote for a poll Cotton does/// not hold changes nothing.#[test]fn votes_on_a_whatsapp_poll_are_counted_and_land_sealed() {    let object = FakeObject::start(DB, OWNER, sealed_messages());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    let copy = Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap();    let options = vec!["Thursday".to_string(), "Friday".to_string()];    let request: ImportBatch = serde_json::from_value(json!({        "workspaceId": DB, "channel": "whatsapp",        "dm": { "label": "Asha Example", "phone": "+919800000001" },        "messages": [{ "direction": "in", "senderLabel": "Asha Example", "body": "Which day for the quokka walk?", "sentAt": "2026-11-23T10:00:00Z", "externalId": "3EB0POLLQUOKKA000001",                       "meta": { "poll": cotton_core::import::poll::linked_poll("Which day for the quokka walk?", &options, 1) } }]    }))    .unwrap();    let work = IngestBatch { work: IngestWork::Messages { request: Box::new(request), media: vec![] }, read: 1, cursor: None };    ObjectSink::new(&client, DB).with_copy(&copy).send(work).unwrap();    let vote = |actor: &str, picks: &[&str]| cotton_client::ingest::PollVote {        external_id: "3EB0POLLQUOKKA000001".into(),        actor: actor.into(),        options: picks.iter().map(|p| cotton_core::import::poll::option_hash(p)).collect(),        at: "2026-11-23T10:05:00Z".into(),    };    let votes = vec![vote("919800000001", &["Friday"]), vote("owner", &["Thursday"]), vote("919800000001", &["Thursday"])];    let missing = cotton_client::ingest::PollVote { external_id: "3EB0NOTHERE".into(), ..vote("owner", &["Friday"]) };    let all: Vec<_> = votes.into_iter().chain([missing]).collect();    let sent = ObjectSink::new(&client, DB)        .with_copy(&copy)        .send(IngestBatch { work: IngestWork::PollVotes { workspace_id: DB.into(), channel: "whatsapp".into(), votes: all }, read: 4, cursor: None })        .unwrap();    assert_eq!(sent.notes.get("vote:noPoll"), Some(&1));    let id = copy.held_message_id("whatsapp", "3EB0POLLQUOKKA000001").unwrap().unwrap();    let poll = copy.row("message", &id).unwrap().unwrap()["meta"]["poll"].clone();    let counts: Vec<(String, f64)> = poll["options"].as_array().unwrap().iter().map(|o| (o["text"].as_str().unwrap().to_string(), o["votes"].as_f64().unwrap())).collect();    assert_eq!(counts, vec![("Thursday".into(), 2.0), ("Friday".into(), 0.0)]);    // CONTRACT "Polls shown": one entry a voter, their latest whole choice, the owner as "me".    let voters = poll["voters"].as_array().unwrap();    assert_eq!(voters.len(), 2);    assert_eq!((voters[0]["who"].as_str(), voters[0]["options"].clone()), (Some("me"), json!([0])));    assert!(voters[1]["who"].as_str().unwrap().contains("919800000001") && voters[1]["options"] == json!([0]), "{voters:?}");    assert_eq!(voters[1]["at"], "2026-11-23T10:05:00Z");    assert!(!object.everything().contains("quokka") && !object.everything().contains("Thursday"), "the poll lands sealed");}/// RULE (owner, Comms 26 with the Mac on build 6, 23 Nov 2026: the OLD polls of his WhatsApp chats). A poll a linked/// device kept before build 6 holds its question and no options. The Mac asks the phone for it again, before the next/// message of its chat, at most a few times; when WhatsApp hands it again the row stays the one row it is and takes/// its options, its votes then count, and a later read of the same poll changes nothing.#[test]fn an_old_poll_kept_as_words_is_asked_for_again_and_takes_its_options_and_votes() {    let object = FakeObject::start(DB, OWNER, sealed_messages());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    let copy = Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap();    let source = |id: &str, kind: &str| json!({ "service": "WhatsApp linked device", "account": "919800000000@s.whatsapp.net", "chat": "919800000001@s.whatsapp.net",                                                "externalId": id, "sender": "919800000001@s.whatsapp.net", "messageType": kind, "origin": "history" });    let land = |messages: Value| {        let request: ImportBatch = serde_json::from_value(json!({ "workspaceId": DB, "channel": "whatsapp", "dm": { "label": "Asha Example", "phone": "+919800000001" }, "messages": messages })).unwrap();        ObjectSink::new(&client, DB).with_copy(&copy).send(IngestBatch { work: IngestWork::Messages { request: Box::new(request), media: vec![] }, read: 1, cursor: None }).unwrap();    };    // As build 5 landed it: the question, no options; then the next message of the chat; and a newer bare poll with nothing after it.    land(json!([        { "direction": "in", "senderLabel": "Asha Example", "body": "Which day for the quokka walk?", "sentAt": "2026-07-01T10:00:00Z", "externalId": "3EB0OLDPOLL000000001", "meta": { "source": source("3EB0OLDPOLL000000001", "poll") } },        { "direction": "in", "senderLabel": "Asha Example", "body": "vote please", "sentAt": "2026-07-01T10:00:05Z", "externalId": "3EB0NEXT000000000001", "meta": { "source": source("3EB0NEXT000000000001", "text") } },        { "direction": "in", "senderLabel": "Asha Example", "body": "Lunch?", "sentAt": "2026-07-02T09:00:00Z", "externalId": "3EB0OLDPOLL000000002", "meta": { "source": source("3EB0OLDPOLL000000002", "poll") } }    ]));    let id = copy.held_message_id("whatsapp", "3EB0OLDPOLL000000001").unwrap().unwrap();    // Asked for before the next message of its chat; the newest one waits; asked again only after a while, three times at most.    let (due, waiting) = cotton_mac::old_polls::due(&copy, 1_800_000_000).unwrap();    assert_eq!(waiting, 1);    assert_eq!(due.len(), 1);    assert_eq!((due[0].poll.as_str(), due[0].chat.as_str(), due[0].before["id"].as_str()), ("3EB0OLDPOLL000000001", "919800000001@s.whatsapp.net", Some("3EB0NEXT000000000001")));    copy.asked_poll("3EB0OLDPOLL000000001", 1_800_000_000).unwrap();    assert!(cotton_mac::old_polls::due(&copy, 1_800_000_060).unwrap().0.is_empty(), "not asked again at once");    let later = 1_800_000_000 + cotton_mac::old_polls::ASK_AGAIN_AFTER;    assert_eq!(cotton_mac::old_polls::due(&copy, later).unwrap().0.len(), 1, "asked again later");    copy.asked_poll("3EB0OLDPOLL000000001", later).unwrap();    copy.asked_poll("3EB0OLDPOLL000000001", later).unwrap();    assert!(cotton_mac::old_polls::due(&copy, later * 2).unwrap().0.is_empty(), "three times at most");    // WhatsApp hands it again whole: the same row takes its options, beside what its meta held.    let options = vec!["Thursday".to_string(), "Friday".to_string()];    let whole = json!([{ "direction": "in", "senderLabel": "Asha Example", "body": "Which day for the quokka walk?", "sentAt": "2026-07-01T10:00:00Z", "externalId": "3EB0OLDPOLL000000001",                         "meta": { "source": source("3EB0OLDPOLL000000001", "poll"), "poll": cotton_core::import::poll::linked_poll("Which day for the quokka walk?", &options, 1) } }]);    land(whole.clone());    assert_eq!(copy.held_message_id("whatsapp", "3EB0OLDPOLL000000001").unwrap().unwrap(), id, "the one row it was");    let meta = copy.row("message", &id).unwrap().unwrap()["meta"].clone();    assert_eq!(meta["poll"]["options"].as_array().map(Vec::len), Some(2));    assert_eq!(meta["source"]["messageType"], "poll");    assert_eq!(object.state.lock().unwrap().live("message").len(), 3, "no second row");    assert!(cotton_mac::old_polls::due(&copy, later * 2).unwrap().0.is_empty());    // The votes that came beside it count on it, and a later read of the same poll resets nothing.    let vote = cotton_client::ingest::PollVote { external_id: "3EB0OLDPOLL000000001".into(), actor: "919800000001".into(), options: vec![cotton_core::import::poll::option_hash("Friday")], at: "2026-07-01T10:01:00Z".into() };    let sent = ObjectSink::new(&client, DB).with_copy(&copy).send(IngestBatch { work: IngestWork::PollVotes { workspace_id: DB.into(), channel: "whatsapp".into(), votes: vec![vote] }, read: 1, cursor: None }).unwrap();    assert_eq!(sent.notes.get("vote:noPoll"), None);    land(whole);    let poll = copy.row("message", &id).unwrap().unwrap()["meta"]["poll"].clone();    assert_eq!(poll["options"][1]["votes"].as_f64(), Some(1.0));    assert_eq!(poll["voters"].as_array().map(Vec::len), Some(1));    assert!(!object.everything().contains("quokka") && !object.everything().contains("Thursday"), "the poll lands sealed");}/// RULE (owner's decision, 11 Oct 2026; Comms showed no display pictures for WhatsApp chats, 24 Nov 2026): the Mac/// tells the WhatsApp link whose profile pictures Cotton would take (a person a number is linked to, whose photo is/// empty or still WhatsApp's, a sender no person is (on their contact), and a WhatsApp group whose picture is), and/// each picture that comes fills that photo under its WhatsApp key. A photo someone chose, and a stranger, are left.#[test]fn whatsapp_profile_pictures_fill_the_photos_comms_shows_and_never_one_someone_chose() {    let object = FakeObject::start(DB, OWNER, sealed_messages());    let dir = tempfile::tempdir().unwrap();    let keys = key(7);    let copy = Arc::new(Copy::open(&dir.path().join("copy.db"), DB, keys.clone()).unwrap());    // Files of sealed kinds go up sealed with the database's key, as the Mac's own client seals them.    let files = Arc::new(cotton_client::media::sealed::PersonFiles::new(DB, keys));    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::clone(&copy))).sealing_files(files);    // Seeded sealed, as the phones write them: a real object holds no plain row in a sealed table.    let seed = |table: &str, id: &str, data: Value| client.act(cotton_mac::object::Act::Create, table, id, &data);    seed("person", "p-asha", json!({ "full_name": "Asha Example", "avatar_key": null })).unwrap();    seed("person", "p-ravi", json!({ "full_name": "Ravi Example", "avatar_key": format!("{DB}/people/p-ravi/chosen.jpg") })).unwrap();    seed("message_contact", "c-asha", json!({ "phone_e164": "919800000001", "person_id": "p-asha" })).unwrap();    seed("message_contact", "c-ravi", json!({ "phone_e164": "919800000002", "person_id": "p-ravi" })).unwrap();    seed("message_contact", "c-nobody", json!({ "phone_e164": "919800000003" })).unwrap();    seed("thread", "t-walkers", json!({ "kind": "group", "external_key": "wa:group:120363000000000001@g.us", "title": "Quokka walkers" })).unwrap();    copy.refresh(&client).unwrap();    let wanted: Vec<String> = copy.wanted_pictures().unwrap().into_iter().collect();    assert_eq!(wanted, vec!["120363000000000001@g.us".to_string(), "919800000001@s.whatsapp.net".to_string(), "919800000003@s.whatsapp.net".to_string()]);    let picture = |jid: &str, bytes: &[u8]| {        let path = dir.path().join(format!("picture-{jid}.jpg"));        std::fs::write(&path, bytes).unwrap();        cotton_client::ingest::profile_pictures::ProfilePicture {            jid: jid.into(),            is_group: jid.ends_with("@g.us"),            file: cotton_client::ingest::IngestMediaFile { external_id: jid.into(), path, name: Some(format!("picture-{jid}.jpg")), content_type: Some("image/jpeg".into()) },            stored: None,        }    };    let page = vec![        picture("919800000001@s.whatsapp.net", b"asha's picture"),        picture("919800000002@s.whatsapp.net", b"ravi's picture"),        picture("919800000003@s.whatsapp.net", b"no person's picture"),        picture("120363000000000001@g.us", b"the walkers' picture"),    ];    let send = |pictures| ObjectSink::new(&client, DB).with_copy(&copy).send(IngestBatch { work: IngestWork::ProfilePictures { workspace_id: DB.into(), pictures }, read: 4, cursor: None }).unwrap();    let sent = send(page.clone());    assert_eq!((sent.notes.get("picture:person"), sent.notes.get("picture:contact"), sent.notes.get("picture:group"), sent.notes.get("picture:notTaken")), (Some(&1), Some(&1), Some(&1), Some(&1)), "{:?}", sent.notes);    let asha_row = copy.row("person", "p-asha").unwrap().unwrap();    let asha = asha_row["avatar_key"].as_str().unwrap_or_else(|| panic!("{asha_row:?}")).to_string();    assert!(asha.starts_with(&format!("{DB}/people/p-asha/whatsapp/")) && asha.ends_with(".jpg"), "{asha}");    assert!(cotton_core::media::keys::is_whatsapp_picture_key(&asha));    let walkers = copy.row("thread", "t-walkers").unwrap().unwrap()["photo_key"].as_str().unwrap().to_string();    assert!(walkers.starts_with(&format!("{DB}/messages/t-walkers/whatsapp/")), "{walkers}");    assert_eq!(copy.row("person", "p-ravi").unwrap().unwrap()["avatar_key"], format!("{DB}/people/p-ravi/chosen.jpg"), "a chosen photo stays");    let puts: Vec<String> = object.server.requests().iter().filter(|r| r.method == "PUT" && r.path.starts_with("/v1/media/")).map(|r| r.path.clone()).collect();    assert_eq!(puts.len(), 3, "only the three taken go up: {puts:?}");    let nobody = copy.row("message_contact", "c-nobody").unwrap().unwrap()["avatar_key"].as_str().unwrap().to_string();    assert!(nobody.starts_with(&format!("{DB}/messages/c-nobody/whatsapp/")) && cotton_core::media::keys::is_whatsapp_picture_key(&nobody), "a sender no person is keeps the picture on their contact: {nobody}");    // The same pictures again change nothing; a WhatsApp photo stays WhatsApp's to update.    let again = send(page);    assert_eq!(again.notes.get("picture:unchanged"), Some(&3), "{:?}", again.notes);    assert!(copy.wanted_pictures().unwrap().contains("919800000001@s.whatsapp.net"));    assert!(!object.everything().contains("Asha Example"), "the person's row lands sealed");}/// ERASES (owner, FEEDBACK-3, 23 Nov 2026): deleted in WhatsApp means deleted in Cotton. A message deleted for/// everyone keeps only its place: its words and its file go from the row, and the file from his storage. Only that/// message: the other message of the page keeps its words, and a file another message still names is kept.#[test]fn a_message_deleted_for_everyone_loses_its_file_and_only_it() {    let tables: Vec<Value> = ["thread", "message", "thread_member", "message_reaction", "message_contact", "message_contact_handle", "person", "person_handle", "call", "seal_key"].into_iter().map(kit_table).collect();    let object = FakeObject::start(DB, OWNER, tables);    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    let copy = Copy::open(&dir.path().join("copy.db"), DB, HeldDataKeys::new()).unwrap();    let sink = ObjectSink::new(&client, DB).with_copy(&copy);    sink.send(batch()).unwrap();    let first = copy.held_message_id("whatsapp", "3EB0A1B2C3D4E5F60001").unwrap().unwrap();    let second = copy.held_message_id("whatsapp", "3EB0A1B2C3D4E5F60002").unwrap().unwrap();    // The second message carries a picture, and the first one shares another file with a message that stays.    object.put_row("message", &second, json!({ "media": [{ "key": "db/messages/t/trailhead.jpg", "playback_key": "db/messages/t/trailhead-small.jpg" }] }));    object.put_row("message", &first, json!({ "media": [{ "key": "db/messages/t/shared.jpg" }] }));    object.put_row("message", "m-other", json!({ "channel": "whatsapp", "external_id": "3EB0OTHER", "thread_id": "t", "media": [{ "key": "db/messages/t/shared.jpg" }] }));    let changes = vec![MessageChange::Revoke { external_id: "3EB0A1B2C3D4E5F60002".into(), at: "2026-10-20T00:50:00Z".into() }];    let sent = sink.send(IngestBatch { work: IngestWork::MessageChanges { workspace_id: DB.into(), channel: "whatsapp".into(), changes }, read: 1, cursor: None }).unwrap();    assert_eq!(sent.notes.get("erased:deletedFiles"), Some(&2), "{:?}", sent.notes);    let gone = copy.row("message", &second).unwrap().unwrap();    assert_eq!(gone["media"], json!([]));    assert_eq!(gone["body"], "");    assert!(gone["deleted_at"].is_string(), "its place stays, as deleted");    let kept = copy.row("message", &first).unwrap().unwrap();    assert_eq!(kept["body"], "Leaving at six?", "the other message keeps its words");    let deletes: Vec<String> = object.server.requests().iter().filter(|r| r.method == "DELETE").map(|r| r.path.clone()).collect();    assert_eq!(deletes, vec!["/v1/media/db/messages/t/trailhead.jpg".to_string(), "/v1/media/db/messages/t/trailhead-small.jpg".to_string()]);    // A later page of changes finds nothing more to erase.    let changes = vec![MessageChange::Reaction { external_id: "3EB0A1B2C3D4E5F60001".into(), actor: "self".into(), emoji: "🎉".into(), at: "2026-10-20T00:51:00Z".into() }];    let again = sink.send(IngestBatch { work: IngestWork::MessageChanges { workspace_id: DB.into(), channel: "whatsapp".into(), changes }, read: 1, cursor: None }).unwrap();    assert_eq!(again.notes.get("erased:deletedFiles"), None);}/// RULE (LIVE CPU 4, 24 Nov 2026): one `import_rows` call never carries more than `IMPORT_TOKENS` blind tokens (each/// a row of the object's search index), whatever its row count, so a chat of a hundred sealed texts goes up in/// several small calls; a row heavier than the cap goes alone, and no row is lost or doubled.#[test]fn an_import_call_is_bounded_by_its_search_tokens_not_only_its_rows() {    use cotton_mac::copy::{import_calls, IMPORT_TOKENS};    let row = |n: usize, tokens: usize| json!({ "table": "message", "id": format!("m{n}"), "blind": vec!["t"; tokens] });    let mut wire: Vec<Value> = (0..120).map(|n| row(n, 300)).collect();    wire.push(row(120, IMPORT_TOKENS + 5));    wire.extend((121..130).map(|n| json!({ "table": "thread", "id": format!("t{n}") })));    let calls = import_calls(&wire);    for call in &calls {        let tokens: usize = call.iter().map(|r| r["blind"].as_array().map_or(0, Vec::len)).sum();        assert!(call.len() == 1 || tokens <= IMPORT_TOKENS, "a call of {} rows carries {tokens} tokens", call.len());    }    let ids: Vec<&str> = calls.iter().flat_map(|c| c.iter().map(|r| r["id"].as_str().unwrap())).collect();    assert_eq!(ids.len(), wire.len(), "every row once, in order");    assert!(ids.iter().zip(wire.iter()).all(|(a, b)| *a == b["id"].as_str().unwrap()));    assert!(calls.iter().any(|c| c.len() == 1 && c[0]["id"] == "m120"), "the heavy row goes alone");    assert_eq!(import_calls(&(0..1200).map(|n| json!({ "id": n })).collect::<Vec<_>>()).len(), 3, "token-free rows still go 500 a call");}/// RULE (FILMS TRUE, 25 Nov 2026; the class of the lost subtitle track, 24 Nov): a sealed row is sealed whole, so the/// Mac lays its patch over the row as the object holds it NOW, never over the copy its run read first. A film job's/// second write (a master moved, an hour after its first) keeps what the phone or another job wrote in between: the/// track list, the resume point, the subtitle ask.#[test]fn a_later_update_keeps_what_another_device_wrote_since_the_runs_first() {    let object = FakeObject::start(DB, OWNER, vec![kit_sealed_table("film"), kit_sealed_table("film_episode")]);    let dir = tempfile::tempdir().unwrap();    let phone = ObjectClient::new(object.server.url.clone(), Some("phone".into())).unwrap().sealing_with(SealDoor::over(Arc::new(Copy::open(&dir.path().join("phone.db"), DB, key(7)).unwrap())));    phone.upsert("film", "f-ferry", &json!({ "title": "Night Ferry", "kind": "film", "file": format!("{DB}/films/f-ferry/master.m3u8") })).unwrap();    // The Mac's run: its first write reads its copy up to the object.    let mac = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::new(Copy::open(&dir.path().join("mac.db"), DB, key(7)).unwrap())));    mac.act(Act::Update, "film", "f-ferry", &json!({ "subtitle_work": "generating", "subtitle_note": "Making subtitles: 10%" })).unwrap();    // Meanwhile another job lays a track, and the phone keeps the place he stopped at.    let track = json!([{ "name": "English", "language": "en", "file": format!("{DB}/films/f-ferry/sub-en-sidecar-0123456789.vtt") }]);    let other = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::new(Copy::open(&dir.path().join("other.db"), DB, key(7)).unwrap())));    other.act(Act::Update, "film", "f-ferry", &json!({ "subtitles": track, "file": format!("{DB}/films/f-ferry/master-aaaaaaaaaaaa.m3u8") })).unwrap();    phone.act(Act::Update, "film", "f-ferry", &json!({ "position": 1234 })).unwrap();    // The Mac's second write, from the same run.    mac.act(Act::Update, "film", "f-ferry", &json!({ "subtitle_note": "Making subtitles: 20%" })).unwrap();    let reader = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::new(Copy::open(&dir.path().join("reader.db"), DB, key(7)).unwrap())));    let row = reader.device_row("film", "f-ferry", 0).unwrap().unwrap().unwrap();    assert_eq!(row["data"]["subtitles"], track, "the track another job laid stays: {row}");    assert_eq!(row["data"]["file"], json!(format!("{DB}/films/f-ferry/master-aaaaaaaaaaaa.m3u8")), "{row}");    assert_eq!(row["data"]["position"], json!(1234), "the place he stopped at stays: {row}");    assert_eq!(row["data"]["subtitle_note"], json!("Making subtitles: 20%"), "{row}");}/// RULE (STALE WRITES, 25 Nov 2026): every landing reads the copy up to the object before it plans and seals, so a/// batch landed after a long wait (WhatsApp's uploads, a history import) never seals back a row as it stood before/// the wait: what the phone changed meanwhile stays, and a row another device made meanwhile is updated, never reset.#[test]fn a_landing_after_a_wait_keeps_what_the_phone_changed_meanwhile() {    let object = FakeObject::start(DB, OWNER, vec![kit_sealed_table("film"), kit_sealed_table("film_episode")]);    let dir = tempfile::tempdir().unwrap();    let phone = ObjectClient::new(object.server.url.clone(), Some("phone".into())).unwrap().sealing_with(SealDoor::over(Arc::new(Copy::open(&dir.path().join("phone.db"), DB, key(7)).unwrap())));    phone.upsert("film", "f-ferry", &json!({ "title": "Night Ferry", "kind": "film", "status": "want_to_watch" })).unwrap();    // The Mac's run reads its copy up, then waits (its uploads).    let mac = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let copy = Copy::open(&dir.path().join("mac.db"), DB, key(7)).unwrap();    copy.refresh(&mac).unwrap();    phone.act(Act::Update, "film", "f-ferry", &json!({ "status": "watched", "position": 4321 })).unwrap();    phone.upsert("film", "f-comets", &json!({ "title": "Paper Comets", "kind": "film" })).unwrap();    // Then it lands its batch: a note on the one, and the other by the id it derived.    let note = |id: &str, words: &str| cotton_mac::copy::Change { table: "film".into(), id: id.into(), patch: Some(json!({ "subtitle_note": words }).as_object().unwrap().clone()) };    copy.landing(&mac, |landing| landing.apply_as_named(&[note("f-ferry", "a"), note("f-comets", "b")])).unwrap();    let reader = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::new(Copy::open(&dir.path().join("reader.db"), DB, key(7)).unwrap())));    let ferry = reader.device_row("film", "f-ferry", 0).unwrap().unwrap().unwrap();    assert_eq!((ferry["data"]["status"].clone(), ferry["data"]["position"].clone(), ferry["data"]["subtitle_note"].clone()), (json!("watched"), json!(4321), json!("a")), "{ferry}");    let comets = reader.device_row("film", "f-comets", 0).unwrap().unwrap().unwrap();    assert_eq!((comets["data"]["title"].clone(), comets["data"]["subtitle_note"].clone()), (json!("Paper Comets"), json!("b")), "{comets}");}/// RULE (coordinator, Mac 10: older WhatsApp chats). The Mac asks the phone, chat by chat, for what came before the/// oldest message the link wrote of it, the chats active most lately first, a few a pass; a chat is asked again only/// after a while, and once three asks before the same message brought nothing older its beginning is reached.#[test]fn each_whatsapp_chat_is_asked_for_what_came_before_its_oldest_message() {    let object = FakeObject::start(DB, OWNER, sealed_messages());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    let copy = Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap();    let source = |chat: &str, id: &str| json!({ "service": "WhatsApp linked device", "account": "919800000000@s.whatsapp.net", "chat": chat,                                                "externalId": id, "sender": chat, "messageType": "text", "origin": "history" });    let land = |phone: &str, label: &str, messages: Value| {        let request: ImportBatch = serde_json::from_value(json!({ "workspaceId": DB, "channel": "whatsapp", "dm": { "label": label, "phone": phone }, "messages": messages })).unwrap();        ObjectSink::new(&client, DB).with_copy(&copy).send(IngestBatch { work: IngestWork::Messages { request: Box::new(request), media: vec![] }, read: 1, cursor: None }).unwrap();    };    let asha = "919800000001@s.whatsapp.net";    let ravi = "919800000002@s.whatsapp.net";    land("+919800000001", "Asha Example", json!([        { "direction": "in", "senderLabel": "Asha Example", "body": "first", "sentAt": "2024-02-01T10:00:00Z", "externalId": "A-OLD", "meta": { "source": source(asha, "A-OLD") } },        { "direction": "out", "body": "later", "sentAt": "2024-03-01T10:00:00Z", "externalId": "A-NEW", "meta": { "source": source(asha, "A-NEW") } }    ]));    land("+919800000002", "Ravi Example", json!([        { "direction": "in", "senderLabel": "Ravi Example", "body": "hi", "sentAt": "2026-11-01T10:00:00Z", "externalId": "R-OLD", "meta": { "source": source(ravi, "R-OLD") } }    ]));    copy.refresh(&client).unwrap();    let now = 1_800_000_000;    let (due, reached) = cotton_mac::older::due(&copy, now).unwrap();    assert_eq!(reached, 0);    let asked: Vec<(&str, &str)> = due.iter().map(|a| (a.chat.as_str(), a.before["id"].as_str().unwrap())).collect();    assert_eq!(asked, vec![(ravi, "R-OLD"), (asha, "A-OLD")], "the chat he talked in last first, each before its oldest");    assert_eq!(due[1].before, json!({ "id": "A-OLD", "from_me": false, "ts": 1706781600, "sender": asha }));    for one in &due {        copy.asked_older(&one.thread, one.before["id"].as_str().unwrap(), now, one.tries, false).unwrap();    }    assert!(cotton_mac::older::due(&copy, now + 60).unwrap().0.is_empty(), "not asked again at once");    // Asha's phone answers with an older message: her chat is asked before that one next, a first try again.    land("+919800000001", "Asha Example", json!([        { "direction": "in", "senderLabel": "Asha Example", "body": "older still", "sentAt": "2023-12-01T10:00:00Z", "externalId": "A-OLDER", "meta": { "source": source(asha, "A-OLDER") } }    ]));    copy.refresh(&client).unwrap();    let mut later = now + cotton_mac::older::ASK_AGAIN_AFTER;    let due = cotton_mac::older::due(&copy, later).unwrap().0;    let a = due.iter().find(|a| a.chat == asha).unwrap();    assert_eq!((a.before["id"].as_str(), a.tries), (Some("A-OLDER"), 1));    let r = due.iter().find(|a| a.chat == ravi).unwrap();    assert_eq!(r.tries, 2, "Ravi's brought nothing older yet");    // Ravi's: three asks before the same message and nothing older: his beginning is reached, asked no more.    copy.asked_older(&r.thread, "R-OLD", later, 3, false).unwrap();    later += cotton_mac::older::ASK_AGAIN_AFTER;    let (due, reached) = cotton_mac::older::due(&copy, later).unwrap();    assert_eq!(reached, 1);    assert!(due.iter().all(|a| a.chat != ravi));    assert!(cotton_mac::older::due(&copy, later * 2).unwrap().0.iter().all(|a| a.chat != ravi), "never asked again");}/// RULE (DELETE FAST question 2, mac-import Mac 11): after a sender's Delete everything moved a counted set to Trash,/// the Mac erases Cotton's email rows of exactly those mails, found by Gmail's id or else by the Message-ID's/// `external_id`; a row the phone already erased is passed over; a conversation left with no mail goes, one that/// still holds other mail stays.#[test]fn mail_moved_to_trash_leaves_cotton_with_its_conversation_when_emptied() {    let object = FakeObject::start(DB, OWNER, sealed_mail());    let dir = tempfile::tempdir().unwrap();    let copy = Arc::new(Copy::open(&dir.path().join("copy.db"), DB, key(7)).unwrap());    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::clone(&copy)));    for thread in ["t-gone", "t-kept"] {        client.upsert("email_thread", thread, &json!({ "subject": "invented" })).unwrap();    }    let mail = |id: &str, thread: &str, gmail: Option<&str>, external: &str| {        let mut row = json!({ "thread_id": thread, "external_id": external, "subject": "invented", "from_email": "deals@shop.invented", "body": "x", "sent_at": "2025-01-10T08:00:00.000Z" });        if let Some(gmail) = gmail {            row["gmail_id"] = json!(gmail);        }        client.upsert("email", id, &row).unwrap();    };    mail("e1", "t-gone", Some("1001"), "mid:one");    mail("e2", "t-gone", None, "mid:two");    mail("e3", "t-kept", Some("1003"), "mid:three");    mail("e4", "t-kept", Some("1004"), "mid:four");    mail("e5", "t-kept", Some("1005"), "mid:five");    // The phone erased what its 90 days held of them.    client.act(Act::Delete, "email", "e5", &json!({})).unwrap();    let named = |gmail: Option<&str>, external: Option<&str>| cotton_mac::mail::trash::GoneMail { gmail_id: gmail.map(str::to_string), external: external.map(str::to_string) };    let gone = [named(Some("1001"), Some("mid:other")), named(Some("ffff"), Some("mid:two")), named(Some("1003"), None), named(Some("1005"), Some("mid:five")), named(None, None)];    assert_eq!(cotton_mac::mail::erase_trashed(&client, &copy, &gone).unwrap(), 3);    let live = |table: &str| -> Vec<String> {        let mut ids: Vec<String> = object.state.lock().unwrap().live(table).into_iter().map(|(id, _)| id).collect();        ids.sort();        ids    };    assert_eq!(live("email"), ["e4"]);    assert_eq!(live("email_thread"), ["t-kept"], "the emptied conversation goes, the one with mail left stays");}/// RULE (AVATAR SEAL 2 (3), 27 Nov 2026): while this Mac holds no data key, a WhatsApp face waits (it is sealed, so its/// put cannot go): the batch carries on past it, nothing goes up open, and the face is kept beside the copy; once the/// Mac is let in, the next page of pictures tries it again and it fills its photo, sealed.#[test]fn a_whatsapp_face_waiting_for_the_data_key_is_skipped_kept_and_tried_again() {    let object = FakeObject::start(DB, OWNER, ["thread", "message", "message_contact", "person", "seal_key"].into_iter().map(kit_table).collect());    let dir = tempfile::tempdir().unwrap();    let keys = HeldDataKeys::new();    let copy = Arc::new(Copy::open(&dir.path().join("copy.db"), DB, keys.clone()).unwrap());    let files = Arc::new(cotton_client::media::sealed::PersonFiles::new(DB, keys.clone()));    let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(Arc::clone(&copy))).sealing_files(files);    object.put_row("person", "p-asha", json!({ "full_name": "Asha Example", "avatar_key": null }));    object.put_row("person", "p-bina", json!({ "full_name": "Bina Example", "avatar_key": null }));    object.put_row("message_contact", "c-asha", json!({ "phone_e164": "919800000001", "person_id": "p-asha" }));    object.put_row("message_contact", "c-bina", json!({ "phone_e164": "919800000004", "person_id": "p-bina" }));    copy.refresh(&client).unwrap();    let picture = |jid: &str, bytes: &[u8]| {        let path = dir.path().join(format!("staged-{jid}.jpg"));        std::fs::write(&path, bytes).unwrap();        cotton_client::ingest::profile_pictures::ProfilePicture {            jid: jid.into(),            is_group: false,            file: cotton_client::ingest::IngestMediaFile { external_id: jid.into(), path, name: Some("picture.jpg".into()), content_type: Some("image/jpeg".into()) },            stored: None,        }    };    let send = |pictures| ObjectSink::new(&client, DB).with_copy(&copy).send(IngestBatch { work: IngestWork::ProfilePictures { workspace_id: DB.into(), pictures }, read: 1, cursor: None });    // No key: both faces wait, the batch does not stop at the first, and nothing goes up.    let sent = send(vec![picture("919800000001@s.whatsapp.net", b"asha's face"), picture("919800000004@s.whatsapp.net", b"bina's face")]).expect("the batch carries on");    assert_eq!(sent.notes.get("picture:waitsForKey"), Some(&2), "{:?}", sent.notes);    assert!(object.server.requests().iter().all(|r| r.method != "PUT"), "nothing goes up open");    // The link's staged files go with their page; the kept copies stay.    for jid in ["919800000001@s.whatsapp.net", "919800000004@s.whatsapp.net"] {        std::fs::remove_file(dir.path().join(format!("staged-{jid}.jpg"))).unwrap();    }    assert_eq!(std::fs::read_dir(dir.path().join("pictures-waiting")).unwrap().count(), 2);    // Let in: the next page (Bina's newer face) takes Asha's waiting one too, sealed.    keys.hold(DB, &cotton_core::seal::DataKey::from_bytes([7; 32]));    copy.refresh(&client).unwrap();    let sent = send(vec![picture("919800000004@s.whatsapp.net", b"bina's newer face")]).unwrap();    assert_eq!(sent.notes.get("picture:person"), Some(&2), "{:?}", sent.notes);    let asha = copy.row("person", "p-asha").unwrap().unwrap()["avatar_key"].as_str().unwrap().to_string();    assert!(asha.starts_with(&format!("{DB}/people/p-asha/whatsapp/")), "{asha}");    let state = object.state.lock().unwrap();    assert_eq!(state.media_types[&asha], "application/vnd.cotton.f1", "the face goes up sealed");    drop(state);    assert_eq!(std::fs::read_dir(dir.path().join("pictures-waiting")).unwrap().count(), 0, "nothing left waiting");    assert_eq!(copy.kept("pictures_waiting").unwrap(), None);}