Cotton code
290 lines · 19.0 KB · RustRaw
//! CONTACTS AT SIZE (coordinator, 28 Nov 2026): Contacts on an invented account the size of the owner's (1,500//! contacts, 300,000 messages, 150,000 mails, 20,000 calls, 30,000 photos with faces). Every name, number and//! address is invented. Each method is measured cold and warm, in SQLite's own steps (`Driver::thread_steps`: what//! it read, whichever way) and time; the bounds below are the guard, as `test/read-cost.test.ts` is on the server.//!//! `CONTACTS_AT_SIZE_PRINT=1` prints the table.use std::time::{Duration, Instant};use serde_json::{json, Value};use crate::handle::CottonHandle;const PEOPLE: i64 = 1_500;const MESSAGES: i64 = 300_000;const MAILS: i64 = 150_000;const CALLS: i64 = 20_000;const PHOTOS: i64 = 30_000;const GROUP_CHATS: i64 = 200;const EVENTS: i64 = 3_000;fn over(client: &crate::shell::client::ClientController, method: &str, request: &Value) -> Result<Value, crate::methods::MethodError> {    if super::METHODS.contains(&method) {        super::call(client, method, request)    } else if crate::phone::contacts_groups::METHODS.contains(&method) {        crate::phone::contacts_groups::call(client, method, request)    } else {        crate::phone::contacts_same::call(client, method, request)    }}fn sql(handle: &CottonHandle, text: &str) {    handle.client().with_writer(|replica| replica.driver.run(text, &[]).map(|_| ()).map_err(|e| format!("{e}: {text}"))).unwrap();}fn has(handle: &CottonHandle, table: &str) -> bool {    handle.client().with_writer(|r| r.driver.get(&format!("SELECT 1 AS one FROM sqlite_master WHERE type = 'table' AND name = '{table}'"), &[]).map_err(|e| e.to_string())).unwrap().is_some()}fn add_columns(handle: &CottonHandle, table: &str, columns: &[&str]) {    for column in columns {        let there = handle.client().with_writer(|r| r.driver.get(&format!("SELECT 1 AS one FROM pragma_table_info('{table}') WHERE name = '{column}'"), &[]).map_err(|e| e.to_string())).unwrap();        if there.is_none() {            sql(handle, &format!("ALTER TABLE {table} ADD COLUMN {column} TEXT"));        }    }}/// `INSERT INTO table (columns) SELECT exprs FROM s` over `n` = 1..=count, with every other NOT NULL column this/// copy's table has (and no default) filled: a whole number with 0, a fraction with 0.5, anything else with an invented `table-n`.fn fill(handle: &CottonHandle, table: &str, count: i64, given: &[(&str, String)]) {    let required: Vec<(String, String)> = handle        .client()        .with_writer(|r| {            Ok(r.driver                .all(&format!("SELECT name, type FROM pragma_table_info('{table}') WHERE \"notnull\" = 1 AND dflt_value IS NULL AND pk = 0"), &[])                .map_err(|e| e.to_string())?                .iter()                .map(|row| (row.text("name").unwrap_or_default().to_string(), row.text("type").unwrap_or_default().to_uppercase()))                .collect())        })        .unwrap();    let mut columns: Vec<String> = given.iter().map(|(c, _)| c.to_string()).collect();    let mut values: Vec<String> = given.iter().map(|(_, v)| v.clone()).collect();    for (name, kind) in required {        if columns.contains(&name) {            continue;        }        values.push(if kind.contains("INT") { "0".into() } else if kind.contains("REAL") || kind.contains("NUM") { "0.5".into() } else { format!("'{table}-' || n") });        columns.push(name);    }    sql(handle, &format!("WITH RECURSIVE s(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM s WHERE n < {count}) INSERT INTO {table} ({}) SELECT {} FROM s", columns.join(", "), values.join(", ")));}/// The invented account, written straight into the copy in a few statements.fn seed(handle: &CottonHandle) {    let now = chrono::Utc::now().timestamp_millis();    let at = |days: &str| format!("strftime('%Y-%m-%dT%H:%M:%fZ', {now} / 1000.0 - ({days}) * 86400 - 3600, 'unixepoch')");    let first = "json_extract('[\"Asha\",\"Ravi\",\"Mira\",\"Kabir\",\"Lena\",\"Omar\",\"Zoe\",\"Arun\",\"Meena\",\"Dev\",\"Nina\",\"Tara\",\"Ishan\",\"Kiran\",\"Leela\",\"Neel\",\"Priya\",\"Rohan\",\"Sana\",\"Vikram\",\"Anil\",\"Bela\",\"Chirag\",\"Divya\",\"Esha\",\"Farhan\",\"Gita\",\"Hari\",\"Indu\",\"Jai\",\"Kavya\",\"Lalit\",\"Mohan\",\"Naina\",\"Ojas\",\"Pooja\",\"Raj\",\"Sita\",\"Uma\",\"Varun\"]', '$[' || (n % 40) || ']')";    let last = "json_extract('[\"Example\",\"Sample\",\"Placeholder\",\"Invent\",\"Madeup\",\"Testwala\",\"Fiction\",\"Notreal\",\"Dummy\",\"Pretend\"]', '$[' || ((n / 40) % 10) || ']')";    let nums = |count: i64| format!("WITH RECURSIVE s(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM s WHERE n < {count})");    sql(handle, "BEGIN");    // People: names repeat across 400 combinations with a number after, so some pairs look alike, as a real book does.    sql(handle, &format!(        "{} INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) SELECT printf('p%05d', n), (SELECT workspace_id FROM _meta), \         {first} || ' ' || {last} || CASE WHEN n > 400 THEN ' ' || (n / 400) ELSE '' END, '2024-01-01', '2024-01-01' FROM s", nums(PEOPLE)));    sql(handle, &format!(        "{} INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) \         SELECT printf('hp%05d', n), (SELECT workspace_id FROM _meta), printf('p%05d', n), 'phone', printf('+1555%07d', n), printf('1555%07d', n), 'manual', '2024-01-01', '2024-01-01' FROM s \         UNION ALL SELECT printf('he%05d', n), (SELECT workspace_id FROM _meta), printf('p%05d', n), 'email', printf('p%05d@invented.example', n), printf('p%05d@invented.example', n), 'manual', '2024-01-01', '2024-01-01' FROM s", nums(PEOPLE)));    // Comms: a chat contact and a one-to-one thread for 1,200 of them; person 1 is the busy one (a tenth of it all).    sql(handle, &format!(        "{} INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, created_at, updated_at) SELECT printf('c%05d', n), (SELECT workspace_id FROM _meta), printf('1555%07d', n), '2024-01-01', '2024-01-01' FROM s", nums(1_200)));    sql(handle, &format!(        "{} INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, contact_id, read_seq, created_at, updated_at) SELECT printf('t%05d', n), (SELECT workspace_id FROM _meta), 'dm', printf('t%05d', n), printf('c%05d', n), 0, '2024-01-01', '2024-01-01' FROM s", nums(1_200)));    sql(handle, &format!(        "{} INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, title, read_seq, created_at, updated_at) SELECT printf('g%05d', n), (SELECT workspace_id FROM _meta), 'group', printf('g%05d', n), 'Group ' || n, 0, '2024-01-01', '2024-01-01' FROM s", nums(GROUP_CHATS)));    sql(handle, &format!(        "{} INSERT INTO cotton_msg_thread_participants (id, thread_id, workspace_id, contact_id, is_self, created_at) SELECT printf('tp%06d', n), printf('g%05d', 1 + n % {GROUP_CHATS}), (SELECT workspace_id FROM _meta), printf('c%05d', 1 + (n * 7) % 1200), 0, '2024-01-01' FROM s", nums(GROUP_CHATS * 8)));    sql(handle, &format!(        "{} INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, created_at, external_id) \         SELECT printf('m%07d', n), CASE WHEN n % 10 = 0 THEN 't00001' WHEN n % 13 = 0 THEN printf('g%05d', 1 + n % {GROUP_CHATS}) ELSE printf('t%05d', 1 + n % 1200) END, \           (SELECT workspace_id FROM _meta), CASE WHEN n % 3 = 0 THEN 'out' ELSE 'in' END, 'whatsapp', 'live', 'an invented line', {d}, n, {d}, printf('m%07d', n) FROM s",        nums(MESSAGES), d = at("(n % 1100) + (n % 7) / 10.0")));    if has(handle, "cotton_call_log") {        let d = at("n % 900");        fill(handle, "cotton_call_log", CALLS, &[("id", "printf('cl%06d', n)".into()), ("workspace_id", "(SELECT workspace_id FROM _meta)".into()), ("contact_id", "printf('c%05d', 1 + (n * 3) % 1200)".into()),            ("direction", "CASE WHEN n % 2 = 0 THEN 'out' ELSE 'in' END".into()), ("started_at", d.clone()), ("outcome", "'answered'".into()), ("created_at", d.clone()), ("updated_at", d)]);    }    // Post: mail in from each person and out to them, plus list mail that counts for nobody.    fill(handle, "cotton_email_threads", MAILS, &[("id", "printf('et%07d', n)".into()), ("workspace_id", "(SELECT workspace_id FROM _meta)".into()), ("external_key", "printf('etk%07d', n)".into()),        ("subject", "'Hello'".into()), ("email_count", "1".into()), ("created_at", "'2024-01-01'".into()), ("updated_at", "'2024-01-01'".into())]);    sql(handle, &format!(        "{} INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, subject, from_email, recipients, sent_at, body, snippet, attachments, unread, account, in_inbox, direction, list_id, created_at) \         SELECT printf('e%07d', n), (SELECT workspace_id FROM _meta), printf('et%07d', n), printf('x%07d', n), 'Hello', \           CASE WHEN n % 4 = 0 THEN 'me@invented.example' ELSE printf('p%05d@invented.example', 1 + (n * 11) % {PEOPLE}) END, \           json_array(json_object('email', printf('p%05d@invented.example', 1 + (n * 11) % {PEOPLE}), 'kind', 'to')), {d}, 'Hello', 'Hello', '[]', 0, 'me@invented.example', 1, \           CASE WHEN n % 4 = 0 THEN 'out' ELSE 'in' END, CASE WHEN n % 9 = 0 THEN 'news.invented.example' ELSE '' END, {d} FROM s",        nums(MAILS), d = at("n % 1000")));    if has(handle, "cotton_events") {        add_columns(handle, "cotton_events", &["people", "my_response", "trashed_at"]);        let d = at("n % 700");        fill(handle, "cotton_events", EVENTS, &[("id", "printf('ev%05d', n)".into()), ("title", "'Invented ' || (n % 50)".into()), ("starts_at", d),            ("people", format!("json_array(printf('p%05d', 1 + n % {PEOPLE}), printf('p%05d', 1 + (n * 5) % {PEOPLE}))")), ("created_at", "'2024-01-01'".into()), ("updated_at", "'2024-01-01'".into())]);    }    if has(handle, "cotton_photos") && has(handle, "cotton_media_faces") {        let d = at("n % 1200");        fill(handle, "cotton_photos", PHOTOS, &[("id", "'photo:' || printf('%064x', n)".into()), ("sha256", "printf('%064x', n)".into()), ("workspace_id", "(SELECT workspace_id FROM _meta)".into()), ("taken_at", d.clone()), ("created_at", d.clone()), ("updated_at", d)]);        fill(handle, "cotton_media_faces", PHOTOS * 3 / 2, &[("id", "printf('f%06d', n)".into()), ("workspace_id", "(SELECT workspace_id FROM _meta)".into()), ("record_kind", "'photo'".into()),            ("record_id", format!("'photo:' || printf('%064x', 1 + n % {PHOTOS})")), ("person_id", "printf('p%05d', 1 + (n * 13) % 300)".into()), ("source", "'cotton'".into()), ("created_at", "'2024-01-01'".into()), ("updated_at", "'2024-01-01'".into())]);    }    sql(handle, "COMMIT");    sql(handle, "ANALYZE");}struct Took {    what: String,    cold: (u64, Duration),    warm: (u64, Duration),}fn measure(handle: &CottonHandle, method: &str, request: Value) -> ((u64, Duration), Value) {    let why = std::env::var("CONTACTS_AT_SIZE_WHY").is_ok_and(|m| m == method);    if why {        handle.client().with_writer(|r| {            r.driver.watch_statements();            Ok(())        }).unwrap();    }    let measured = measure_plain(handle, method, request);    if why {        handle.client().with_writer(|r| {            for (steps, statement) in r.driver.steps_by_statement().into_iter().take(6) {                eprintln!("[why {method}] {steps} {}", statement.chars().take(300).collect::<String>());            }            Ok(())        }).unwrap();    }    measured}fn measure_plain(handle: &CottonHandle, method: &str, request: Value) -> ((u64, Duration), Value) {    let steps = cotton_store::driver::Driver::thread_steps();    let started = Instant::now();    let answer = over(&handle.client(), method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message));    ((cotton_store::driver::Driver::thread_steps() - steps, started.elapsed()), answer)}fn both(handle: &CottonHandle, table: &mut Vec<Took>, what: &str, method: &str, request: Value) -> Value {    let (cold, _) = measure(handle, method, request.clone());    let (warm, answer) = measure(handle, method, request);    table.push(Took { what: what.into(), cold, warm });    answer}fn print(table: &[Took]) {    if std::env::var("CONTACTS_AT_SIZE_PRINT").is_err() {        return;    }    eprintln!("| method | cold steps | cold ms | warm steps | warm ms |\n|---|---|---|---|---|");    for t in table {        eprintln!("| {} | {} | {} | {} | {} |", t.what, t.cold.0, t.cold.1.as_millis(), t.warm.0, t.warm.1.as_millis());    }}/// RULE (CONTACTS AT SIZE): on an account the owner's size, the home screen never walks messages or mails; facts are/// kept, and a new message costs a little, not a recount; the first rebuild goes in pages with home usable meanwhile.#[test]fn contacts_at_the_owners_size_stay_within_their_bounds() {    // A Contacts copy (the People kit), so the groups list answers as it does on the phone.    let dir = tempfile::tempdir().expect("a dir");    let handle = crate::phone::contacts_io::tests::phone(&dir);    super::tests::hold_contacts(&handle);    let seeded = Instant::now();    seed(&handle);    let seeded = seeded.elapsed();    let mut table = Vec::new();    let home = both(&handle, &mut table, "contacts.home (before facts)", "contacts.home", json!({}));    assert_eq!(home["sorting"], "Still sorting your people", "before the first count the home says so");    if std::env::var("CONTACTS_AT_SIZE_WHY").is_ok() {        let facts = crate::phone::contacts_facts::tests_parts;        for round in ["first", "again"] {            crate::phone::cotton_chat::write(&handle.client(), "parts", |ctx| {                for (name, steps, ms) in facts(ctx)? {                    eprintln!("[rebuild {round}] {name}: {steps} steps, {ms} ms");                }                ctx.commit().map_err(|e| e.to_string())?;                Ok(Value::Null)            })            .unwrap();        }        crate::phone::cotton_chat::write(&handle.client(), "reset", |ctx| {            ctx.db().run("DELETE FROM _contacts_counted", &[]).map_err(|e| e.to_string())?;            ctx.db().run("DELETE FROM cotton_person_fact", &[]).map_err(|e| e.to_string())?;            ctx.db().run("DELETE FROM cotton_group_origin", &[]).map_err(|e| e.to_string())?;            ctx.commit().map_err(|e| e.to_string())?;            Ok(Value::Null)        })        .unwrap();    }    let (first, counted) = measure(&handle, "contacts.facts", json!({}));    table.push(Took { what: "first facts build (whole rebuild)".into(), cold: first, warm: (0, Duration::ZERO) });    let _ = counted;    let (again, _) = measure(&handle, "contacts.facts", json!({}));    table.push(Took { what: "facts with nothing new".into(), cold: again, warm: (0, Duration::ZERO) });    sql(&handle, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, created_at, external_id) \                  SELECT 'm-new', 't00002', workspace_id, 'out', 'whatsapp', 'live', 'one more', strftime('%Y-%m-%dT%H:%M:%fZ','now'), 1, strftime('%Y-%m-%dT%H:%M:%fZ','now'), 'm-new' FROM _meta");    let (one, _) = measure(&handle, "contacts.facts", json!({}));    table.push(Took { what: "facts after one new message".into(), cold: one, warm: (0, Duration::ZERO) });    both(&handle, &mut table, "contacts.home", "contacts.home", json!({}));    both(&handle, &mut table, "contacts.person (busy)", "contacts.person", json!({ "id": "p00001" }));    for typed in ["a", "as", "ash", "asha"] {        both(&handle, &mut table, &format!("search \"{typed}\""), "contacts.home", json!({ "query": typed }));    }    both(&handle, &mut table, "search \"1555000\"", "contacts.home", json!({ "query": "1555000" }));    let same = both(&handle, &mut table, "contacts.same.list", "contacts.same.list", json!({}));    let _ = same;    // The groups list, with the 200 groups made from the chats.    let groups = both(&handle, &mut table, "contacts.groups", "contacts.groups", json!({}));    assert!(groups.to_string().contains("Group 1"), "the chats' groups are listed: {}", groups.to_string().chars().take(400).collect::<String>());    let first = groups["sections"][0]["rows"][0]["id"].as_str().expect("a group").to_string();    both(&handle, &mut table, "contacts.group (one)", "contacts.group", json!({ "id": first }));    let (merge, _) = measure(&handle, "contacts.merge", json!({ "keep": "p00002", "drop": "p00402" }));    table.push(Took { what: "contacts.merge".into(), cold: merge, warm: (0, Duration::ZERO) });    if std::env::var("CONTACTS_AT_SIZE_WHY").is_ok() {        handle.client().read_rows("parts", &mut |ctx| {            let part = |name: &str, ctx: &mut cotton_tools::mcp::dispatch::Ctx<'_>, work: &mut dyn FnMut(&mut cotton_tools::mcp::dispatch::Ctx<'_>) -> Result<(), String>| {                let steps = cotton_store::driver::Driver::thread_steps();                let started = Instant::now();                work(ctx).unwrap();                eprintln!("[part] {name}: {} steps, {} ms", cotton_store::driver::Driver::thread_steps() - steps, started.elapsed().as_millis());            };            part("contacts", ctx, &mut |c| super::contacts(c).map(|_| ()));            part("facts_by_person", ctx, &mut |c| super::facts_by_person(c).map(|_| ()));            part("first_groups", ctx, &mut |c| super::first_groups(c).map(|_| ()));            part("merged_away", ctx, &mut |c| crate::phone::contacts_same::merged_away(c).map(|_| ()));            part("same count", ctx, &mut |c| crate::phone::contacts_same::count(c).map(|_| ()));            part("reach busy", ctx, &mut |c| super::reach(c, "p00001").map(|_| ()));            part("between busy", ctx, &mut |c| super::between(c, "p00001", 0).map(|_| ()));            part("sources busy", ctx, &mut |c| super::sources(c, "p00001").map(|_| ()));            Ok(Value::Null)        }).unwrap();    }    eprintln!("[at size] seeded in {} ms", seeded.as_millis());    print(&table);    assert!(over(&handle.client(), "contacts.home", &json!({})).unwrap()["sorting"].is_null(), "counted once, the home no longer says it is sorting");    // THE GUARD, in SQLite's steps (what was read; time on a shared box is noise). Walking the messages or the mail    // once is tens of millions: no screen may come near it, and the kept facts never recount everyone for a message.    let bound = |what: &str, most: u64, warm: bool| {        let t = table.iter().find(|t| t.what == what).unwrap_or_else(|| panic!("{what} measured"));        let steps = if warm { t.warm.0 } else { t.cold.0 };        assert!(steps <= most, "{what}: {steps} steps, more than {most}");    };    bound("contacts.home", 1_000_000, true);    bound("contacts.person (busy)", 1_000_000, true);    for typed in ["a", "as", "ash", "asha", "1555000"] {        bound(&format!("search \"{typed}\""), 1_000_000, true);    }    bound("contacts.same.list", 1_000_000, true);    bound("contacts.merge", 500_000, false);    bound("contacts.groups", 1_000_000, true);    bound("contacts.group (one)", 1_000_000, true);    bound("facts with nothing new", 1_000_000, false);    bound("facts after one new message", 5_000_000, false);    bound("first facts build (whole rebuild)", 100_000_000, false);}