Cotton code
1105 lines · 56.4 KB · RustRaw
use std::collections::BTreeMap;use serde_json::json;use super::*;use crate::test_support::{counter_seed, fold_create, seeded_file, WORKSPACE};/// 12 Oct 2026, 00:00 UTC.const NOW: i64 = 1_791_763_200_000;const AUTHOR: &str = "device:mac-author";const PHONE: &str = "phone-key";const MAC: &str = "mac-key";const OLD_THREAD: &str = "thread-old";const NEW_THREAD: &str = "thread-new";const OLD_EMAIL: &str = "email-old";const NEW_EMAIL: &str = "email-new";const OLD_PARTICIPANT: &str = "participant-old";const STORY: &str = "story-1";fn device(db: &Driver, key: &str, platform: Option<&str>) {    db.run(        "INSERT INTO cotton_devices (id, workspace_id, device_id, name, platform, approved_at, approved_by_device, created_at, updated_at) \         VALUES (?, ?, ?, 'Invented device', ?, '2026-01-01', ?, '2026-01-01', '2026-01-01')",        &[            text(key),            text(WORKSPACE),            text(key),            platform.map(text).unwrap_or(SqlValue::Null),            text(key),        ],    )    .unwrap();}fn thread(db: &Driver, id: &str, last_at: &str, ms: i64) {    fold_create(        db,        "cotton_email_threads",        id,        json!({"id": id, "workspace_id": WORKSPACE, "external_key": id, "last_at": last_at,               "created_at": last_at, "updated_at": last_at}),        AUTHOR,        ms,    );}fn email(db: &Driver, id: &str, thread_id: &str, sent_at: &str, ms: i64) {    fold_create(        db,        "cotton_emails",        id,        json!({"id": id, "workspace_id": WORKSPACE, "thread_id": thread_id, "external_id": id,               "from_email": "a@example.com", "sent_at": sent_at, "created_at": sent_at}),        AUTHOR,        ms,    );}/// The serving Mac's file: a phone and a Mac, a thread from January with its/// email and a participant, a thread from this week with its email, a status.fn household() -> Driver {    let db = seeded_file("device:serving");    device(&db, PHONE, Some("ios"));    device(&db, MAC, Some("mac"));    thread(&db, OLD_THREAD, "2026-01-05T09:00:00.000Z", 10);    email(&db, OLD_EMAIL, OLD_THREAD, "2026-01-05T09:00:00.000Z", 11);    fold_create(        &db,        "cotton_email_participants",        OLD_PARTICIPANT,        json!({"id": OLD_PARTICIPANT, "workspace_id": WORKSPACE, "thread_id": OLD_THREAD, "email": "a@example.com",               "role": "from", "created_at": "2026-01-05T09:00:00.000Z", "updated_at": "2026-01-05T09:00:00.000Z"}),        AUTHOR,        12,    );    thread(&db, NEW_THREAD, "2026-10-10T09:00:00.000Z", 13);    email(&db, NEW_EMAIL, NEW_THREAD, "2026-10-10T09:00:00.000Z", 14);    fold_create(        &db,        "cotton_stories",        STORY,        json!({"id": STORY, "workspace_id": WORKSPACE, "source": "whatsapp", "account": "me", "external_id": STORY,               "kind": "image", "posted_at": "2026-10-11T09:00:00.000Z", "expires_at": "2026-10-12T09:00:00.000Z",               "created_at": "2026-10-11T09:00:00.000Z"}),        AUTHOR,        15,    );    db}/// A rule row written past `set_rule` — what a peer's push could carry.fn rule_row(db: &Driver, device_id: &str, kind: &str, target: &str, rule: &str) {    let id = derived_id::device_keep_id(device_id, kind, target);    db.run(        "INSERT INTO cotton_device_keep (id, workspace_id, device_id, kind, target, rule, created_at, updated_at) \         VALUES (?, ?, ?, ?, ?, ?, '2026-10-01', '2026-10-01') \         ON CONFLICT (id) DO UPDATE SET rule = excluded.rule",        &[text(&id), text(WORKSPACE), text(device_id), text(kind), text(target), text(rule)],    )    .unwrap();}/// The whole catch-up page this file answers a device that has seen nothing.fn page(db: &Driver) -> Vec<CottonOp> {    let answered = crate::exchange::answer(db, &BTreeMap::new(), 2_000).unwrap();    assert!(!answered.has_more);    answered.ops}/// The rows a page carries for one device, as `(table, row id)`.fn sent_to(db: &Driver, device_id: &str) -> Vec<(String, String)> {    let keep = Keep::of_device(db, device_id).unwrap();    keep.leave_out(db, page(db), NOW)        .unwrap()        .into_iter()        .map(|op| (op.table, op.row_id))        .collect()}fn carries(rows: &[(String, String)], table: &str, row_id: &str) -> bool {    rows.iter().any(|(t, r)| t == table && r == row_id)}fn owner() -> Actor {    crate::fixtures::fixture_actor()}/// RULE: a Mac's keep rules cannot be narrowed. A Mac may take over serving/// and must hold the whole file, so a rule naming a Mac is refused where/// rules are written AND never read where rows are judged — a row that/// arrived some other way (a peer's push) narrows nothing. A device whose/// platform the file does not say is a Mac's answer, for the same reason.#[test]fn a_macs_rules_cannot_be_narrowed() {    let db = household();    device(&db, "unknown-key", None);    let mut ids = crate::protocol::ulid::Monotonic::new(counter_seed());    for mac in [MAC, "unknown-key"] {        let refused = set_rule(&db, WORKSPACE, mac, KIND_TABLE, "cotton_stories", "none", owner(), NOW, &mut ids, Held::Served);        assert!(matches!(refused, Err(StoreError::Refused(_))), "{mac}: {refused:?}");        // Written past the writer, as a push could: still nothing is left out.        rule_row(&db, mac, KIND_TABLE, "cotton_stories", "none");        rule_row(&db, mac, KIND_TABLE, "cotton_email_threads", "days:90");        let keep = Keep::of_device(&db, mac).unwrap();        assert!(!keep.narrows(), "{mac}");        let whole = page(&db);        assert_eq!(keep.leave_out(&db, whole.clone(), NOW).unwrap(), whole, "{mac}");    }}/// RULE: a row outside a phone's keep rules is never sent in a catch-up page./// Not a stub: the row is simply absent — a status under `none`, a thread/// older than its horizon — and so is every row it OWNS (its emails, its/// participants), which would otherwise sit on the phone waiting for a parent/// that never comes. A phone with no rule row is sent everything but what a/// phone never holds by default (`PHONE_DEFAULTS`).#[test]fn a_row_outside_a_phones_rules_is_never_in_a_page() {    let db = household();    let whole = page(&db);    // The defaults leave out every status and the January thread with what    // it owns: it is older than the six months a phone keeps of mail.    let january = [OLD_THREAD, OLD_EMAIL, OLD_PARTICIPANT];    let but_the_defaults: Vec<CottonOp> = whole        .iter()        .filter(|op| op.table != "cotton_stories" && !january.contains(&op.row_id.as_str()))        .cloned()        .collect();    assert_eq!(        Keep::of_device(&db, PHONE).unwrap().leave_out(&db, whole.clone(), NOW).unwrap().len(),        but_the_defaults.len(),        "no rule row is all but the defaults"    );    rule_row(&db, PHONE, KIND_TABLE, "cotton_stories", "none");    rule_row(&db, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");    let sent = sent_to(&db, PHONE);    assert!(!carries(&sent, "cotton_stories", STORY));    assert!(!carries(&sent, "cotton_email_threads", OLD_THREAD));    assert!(!carries(&sent, "cotton_emails", OLD_EMAIL));    assert!(!carries(&sent, "cotton_email_participants", OLD_PARTICIPANT));    // What is inside the rules, and what no rule governs, travels untouched.    assert!(carries(&sent, "cotton_email_threads", NEW_THREAD));    assert!(carries(&sent, "cotton_emails", NEW_EMAIL));    assert!(carries(&sent, "cotton_workspaces", WORKSPACE));    assert_eq!(sent.len(), whole.len() - 4);    // The Mac beside it is sent the page whole.    assert_eq!(sent_to(&db, MAC).len(), whole.len());}/// RULE: a delete always travels, except for a table that is never kept. A/// row a phone opened yesterday must leave it when it is erased today, so the/// delete of a row outside a horizon is sent; a table under `none` has nothing/// on the phone to delete, so its deletes are not.#[test]fn a_delete_always_travels_except_for_a_table_never_kept() {    let db = household();    rule_row(&db, PHONE, KIND_TABLE, "cotton_stories", "none");    rule_row(&db, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");    let delete_of = |table: &str, row_id: &str| {        let mut op = page(&db).into_iter().find(|op| op.table == table && op.row_id == row_id).unwrap();        op.kind = OpKind::Delete;        op.patch = None;        op    };    let deletes = vec![        delete_of("cotton_email_threads", OLD_THREAD),        delete_of("cotton_emails", OLD_EMAIL),        delete_of("cotton_stories", STORY),    ];    let sent: Vec<(String, String)> = Keep::of_device(&db, PHONE)        .unwrap()        .leave_out(&db, deletes, NOW)        .unwrap()        .into_iter()        .map(|op| (op.table, op.row_id))        .collect();    assert!(carries(&sent, "cotton_email_threads", OLD_THREAD));    assert!(carries(&sent, "cotton_emails", OLD_EMAIL));    assert!(!carries(&sent, "cotton_stories", STORY));}/// RULE: a RECORD keep and a GROUP keep bring a record past its table's/// horizon, with the rows it owns; a pinned row keeps the rows it belongs to/// (pinning one email keeps its thread, or the email could never land)./// Nothing brings back a table that is never kept.#[test]fn a_pin_and_a_kept_group_bring_a_record_past_its_horizon() {    let db = household();    rule_row(&db, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");    assert!(!carries(&sent_to(&db, PHONE), "cotton_email_threads", OLD_THREAD));    // A pin on the thread.    rule_row(&db, PHONE, KIND_RECORD, &record_target_of("cotton_email_threads", OLD_THREAD), ALWAYS);    let sent = sent_to(&db, PHONE);    assert!(carries(&sent, "cotton_email_threads", OLD_THREAD));    assert!(carries(&sent, "cotton_emails", OLD_EMAIL));    assert!(carries(&sent, "cotton_email_participants", OLD_PARTICIPANT));    db.run("DELETE FROM cotton_device_keep WHERE kind = 'record'", &[]).unwrap();    // A pin on one email of it keeps the thread it belongs to.    rule_row(&db, PHONE, KIND_RECORD, &record_target_of("cotton_emails", OLD_EMAIL), ALWAYS);    let sent = sent_to(&db, PHONE);    assert!(carries(&sent, "cotton_emails", OLD_EMAIL));    assert!(carries(&sent, "cotton_email_threads", OLD_THREAD));    db.run("DELETE FROM cotton_device_keep WHERE kind = 'record'", &[]).unwrap();    assert!(!carries(&sent_to(&db, PHONE), "cotton_email_threads", OLD_THREAD));    // A hand-picked group the thread is a member of, kept always.    group(&db, "group-1", OLD_THREAD, 20);    rule_row(&db, PHONE, KIND_GROUP, "group-1", ALWAYS);    let sent = sent_to(&db, PHONE);    assert!(carries(&sent, "cotton_email_threads", OLD_THREAD));    assert!(carries(&sent, "cotton_emails", OLD_EMAIL));    // Never is never: a pin on a status sends no status.    rule_row(&db, PHONE, KIND_TABLE, "cotton_stories", "none");    rule_row(&db, PHONE, KIND_RECORD, &record_target_of("cotton_stories", STORY), ALWAYS);    assert!(!carries(&sent_to(&db, PHONE), "cotton_stories", STORY));}/// RULE: opening a row outside a phone's rules fetches it — the record whole:/// the row, the owning parents it could not land without and the rows it/// owns, as the receipts the file holds, so a phone that folds the answer/// holds the record. A row that is never kept is never fetched.#[test]fn opening_a_row_outside_the_rules_fetches_it_and_never_a_row_never_kept() {    let db = household();    rule_row(&db, PHONE, KIND_TABLE, "cotton_stories", "none");    rule_row(&db, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");    let keep = Keep::of_device(&db, PHONE).unwrap();    // The phone's own file, caught up within its rules: the old thread is absent.    let phone = seeded_file("device:phone");    let within = keep.leave_out(&db, page(&db), NOW).unwrap();    let within: Vec<CottonOp> = within.into_iter().filter(|op| op.table != "cotton_workspaces").collect();    let folded = crate::fold::fold_pulled(&phone, &within).unwrap();    assert!(folded.rejected.is_empty(), "{folded:?}");    let held = |table: &str, id: &str| {        phone.get(&format!("SELECT 1 AS x FROM {table} WHERE id = ?"), &[text(id)]).unwrap().is_some()    };    assert!(held("cotton_email_threads", NEW_THREAD));    assert!(!held("cotton_email_threads", OLD_THREAD));    assert!(!held("cotton_emails", OLD_EMAIL));    // Opening the old EMAIL answers its thread first, then the email.    let opened = open(&db, &keep, "cotton_emails", OLD_EMAIL, 0, NOW).unwrap();    assert_eq!(        opened.rows,        vec![            ("cotton_email_threads".to_string(), OLD_THREAD.to_string()),            ("cotton_emails".to_string(), OLD_EMAIL.to_string()),        ]    );    assert_eq!(opened.next, None);    let folded = crate::fold::fold_pulled(&phone, &opened.ops).unwrap();    assert!(folded.rejected.is_empty(), "{folded:?}");    assert!(held("cotton_email_threads", OLD_THREAD));    assert!(held("cotton_emails", OLD_EMAIL));    record_opened(&phone, &opened.rows, NOW).unwrap();    record_opened(&phone, &opened.rows, NOW + DAY_MS).unwrap();    let ledger = phone.all("SELECT tbl, row_id, fetched_at, opened_at FROM _on_demand ORDER BY tbl", &[]).unwrap();    assert_eq!(ledger.len(), 2);    assert_eq!(ledger[0].text("fetched_at"), Some("2026-10-12T00:00:00.000Z"));    assert_eq!(ledger[0].text("opened_at"), Some("2026-10-13T00:00:00.000Z"));    // Opening the old THREAD answers it with everything it owns.    let opened = open(&db, &keep, "cotton_email_threads", OLD_THREAD, 0, NOW).unwrap();    assert_eq!(opened.rows[0], ("cotton_email_threads".to_string(), OLD_THREAD.to_string()));    assert!(carries(&opened.rows, "cotton_emails", OLD_EMAIL));    assert!(carries(&opened.rows, "cotton_email_participants", OLD_PARTICIPANT));    let folded = crate::fold::fold_pulled(&phone, &opened.ops).unwrap();    assert!(folded.rejected.is_empty(), "{folded:?}");    assert!(held("cotton_email_participants", OLD_PARTICIPANT));    // A status is never fetched by a phone; a Mac opens anything.    let refused = open(&db, &keep, "cotton_stories", STORY, 0, NOW);    assert!(matches!(&refused, Err(StoreError::Refused(why)) if why.contains(NEVER_REFUSAL)), "{refused:?}");    let mac = Keep::of_device(&db, MAC).unwrap();    assert_eq!(open(&db, &mac, "cotton_stories", STORY, 0, NOW).unwrap().rows.len(), 1);    // A row this file does not hold answers nothing; a table no device is    // sent is refused.    assert!(open(&db, &keep, "cotton_emails", "no-such-email", 0, NOW).unwrap().ops.is_empty());    assert!(open(&db, &keep, "cotton_mcp_audit", "x", 0, NOW).is_err());}/// RULE: a keep rule is one row per (device, kind, target), written as a/// minted change, and only a rule somebody could keep is written: a table/// rule names a table a rule may narrow and says all, none or days:N; a group/// or a record is kept always; no record of a table never kept is pinned./// Clearing a rule is the device keeping everything of it again.#[test]fn a_rule_is_one_row_and_only_a_rule_somebody_could_keep_is_written() {    let db = household();    let mut ids = crate::protocol::ulid::Monotonic::new(counter_seed());    let mut set = |kind: &str, target: &str, rule: &str, at: i64| {        set_rule(&db, WORKSPACE, PHONE, kind, target, rule, owner(), at, &mut ids, Held::Served)    };    for (kind, target, rule) in [        (KIND_TABLE, "cotton_email_threads", "days:0"),        (KIND_TABLE, "cotton_email_threads", "days:"),        (KIND_TABLE, "cotton_email_threads", "days:9x"),        (KIND_TABLE, "cotton_email_threads", "always"),        // Not a table a rule may narrow: the device's own rows.        (KIND_TABLE, "cotton_devices", "none"),        (KIND_TABLE, "cotton_device_keep", "none"),        (KIND_GROUP, "no-such-group", ALWAYS),        (KIND_RECORD, "cotton_emails", ALWAYS),        (KIND_RECORD, "cotton_mcp_audit:x", ALWAYS),        (KIND_RECORD, "cotton_emails:email-old", "none"),        ("tool", "photo", "all"),    ] {        let refused = set(kind, target, rule, NOW);        assert!(matches!(refused, Err(StoreError::Refused(_))), "{kind} {target} {rule}: {refused:?}");    }    assert!(rules_of(&db, PHONE).unwrap().is_empty());    let first = set(KIND_TABLE, "cotton_email_threads", "days:90", NOW).unwrap();    let again = set(KIND_TABLE, "cotton_email_threads", "days:30", NOW + 1_000).unwrap();    assert_eq!(first, again);    set(KIND_RECORD, &record_target_of("cotton_emails", OLD_EMAIL), ALWAYS, NOW + 2_000).unwrap();    let rules = rules_of(&db, PHONE).unwrap();    assert_eq!(rules.len(), 2);    assert_eq!(rules.iter().find(|r| r.kind == KIND_TABLE).unwrap().rule, "days:30");    let keep = Keep::of_device(&db, PHONE).unwrap();    assert_eq!(keep.table_rule("cotton_email_threads"), TableRule::Days(30));    // The rule is a receipt of this file like any other row: it travels.    assert!(page(&db).iter().any(|op| op.table == TABLE && op.row_id == first));    // Never is never: once statuses are never kept, none is pinned.    set(KIND_TABLE, "cotton_stories", "none", NOW + 3_000).unwrap();    let refused = set(KIND_RECORD, &record_target_of("cotton_stories", STORY), ALWAYS, NOW + 4_000);    assert!(matches!(refused, Err(StoreError::Refused(_))), "{refused:?}");    // Cleared, the table is back to its default; clearing nothing is no write.    assert!(clear_rule(&db, PHONE, KIND_TABLE, "cotton_email_threads", owner(), NOW + 5_000, &mut ids, Held::Served).unwrap());    assert!(!clear_rule(&db, PHONE, KIND_TABLE, "cotton_email_threads", owner(), NOW + 6_000, &mut ids, Held::Served).unwrap());    assert_eq!(        Keep::of_device(&db, PHONE).unwrap().table_rule("cotton_email_threads"),        TableRule::Days(PHONE_KEEP_DAYS),        "cleared, the table is back to a phone's default"    );}/// RULE: every table a keep rule may narrow names a real table a device is/// sent and a real date column of it — a horizon read from a column that is/// not there would keep every row for ever and say nothing.#[test]fn every_narrowable_table_names_a_real_date_column() {    for (table, column) in NARROWABLE {        let spec = spec_for(table).unwrap_or_else(|| panic!("{table} is no table"));        assert!(is_handed_over(spec.name), "{table} is never sent to a device");        assert!(            spec.columns.iter().any(|(name, codec)| name == column && *codec == crate::schema::decl::Codec::Timestamp),            "{table}.{column} is not a date column"        );    }    for (table, _rule, why) in PHONE_DEFAULTS {        assert!(age_column(table).is_some(), "{table} has a default and is not narrowable");        assert!(!why.trim().is_empty(), "{table}'s default says why");    }    assert_eq!(TableRule::parse("days:90"), Some(TableRule::Days(90)));    assert_eq!(TableRule::parse(&TableRule::Days(7).as_text()), Some(TableRule::Days(7)));    assert_eq!(TableRule::parse("days:007"), None);}// ── the device's side: what leaves, what enters, the first copy ─────────const OLDER_THREAD: &str = "thread-older";fn holds(db: &Driver, table: &str, id: &str) -> bool {    db.get(&format!("SELECT 1 AS x FROM {table} WHERE id = ?"), &[text(id)]).unwrap().is_some()}/// How many receipts — writes and retracts — a file holds of one row.fn receipts(db: &Driver, table: &str, id: &str) -> i64 {    db.get(        "SELECT (SELECT COUNT(*) FROM _writes WHERE tbl = ?1 AND row_id = ?2) \              + (SELECT COUNT(*) FROM _tombstones WHERE tbl = ?1 AND row_id = ?2) AS n",        &[text(table), text(id)],    )    .unwrap()    .and_then(|row| row.int("n"))    .unwrap_or(0)}fn count(db: &Driver, table: &str) -> i64 {    db.get(&format!("SELECT COUNT(*) AS n FROM {table}"), &[]).unwrap().and_then(|row| row.int("n")).unwrap_or(0)}/// A phone's own file after folding `ops`, knowing itself as a phone.fn phone_with(ops: Vec<CottonOp>) -> Driver {    let phone = seeded_file("device:phone");    let ops: Vec<CottonOp> = ops.into_iter().filter(|op| op.table != "cotton_workspaces").collect();    let folded = crate::fold::fold_pulled(&phone, &ops).unwrap();    assert!(folded.rejected.is_empty(), "{folded:?}");    device(&phone, PHONE, Some("ios"));    // The phone's copy names the Mac it syncs from, as every joined phone's does.    device(&phone, MAC, Some("mac"));    phone}/// A change to a row, folded where it is made; the op, for a peer to fold.fn fold_change(db: &Driver, table: &str, row_id: &str, patch: serde_json::Value, ms: i64) -> CottonOp {    let hlc = format!("{ms:013}:0000:{AUTHOR}");    let change = crate::mint::Change::update(table, row_id, patch.as_object().cloned().expect("a patch is an object"));    let op = crate::wire::op_of_change(db, &change, &hlc, AUTHOR, &owner(), format!("op-change-{table}-{row_id}-{ms}"))        .expect("the change's receipt");    let folded = crate::fold::fold_ops(db, std::slice::from_ref(&op)).expect("the change folds");    assert!(folded.rejected.is_empty(), "{folded:?}");    op}/// A hand-picked group of email threads (`cotton_groups`) holding `member`.fn group(db: &Driver, id: &str, member: &str, ms: i64) {    fold_create(        db,        "cotton_groups",        id,        json!({"id": id, "workspace_id": WORKSPACE, "table_id": "email_thread", "name": "Taxes",               "created_at": "2026-10-01T00:00:00.000Z", "updated_at": "2026-10-01T00:00:00.000Z"}),        AUTHOR,        ms,    );    join(db, id, member, 1.0, ms);}/// `member` joins the group at `place`: its own `cotton_group_members` row.fn join(db: &Driver, group: &str, member: &str, place: f64, ms: i64) {    let row = crate::protocol::derived_id::group_member_id(group, member);    fold_create(        db,        "cotton_group_members",        &row,        json!({"id": row, "workspace_id": WORKSPACE, "group_id": group, "record_id": member, "place": place,               "created_at": "2026-10-01T00:00:00.000Z", "updated_at": "2026-10-01T00:00:00.000Z"}),        AUTHOR,        ms,    );}/// `member` leaves the group: its member row is retracted.fn leave_group(db: &Driver, group: &str, member: &str, ms: i64) {    let row = crate::protocol::derived_id::group_member_id(group, member);    let hlc = format!("{ms:013}:0000:{AUTHOR}");    let change = crate::mint::Change::retract("cotton_group_members", &row);    let op = crate::wire::op_of_change(db, &change, &hlc, AUTHOR, &owner(), format!("op-leave-{row}-{ms}"))        .expect("the retract's receipt");    let folded = crate::fold::fold_ops(db, std::slice::from_ref(&op)).expect("the retract folds");    assert!(folded.rejected.is_empty(), "{folded:?}");}fn fetch_line(db: &Driver, table: &str) -> (Option<String>, Option<String>, Option<String>) {    let line = db        .get("SELECT covered, target, after FROM _keep_fetch WHERE tbl = ?", &[text(table)])        .unwrap()        .unwrap_or_else(|| panic!("{table} has no line of what this copy is complete for"));    (        line.text("covered").map(str::to_string),        line.text("target").map(str::to_string),        line.text("after").map(str::to_string),    )}/// One pass of the phone's widening against the serving Mac's file: every/// fetch its rules owe, asked of the Mac's judge a page at a time, folded, and/// written down. Answers the rows that were restated.fn widen(mac: &Driver, phone: &Driver) -> Vec<(String, String)> {    let mut rows = Vec::new();    for owed in widenings(phone, &Keep::of_device(phone, PHONE).unwrap()).unwrap() {        let mut after = owed.after.clone();        loop {            let answer = open_table(mac, &Keep::of_device(mac, PHONE).unwrap(), &owed.table, &after, NOW).unwrap();            let folded = fold_fetched(phone, &answer.ops, NOW).unwrap();            assert!(folded.rejected.is_empty(), "{folded:?}");            widened(phone, &owed.table, &owed.target, &answer.reached, answer.more).unwrap();            rows.extend(answer.rows);            if !answer.more {                break;            }            after = answer.reached;        }    }    rows}/// RULE: a keep rule that is widened brings its rows back — the rows a narrower rule left out were never sent, so the phone cannot name them: it keeps a line of what its copy is complete for, and when its rule comes to keep more it asks the serving Mac for the table and is answered every row its rules now keep, whole (a thread with its emails and participants); a rule that narrows, or stays, owes no fetch; a fetch is for one rule and starts again when the rule changes; a table that is never kept is never answered; and a Mac, which keeps everything, never owes one.#[test]fn a_widened_rule_brings_its_rows_back_by_table() {    const THREADS: &str = "cotton_email_threads";    let mac = household();    rule_row(&mac, PHONE, KIND_TABLE, THREADS, "days:90");    let sent = Keep::of_device(&mac, PHONE).unwrap().leave_out(&mac, page(&mac), NOW).unwrap();    let phone = phone_with(sent);    let both = |rule: &str| {        rule_row(&mac, PHONE, KIND_TABLE, THREADS, rule);        rule_row(&phone, PHONE, KIND_TABLE, THREADS, rule);    };    both("days:90");    assert!(!holds(&phone, THREADS, OLD_THREAD) && receipts(&phone, THREADS, OLD_THREAD) == 0, "never heard of");    // The first look: this copy is complete for the rule it has. Nothing owed.    assert!(widen(&mac, &phone).is_empty());    assert_eq!(fetch_line(&phone, THREADS), (Some("days:90".into()), None, None));    assert_eq!(fetch_line(&phone, "cotton_stories").0.as_deref(), Some("none"), "the default is a rule too");    // Narrowed: complete for the narrower rule at once, and nothing is asked.    both("days:30");    assert!(widen(&mac, &phone).is_empty());    assert_eq!(fetch_line(&phone, THREADS), (Some("days:30".into()), None, None));    // WIDENED past the January thread: a fetch is owed, from the beginning.    both("days:400");    let owed = widenings(&phone, &Keep::of_device(&phone, PHONE).unwrap()).unwrap();    assert_eq!(owed, vec![Widening { table: THREADS.into(), target: "days:400".into(), after: String::new() }]);    assert_eq!(fetch_line(&phone, THREADS), (Some("days:30".into()), Some("days:400".into()), Some(String::new())));    // A page answered for a rule the phone no longer has is not written down.    widened(&phone, THREADS, "days:365", "zzz", false).unwrap();    assert_eq!(fetch_line(&phone, THREADS).0.as_deref(), Some("days:30"), "still owed");    let restated = widen(&mac, &phone);    for (table, id) in [(THREADS, OLD_THREAD), ("cotton_emails", OLD_EMAIL), ("cotton_email_participants", OLD_PARTICIPANT)] {        assert!(carries(&restated, table, id), "{table} {id} was not answered");        assert!(holds(&phone, table, id), "{table} {id} did not come back");    }    assert!(holds(&phone, THREADS, NEW_THREAD) && holds(&phone, "cotton_emails", NEW_EMAIL));    assert_eq!(count(&phone, "_on_demand"), 0, "kept by the rule: no thirty-day line");    assert_eq!(fetch_line(&phone, THREADS), (Some("days:400".into()), None, None));    assert!(widen(&mac, &phone).is_empty(), "complete: the next pass asks for nothing");    // Narrowed away again and then CLEARED: no rule is a phone's default, six    // months of mail, which January's thread is still past; `all` is the widest.    both("days:90");    assert!(leave(&phone, &Keep::of_device(&phone, PHONE).unwrap(), NOW, 100).unwrap().dropped >= 3);    assert!(widen(&mac, &phone).is_empty());    assert!(!holds(&phone, THREADS, OLD_THREAD));    for db in [&mac, &phone] {        db.run("DELETE FROM cotton_device_keep WHERE target = ?", &[text(THREADS)]).unwrap();    }    assert!(!carries(&widen(&mac, &phone), THREADS, OLD_THREAD));    assert_eq!(fetch_line(&phone, THREADS).0, Some(format!("days:{PHONE_KEEP_DAYS}")));    both("all");    assert!(carries(&widen(&mac, &phone), THREADS, OLD_THREAD));    assert!(holds(&phone, THREADS, OLD_THREAD) && holds(&phone, "cotton_emails", OLD_EMAIL));    assert_eq!(fetch_line(&phone, THREADS), (Some("all".into()), None, None));    // A table that is never kept is never answered, and one no rule may narrow    // is not answered this way at all.    let keep = Keep::of_device(&mac, PHONE).unwrap();    assert!(open_table(&mac, &keep, "cotton_stories", "", NOW).unwrap_err().to_string().contains(NEVER_REFUSAL));    assert!(open_table(&mac, &keep, "cotton_devices", "", NOW).is_err());    // …until its own rule is widened: the owner's `all` replaces the default.    for db in [&mac, &phone] {        rule_row(db, PHONE, KIND_TABLE, "cotton_stories", "all");    }    assert!(carries(&widen(&mac, &phone), "cotton_stories", STORY));    assert!(holds(&phone, "cotton_stories", STORY));    // A Mac keeps everything: its lines say `all` and it never owes a fetch.    rule_row(&mac, MAC, KIND_TABLE, THREADS, "days:1");    assert!(widenings(&mac, &Keep::of_device(&mac, MAC).unwrap()).unwrap().is_empty());    assert_eq!(fetch_line(&mac, THREADS).0.as_deref(), Some("all"));}/// RULE: a widened table is answered a page at a time and a fetch goes on from where it stopped — an answer stops after the record that brings it to a page of rows, says the key it reached and that there is more, and the next answer starts beyond that key, so every row the rules keep is answered once across the pages and none twice.#[test]fn a_widened_table_is_answered_a_page_at_a_time_from_where_it_stopped() {    const THREADS: &str = "cotton_email_threads";    let mac = household();    for n in 0..520 {        thread(&mac, &format!("page-{n:04}"), "2026-10-09T09:00:00.000Z", 100 + n);    }    rule_row(&mac, PHONE, KIND_TABLE, THREADS, "days:90");    let keep = Keep::of_device(&mac, PHONE).unwrap();    let first = open_table(&mac, &keep, THREADS, "", NOW).unwrap();    assert!(first.more);    assert_eq!(first.rows.len(), OPEN_PAGE_ROWS);    assert_eq!(first.reached, "page-0499");    let second = open_table(&mac, &keep, THREADS, &first.reached, NOW).unwrap();    assert!(!second.more);    let threads = |rows: &[(String, String)]| rows.iter().filter(|(table, _)| table == THREADS).count();    assert_eq!(threads(&first.rows) + threads(&second.rows), 521, "the 520 and this week's; January's is outside");    assert!(carries(&second.rows, THREADS, NEW_THREAD) && carries(&second.rows, "cotton_emails", NEW_EMAIL));    assert!(!carries(&second.rows, THREADS, OLD_THREAD) && !carries(&first.rows, THREADS, OLD_THREAD));    assert!(second.rows.iter().all(|row| !first.rows.contains(row)), "no row is answered twice");}/// RULE: a status is never on a phone, and no rule row is needed to say so —/// it is the phone's default (`PHONE_DEFAULTS`): not in a page, not when/// opened. Every Mac holds them all, mail stays whole on a phone, and a rule/// a person stores for the table replaces the default.#[test]fn a_status_is_never_on_a_phone_by_default() {    let db = household();    let sent = sent_to(&db, PHONE);    assert!(!carries(&sent, "cotton_stories", STORY));    assert!(!carries(&sent, "cotton_email_threads", OLD_THREAD), "January's mail is past the six months a phone keeps");    assert!(carries(&sent, "cotton_email_threads", NEW_THREAD), "this week's is inside them");    assert!(carries(&sent_to(&db, MAC), "cotton_stories", STORY));    let keep = Keep::of_device(&db, PHONE).unwrap();    assert_eq!(keep.table_rule("cotton_stories"), TableRule::None);    let refused = open(&db, &keep, "cotton_stories", STORY, 0, NOW);    assert!(matches!(&refused, Err(StoreError::Refused(why)) if why.contains(NEVER_REFUSAL)), "{refused:?}");    rule_row(&db, PHONE, KIND_TABLE, "cotton_stories", "all");    assert!(carries(&sent_to(&db, PHONE), "cotton_stories", STORY));}/// RULE: what a phone's rules no longer keep leaves the phone's own copy —/// the row, the rows it owns, and every receipt of them — and nothing about/// it travels: no tombstone, nothing queued, so the row is deleted nowhere./// A row the phone still owes somebody a change to is never dropped, a pass/// stops at its limit and says there is more, and what the rules keep stays.#[test]fn what_leaves_the_rules_leaves_the_phone_and_nothing_travels() {    let db = household();    thread(&db, OLDER_THREAD, "2025-01-05T09:00:00.000Z", 16);    // The phone as every phone was before a rule: holding everything.    let phone = phone_with(page(&db));    assert!(holds(&phone, "cotton_stories", STORY) && holds(&phone, "cotton_emails", OLD_EMAIL));    rule_row(&phone, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");    let keep = Keep::of_device(&phone, PHONE).unwrap();    let queued = count(&phone, "_outbox");    // An email of the old thread carries a change nobody else has yet.    phone.run("UPDATE _writes SET held = 1 WHERE tbl = 'cotton_emails' AND row_id = ?", &[text(OLD_EMAIL)]).unwrap();    phone.run("UPDATE _writes SET held = 1 WHERE tbl = 'cotton_email_threads' AND row_id = ?", &[text(OLDER_THREAD)]).unwrap();    let left = leave(&phone, &keep, NOW, 100).unwrap();    assert_eq!((left.dropped, left.owed, left.more), (1, 2, false), "{left:?}");    assert!(!holds(&phone, "cotton_stories", STORY), "the status went");    assert!(holds(&phone, "cotton_email_threads", OLD_THREAD), "a thread is not dropped from under an owed email");    assert!(holds(&phone, "cotton_emails", OLD_EMAIL));    phone.run("UPDATE _writes SET held = 0", &[]).unwrap();    // One record a pass: the first old thread goes whole, and there is more.    let left = leave(&phone, &keep, NOW, 1).unwrap();    assert!(left.more, "{left:?}");    assert!(left.dropped >= 1);    let left = leave(&phone, &keep, NOW, 100).unwrap();    assert!(!left.more && left.owed == 0, "{left:?}");    for (table, id) in [        ("cotton_email_threads", OLD_THREAD),        ("cotton_emails", OLD_EMAIL),        ("cotton_email_participants", OLD_PARTICIPANT),        ("cotton_email_threads", OLDER_THREAD),        ("cotton_stories", STORY),    ] {        assert!(!holds(&phone, table, id), "{table} {id} is still on the phone");        assert_eq!(receipts(&phone, table, id), 0, "{table} {id} left a receipt behind");    }    assert!(holds(&phone, "cotton_email_threads", NEW_THREAD) && holds(&phone, "cotton_emails", NEW_EMAIL));    crate::test_support::assert_receipt_owners_are_attached(&phone);    assert!(phone.get("SELECT 1 FROM _writes_owners WHERE tbl = 'cotton_emails' AND owner = ?", &[text(OLD_THREAD)]).unwrap().is_none());    assert_eq!(count(&phone, "_outbox"), queued, "a local drop queues nothing");    assert_eq!(leave(&phone, &keep, NOW, 100).unwrap(), Left::default(), "a settled copy is left alone");    // A Mac that holds the same rows and the same rule rows drops nothing.    let mac = phone_with(page(&db));    rule_row(&mac, MAC, KIND_TABLE, "cotton_email_threads", "days:90");    rule_row(&mac, MAC, KIND_TABLE, "cotton_stories", "none");    let keep = Keep::of_device(&mac, MAC).unwrap();    assert_eq!(leave(&mac, &keep, NOW, 100).unwrap(), Left::default());    assert!(holds(&mac, "cotton_stories", STORY) && holds(&mac, "cotton_email_threads", OLD_THREAD));}/// RULE: a row opened from outside a phone's rules is dropped again after/// thirty days unopened — counted from its last opening, and never while a/// rule has since come to keep it (then it only loses its line in the/// on-demand ledger).#[test]fn a_row_opened_from_outside_the_rules_leaves_again_after_thirty_days_unopened() {    let db = household();    rule_row(&db, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");    let serving = Keep::of_device(&db, PHONE).unwrap();    let phone = phone_with(serving.leave_out(&db, page(&db), NOW).unwrap());    rule_row(&phone, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");    assert!(!holds(&phone, "cotton_email_threads", OLD_THREAD));    let opened = open(&db, &serving, "cotton_emails", OLD_EMAIL, 0, NOW).unwrap();    fold_opened(&phone, &opened.ops, &opened.rows, NOW).unwrap();    assert!(holds(&phone, "cotton_email_threads", OLD_THREAD) && holds(&phone, "cotton_emails", OLD_EMAIL));    let keep = Keep::of_device(&phone, PHONE).unwrap();    assert_eq!(leave(&phone, &keep, NOW + 29 * DAY_MS, 100).unwrap().dropped, 0);    // Opened again on day 29: day 45 is sixteen days unopened.    record_opened(&phone, &opened.rows, NOW + 29 * DAY_MS).unwrap();    assert_eq!(leave(&phone, &keep, NOW + 45 * DAY_MS, 100).unwrap().dropped, 0);    assert!(holds(&phone, "cotton_emails", OLD_EMAIL));    // Pinned since: at day 60 it stays, kept by the rule and no longer on demand.    rule_row(&phone, PHONE, KIND_RECORD, &record_target_of("cotton_email_threads", OLD_THREAD), ALWAYS);    let pinned = Keep::of_device(&phone, PHONE).unwrap();    assert_eq!(leave(&phone, &pinned, NOW + 60 * DAY_MS, 100).unwrap().dropped, 0);    assert_eq!(count(&phone, "_on_demand"), 0);    assert!(holds(&phone, "cotton_emails", OLD_EMAIL));    phone.run("DELETE FROM cotton_device_keep WHERE kind = 'record'", &[]).unwrap();    // Opened once more, then thirty-one days of nothing.    record_opened(&phone, &opened.rows, NOW + 60 * DAY_MS).unwrap();    assert_eq!(leave(&phone, &keep, NOW + 80 * DAY_MS, 100).unwrap().dropped, 0);    // (By day 91 this week's thread is past the horizon too, and goes with it.)    let left = leave(&phone, &keep, NOW + 91 * DAY_MS, 100).unwrap();    assert!(left.dropped >= 2, "{left:?}");    assert!(!holds(&phone, "cotton_email_threads", OLD_THREAD) && !holds(&phone, "cotton_emails", OLD_EMAIL));    assert_eq!(count(&phone, "_on_demand"), 0);    assert_eq!(receipts(&phone, "cotton_emails", OLD_EMAIL), 0);}/// RULE: what comes inside a phone's rules after it was passed over is asked/// for whole. An old thread a new message revives arrives as a change with no/// create — the fold holds it dormant, never a partial row — and the phone/// names the THREAD as wanted; so is a pinned record that is not here, and a/// record that joins a kept group. Fetched, it is kept by its rule: no/// on-demand line, and nothing drops it. A record that leaves a kept group/// leaves the phone.#[test]fn what_enters_the_rules_is_asked_for_whole_and_what_leaves_a_kept_group_goes() {    let db = household();    thread(&db, OLDER_THREAD, "2025-01-05T09:00:00.000Z", 16);    rule_row(&db, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");    let serving = Keep::of_device(&db, PHONE).unwrap();    let phone = phone_with(serving.leave_out(&db, page(&db), NOW).unwrap());    rule_row(&phone, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");    let keep = Keep::of_device(&phone, PHONE).unwrap();    assert!(wanted(&phone, &keep, 10).unwrap().is_empty());    // A reply lands in the January thread: its date moves inside the horizon.    let revived = fold_change(        &db,        "cotton_email_threads",        OLD_THREAD,        json!({"last_at": "2026-10-11T09:00:00.000Z", "updated_at": "2026-10-11T09:00:00.000Z"}),        30,    );    email(&db, "email-reply", OLD_THREAD, "2026-10-11T09:00:00.000Z", 31);    // The page after the phone's cursors carries the change and the reply —    // the thread is inside now — and not the creates it was passed over on.    let later: Vec<CottonOp> = serving        .leave_out(&db, page(&db), NOW)        .unwrap()        .into_iter()        .filter(|op| op.hlc >= revived.hlc && op.table.starts_with("cotton_email"))        .collect();    assert_eq!(later.len(), 2, "{later:?}");    let folded = crate::fold::fold_pulled(&phone, &later).unwrap();    assert!(folded.rejected.is_empty(), "{folded:?}");    assert!(!holds(&phone, "cotton_email_threads", OLD_THREAD), "a change with no create is no row");    assert!(!holds(&phone, "cotton_emails", "email-reply"), "a reply waits for its thread");    assert_eq!(        wanted(&phone, &keep, 10).unwrap(),        vec![("cotton_email_threads".to_string(), OLD_THREAD.to_string())],        "the thread is asked for once, for itself and for the reply under it"    );    let fetched = open(&db, &serving, "cotton_email_threads", OLD_THREAD, 0, NOW).unwrap();    fold_fetched(&phone, &fetched.ops, NOW).unwrap();    for (table, id) in        [("cotton_email_threads", OLD_THREAD), ("cotton_emails", OLD_EMAIL), ("cotton_emails", "email-reply")]    {        assert!(holds(&phone, table, id), "{table} {id} did not land");    }    assert!(wanted(&phone, &keep, 10).unwrap().is_empty());    assert_eq!(count(&phone, "_on_demand"), 0, "a kept row is not an on-demand row");    assert_eq!(leave(&phone, &keep, NOW, 100).unwrap().dropped, 0);    // A pin set on another device arrives as a rule row.    let older = ("cotton_email_threads".to_string(), OLDER_THREAD.to_string());    rule_row(&phone, PHONE, KIND_RECORD, &record_target_of("cotton_email_threads", OLDER_THREAD), ALWAYS);    assert_eq!(wanted(&phone, &Keep::of_device(&phone, PHONE).unwrap(), 10).unwrap(), vec![older.clone()]);    phone.run("DELETE FROM cotton_device_keep WHERE kind = 'record'", &[]).unwrap();    assert!(wanted(&phone, &Keep::of_device(&phone, PHONE).unwrap(), 10).unwrap().is_empty());    // A kept group, and a record that joins it.    group(&phone, "group-1", NEW_THREAD, 40);    rule_row(&phone, PHONE, KIND_GROUP, "group-1", ALWAYS);    assert!(wanted(&phone, &Keep::of_device(&phone, PHONE).unwrap(), 10).unwrap().is_empty());    join(&phone, "group-1", OLDER_THREAD, 2.0, 41);    let kept = Keep::of_device(&phone, PHONE).unwrap();    assert_eq!(wanted(&phone, &kept, 10).unwrap(), vec![older.clone()]);    assert!(wanted(&phone, &kept, 0).unwrap().is_empty(), "a pass that may fetch nothing asks for nothing");    let fetched = open(&db, &serving, "cotton_email_threads", OLDER_THREAD, 0, NOW).unwrap();    fold_fetched(&phone, &fetched.ops, NOW).unwrap();    assert!(holds(&phone, "cotton_email_threads", OLDER_THREAD));    assert!(wanted(&phone, &kept, 10).unwrap().is_empty());    assert_eq!(leave(&phone, &kept, NOW, 100).unwrap().dropped, 0, "a member of a kept group stays past its horizon");    // It leaves the group: the phone drops it.    leave_group(&phone, "group-1", OLDER_THREAD, 42);    assert!(wanted(&phone, &kept, 10).unwrap().is_empty());    assert_eq!(leave(&phone, &kept, NOW, 100).unwrap().dropped, 1);    assert!(!holds(&phone, "cotton_email_threads", OLDER_THREAD));    assert!(holds(&phone, "cotton_email_threads", OLD_THREAD), "the revived thread is inside its horizon");}/// RULE: a phone's first copy is cut by its rules — the snapshot it starts/// from holds what its pages would have carried and nothing its rules leave/// out, not a row, not a receipt and not a byte — and a Mac's copy is cut of/// nothing, whatever a rule row names it.#[test]fn a_phones_first_copy_is_cut_by_its_rules_and_a_macs_is_whole() {    let copy = household();    rule_row(&copy, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");    // The serving Mac's own ledger of the bytes it holds: a first copy carries    // NO BYTES and no claim to any — a phone starts with none and fetches an    // original when its record is opened.    copy.run(        "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, state, created_at, updated_at) \         VALUES ('synthetic/photos/held-by-the-mac.jpg', ?, 'synthetic', 'image/jpeg', 10, '/synthetic/held-by-the-mac.jpg', 'synced', '2026-01-01', '2026-01-01')",        &[text(WORKSPACE)],    )    .unwrap();    assert!(copy.get("SELECT 1 FROM _writes_owners WHERE tbl = 'cotton_emails' AND owner = ?", &[text(OLD_THREAD)]).unwrap().is_some());    let ceilings = crate::cursors::seen_ceiling(&copy).unwrap();    let counts = crate::snapshot::strip_for_device(&copy, PHONE, NOW).unwrap();    assert_eq!(crate::cursors::read_cursors(&copy).unwrap(), ceilings);    crate::test_support::assert_receipt_owners_are_attached(&copy);    assert!(copy.get("SELECT 1 FROM _writes_owners WHERE tbl = 'cotton_emails' AND owner = ?", &[text(OLD_THREAD)]).unwrap().is_none());    // The cut goes out a table at a time, its foreign keys checked whole.    assert!(copy.all("PRAGMA foreign_key_check", &[]).unwrap().is_empty(), "the cut left a child without its row");    assert_eq!(count(&copy, "_media"), 0, "the first copy claims a byte the phone does not hold");    // And it says what it is complete for: the rules it was cut by — so a    // rule widened before the phone first looks is still fetched.    assert_eq!(fetch_line(&copy, "cotton_email_threads").0.as_deref(), Some("days:90"));    assert_eq!(fetch_line(&copy, "cotton_stories").0.as_deref(), Some("none"));    for (table, id) in [        ("cotton_email_threads", OLD_THREAD),        ("cotton_emails", OLD_EMAIL),        ("cotton_email_participants", OLD_PARTICIPANT),        ("cotton_stories", STORY),    ] {        assert!(!holds(&copy, table, id), "{table} {id} is in the phone's first copy");        assert_eq!(receipts(&copy, table, id), 0, "{table} {id} left a receipt in the copy");    }    assert!(holds(&copy, "cotton_email_threads", NEW_THREAD) && holds(&copy, "cotton_emails", NEW_EMAIL));    assert!(        counts.emptied.iter().any(|(what, rows)| what.contains("keep rules") && *rows == 4),        "{:?}",        counts.emptied    );    let whole = household();    rule_row(&whole, MAC, KIND_TABLE, "cotton_email_threads", "days:90");    rule_row(&whole, MAC, KIND_TABLE, "cotton_stories", "none");    let counts = crate::snapshot::strip_for_device(&whole, MAC, NOW).unwrap();    assert!(holds(&whole, "cotton_email_threads", OLD_THREAD) && holds(&whole, "cotton_stories", STORY));    assert!(!counts.emptied.iter().any(|(what, _)| what.contains("keep rules")), "{:?}", counts.emptied);    assert_eq!(fetch_line(&whole, "cotton_email_threads").0.as_deref(), Some("all"));}// ── the mail index follows a local drop ─────────────────────────────────const WORD_EMAIL: &str = "email-zanzibar";const NEWEST_EMAIL: &str = "email-newest";/// The emails `index` finds for `word`, by id; an entry whose row is not in/// `cotton_emails` any more answers `stale <rowid>` — a hit for a row the/// device no longer holds.fn found(db: &Driver, index: &str, word: &str) -> Vec<String> {    db.all(        &format!(            "SELECT coalesce(e.id, 'stale ' || f.rowid) AS id FROM (SELECT rowid FROM {index} WHERE {index} MATCH ?) f \             LEFT JOIN cotton_emails e ON e.rowid = f.rowid ORDER BY id"        ),        &[text(word)],    )    .unwrap()    .iter()    .map(|row| row.text("id").unwrap().to_string())    .collect()}/// An external-content index agrees with every row of its source.fn agrees(db: &Driver, index: &str) {    db.exec(&format!("INSERT INTO {index} ({index}, rank) VALUES ('integrity-check', 1)"))        .unwrap_or_else(|error| panic!("{index} disagrees with cotton_emails: {error}"));}/// RULE (keep's finding (3)): the mail indexes are kept by the same triggers/// on a LOCAL drop as on a fold — the drop reassembles the row out through/// the fold's own DELETE — so a phone that narrows its mail (a horizon, or a/// row opened once and left unopened) never keeps a hit for a row it no/// longer holds, and the row fetched again on open is found again at once./// The same holds while `fts_mail` is still FILLING (v122): a dropped row the/// fill had not reached was never in the index and is not retracted from it/// (for an external-content index that would be corruption), and the/// re-fetched row is written above the floor, where its trigger indexes it;/// the fill then never puts it in twice.#[test]fn a_local_drop_takes_its_hits_out_of_the_mail_index_and_a_fetch_puts_them_back() {    let db = household();    fold_create(        &db,        "cotton_emails",        WORD_EMAIL,        json!({"id": WORD_EMAIL, "workspace_id": WORKSPACE, "thread_id": OLD_THREAD, "external_id": WORD_EMAIL,               "subject": "The Zanzibar ferry", "body": "the zanzibar ferry leaves at noon",               "from_name": "Otter", "from_email": "otter@example.invalid",               "sent_at": "2026-01-05T10:00:00.000Z", "created_at": "2026-01-05T10:00:00.000Z"}),        AUTHOR,        17,    );    // The newest row is a kept one, so a fill that has taken one slice stops    // above the January mail.    email(&db, NEWEST_EMAIL, NEW_THREAD, "2026-10-11T09:00:00.000Z", 18);    rule_row(&db, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");    let serving = Keep::of_device(&db, PHONE).unwrap();    for mid_fill in [false, true] {        // The phone as every phone was before a rule: holding everything.        let phone = phone_with(page(&db));        if mid_fill {            // As the v122 move leaves it: empty, then one slice from the top.            phone.exec("INSERT INTO fts_mail (fts_mail) VALUES ('delete-all')").unwrap();            crate::fts_fill::begin(&phone, "fts_mail").unwrap();            crate::fts_fill::step(&phone, "fts_mail", 1).unwrap();            assert!(found(&phone, "fts_mail", "zanzibar").is_empty(), "the fill has not reached January");        } else {            assert_eq!(found(&phone, "fts_mail", "zanzibar"), vec![WORD_EMAIL]);            assert_eq!(found(&phone, "fts_mail", "otter"), vec![WORD_EMAIL]);        }        assert_eq!(found(&phone, "fts_emails", "zanzibar"), vec![WORD_EMAIL]);        rule_row(&phone, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");        let keep = Keep::of_device(&phone, PHONE).unwrap();        assert!(leave(&phone, &keep, NOW, 100).unwrap().dropped >= 3);        assert!(!holds(&phone, "cotton_emails", WORD_EMAIL));        for index in ["fts_mail", "fts_emails"] {            for word in ["zanzibar", "otter"] {                assert!(found(&phone, index, word).is_empty(), "mid_fill {mid_fill}: {index} still finds {word}");            }        }        agrees(&phone, "fts_emails");        let opened = open(&db, &serving, "cotton_emails", WORD_EMAIL, 0, NOW).unwrap();        fold_opened(&phone, &opened.ops, &opened.rows, NOW).unwrap();        assert!(holds(&phone, "cotton_emails", WORD_EMAIL));        for index in ["fts_mail", "fts_emails"] {            assert_eq!(found(&phone, index, "zanzibar"), vec![WORD_EMAIL], "mid_fill {mid_fill}: {index}");        }        assert_eq!(found(&phone, "fts_mail", "otter"), vec![WORD_EMAIL]);        while crate::fts_fill::step(&phone, "fts_mail", 1).unwrap().is_some_and(|step| !step.done) {}        assert!(crate::fts_fill::filling(&phone, "fts_mail").unwrap().is_none());        assert_eq!(found(&phone, "fts_mail", "zanzibar"), vec![WORD_EMAIL], "mid_fill {mid_fill}: found once");        agrees(&phone, "fts_mail");        agrees(&phone, "fts_emails");    }}/// RULE (sync programme lane C, 12 Oct 2026): a keep-rule FINGERPRINT names what a copy cut by those rules holds — equal for the same rules, different the moment a rule changes, and the same for every Mac (a Mac keeps everything, whatever a row says) — so the serving Mac hands an hour-old cut copy out again only to a device whose rules still cut it the same.#[test]fn a_keep_fingerprint_changes_with_the_rules_and_never_otherwise() {    let db = seeded_file(AUTHOR);    device(&db, PHONE, Some("ios"));    device(&db, MAC, Some("mac"));    let of = |device_id: &str| Keep::of_device(&db, device_id).expect("the rules").fingerprint();    let defaults = of(PHONE);    assert_eq!(defaults, of(PHONE), "the same rules, the same fingerprint");    assert_ne!(defaults, of(MAC), "a phone's defaults narrow; a Mac keeps everything");    assert_eq!(of(MAC), Keep::everything().fingerprint());    rule_row(&db, PHONE, KIND_TABLE, "cotton_email_threads", "days:30");    let thirty = of(PHONE);    assert_ne!(thirty, defaults, "a narrowed table is a different cut");    rule_row(&db, PHONE, KIND_TABLE, "cotton_email_threads", "days:90");    assert_ne!(of(PHONE), thirty, "a wider horizon is a different cut");    rule_row(&db, PHONE, KIND_GROUP, "group-kept", "always");    assert_ne!(of(PHONE), thirty);    // A Mac's rows are never read: a rule written for it changes nothing.    rule_row(&db, MAC, KIND_TABLE, "cotton_email_threads", "days:30");    assert_eq!(of(MAC), Keep::everything().fingerprint());}/// RULE: Paging a never-kept table judges each owed row once even when it holds more than a page of writes and a tombstone; retention must preserve all those receipts.#[test]fn never_kept_pages_preserve_and_count_overlapping_owed_rows_once() {    let db = seeded_file("device:phone");    db.exec("WITH RECURSIVE n(x) AS (VALUES(0) UNION ALL SELECT x+1 FROM n WHERE x<129) INSERT INTO _writes(tbl,row_id,hlc,held) SELECT 'cotton_stories','owed',printf('%08d',x),1 FROM n; INSERT INTO _tombstones(tbl,row_id,hlc,op_id,author,actor,bytes,held) VALUES ('cotton_stories','owed','stamp','op','author','actor',X'7B7D',1)").unwrap();    let mut keep = Keep::everything();    keep.tables.insert("cotton_stories".into(), TableRule::None);    let left = leave(&db, &keep, NOW, 100).unwrap();    assert_eq!((left.dropped, left.owed, left.more), (0, 1, false));    assert_eq!(receipts(&db, "cotton_stories", "owed"), 131);}/// RULE: a phone with a Mac behind it keeps six months of chats and import/// runs by default, as it keeps six months of mail: an older chat leaves with/// its messages, a newer one stays (owner, 23 Oct 2026).#[test]fn a_phone_keeps_six_months_of_chats_and_imports_by_default() {    let db = household();    let chat = |id: &str, at: &str, ms: i64| {        fold_create(            &db,            "cotton_msg_threads",            id,            json!({"id": id, "workspace_id": WORKSPACE, "kind": "group", "title": "Invented chat",                   "last_message_at": at, "created_at": at, "updated_at": at}),            AUTHOR,            ms,        );        let message = format!("{id}-message");        fold_create(            &db,            "cotton_msg_messages",            &message,            json!({"id": message, "workspace_id": WORKSPACE, "thread_id": id, "direction": "in", "channel": "whatsapp",                   "origin": "imported", "body": "Invented words", "sent_at": at, "created_at": at}),            AUTHOR,            ms + 1,        );    };    chat("chat-old", "2026-01-05T09:00:00.000Z", 20);    chat("chat-new", "2026-10-10T09:00:00.000Z", 22);    for (id, at, ms) in [("import-old", "2026-01-05T09:00:00.000Z", 24), ("import-new", "2026-10-10T09:00:00.000Z", 25)] {        fold_create(            &db,            "cotton_imports",            id,            json!({"id": id, "workspace_id": WORKSPACE, "source": "messages", "title": "Invented import",                   "finished_at": at, "created_at": at}),            AUTHOR,            ms,        );    }    let sent = sent_to(&db, PHONE);    assert!(!carries(&sent, "cotton_msg_threads", "chat-old") && !carries(&sent, "cotton_msg_messages", "chat-old-message"));    assert!(carries(&sent, "cotton_msg_threads", "chat-new") && carries(&sent, "cotton_msg_messages", "chat-new-message"));    assert!(!carries(&sent, "cotton_imports", "import-old") && carries(&sent, "cotton_imports", "import-new"));    assert!(carries(&sent_to(&db, MAC), "cotton_msg_threads", "chat-old"), "a Mac keeps everything");}/// RULE: a phone that is its database's only home — no Mac in the file to/// answer for what it lets go (Rigby) — keeps everything: no default narrows/// it, and only a rule somebody stores does.#[test]fn a_phone_with_no_mac_behind_it_keeps_everything() {    let db = seeded_file("device:phone");    device(&db, PHONE, Some("ios"));    thread(&db, OLD_THREAD, "2026-01-05T09:00:00.000Z", 10);    let keep = Keep::of_device(&db, PHONE).unwrap();    assert!(!keep.narrows(), "{keep:?}");    assert_eq!(keep.table_rule("cotton_email_threads"), TableRule::All);    assert_eq!(keep.table_rule("cotton_stories"), TableRule::All);    assert_eq!(leave(&db, &keep, NOW, 100).unwrap().dropped, 0);    assert!(holds(&db, "cotton_email_threads", OLD_THREAD));    // An assistant's row or a runner's holds no file: neither is a Mac.    device(&db, "assistant-key", Some("assistant"));    device(&db, "runner-key", Some("linux"));    db.run("UPDATE cotton_devices SET scope = 'runner' WHERE device_id = 'runner-key'", &[]).unwrap();    assert!(!Keep::of_device(&db, PHONE).unwrap().narrows());    // A Linux host serving the whole file answers for it as a Mac does.    device(&db, "linux-host-key", Some("linux"));    assert_eq!(Keep::of_device(&db, PHONE).unwrap().table_rule("cotton_email_threads"), TableRule::Days(PHONE_KEEP_DAYS));    db.run("UPDATE cotton_devices SET revoked_at = '2026-02-01' WHERE device_id = 'linux-host-key'", &[]).unwrap();    assert!(!Keep::of_device(&db, PHONE).unwrap().narrows());    // A revoked Mac answers for nothing.    device(&db, MAC, Some("mac"));    db.run("UPDATE cotton_devices SET revoked_at = '2026-02-01' WHERE device_id = ?", &[text(MAC)]).unwrap();    assert!(!Keep::of_device(&db, PHONE).unwrap().narrows());    db.run("UPDATE cotton_devices SET revoked_at = NULL WHERE device_id = ?", &[text(MAC)]).unwrap();    assert_eq!(Keep::of_device(&db, PHONE).unwrap().table_rule("cotton_email_threads"), TableRule::Days(PHONE_KEEP_DAYS));}