Cotton code
179 lines · 10.1 KB · RustRaw
//! The Mail list reads the threads on its page, not every thread in the file.//!//! The phone asks for a folder (Inbox, Starred, Archived, Bin, All) a page at//! a time. Until 11 Oct 2026 every page assembled every thread the file held —//! its emails with their bodies, its participants and their people — and then//! filtered and paged in Rust: a named hold on the serving Mac (05:38:25Z,//! 6.8 s, 248,914,242 steps in one read) while the IMAP reader backfilled.//!//! Every value is invented ([nothing-real-ever-goes-in-cotton-s-public-tree]).mod support;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::Harness;use support::mcp::{call_tool, mint_token};const NOW: &str = "2026-10-05T09:00:00.000Z";/// A file holding `threads` conversations of one email each — every third/// archived, every fifth starred, every seventh binned — from forty senders who/// are people, among `people` people with an address each.fn file_with(threads: i64, people: i64) -> (Harness, String) {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let workspace = || SqlValue::Text(h.workspace_id.clone());    h.run(        "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM n WHERE i + 1 < ?1) \         INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, first_at, last_at, email_count, created_at, updated_at) \         SELECT printf('thread-%08d', i), ?2, printf('key-%08d', i), printf('An invented subject %d', i), \                strftime('%Y-%m-%dT%H:%M:%fZ', '2026-01-01', printf('+%d minutes', i)), \                strftime('%Y-%m-%dT%H:%M:%fZ', '2026-01-01', printf('+%d minutes', i)), 1, ?3, ?3 FROM n",        &[SqlValue::Integer(threads), workspace(), SqlValue::Text(NOW.into())],    );    h.run(        "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM n WHERE i + 1 < ?1) \         INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, subject, from_name, from_email, sent_at, body, snippet, \                                    in_inbox, starred, unread, trashed_at, created_at) \         SELECT printf('email-%08d', i), ?2, printf('thread-%08d', i), printf('<%d@example.invalid>', i), \                printf('An invented subject %d', i), 'An Invented Sender', printf('sender%d@example.invalid', i % 40), \                strftime('%Y-%m-%dT%H:%M:%fZ', '2026-01-01', printf('+%d minutes', i)), 'An invented body.', 'An invented body.', \                i % 3 <> 0, i % 5 = 0, i % 2, CASE WHEN i % 7 = 0 THEN ?3 END, ?3 FROM n",        &[SqlValue::Integer(threads), workspace(), SqlValue::Text(NOW.into())],    );    h.run(        "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM n WHERE i + 1 < ?1) \         INSERT INTO cotton_email_participants (id, workspace_id, thread_id, email, role, created_at, updated_at) \         SELECT printf('from-%08d', i), ?2, printf('thread-%08d', i), printf('sender%d@example.invalid', i % 40), 'from', ?3, ?3 FROM n \         UNION ALL \         SELECT printf('to-%08d', i), ?2, printf('thread-%08d', i), 'owner@example.invalid', 'to', ?3, ?3 FROM n",        &[SqlValue::Integer(threads), workspace(), SqlValue::Text(NOW.into())],    );    h.run(        "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM n WHERE i + 1 < ?1) \         INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) \         SELECT printf('person-%08d', i), ?2, printf('An Invented Person %d', i), ?3, ?3 FROM n",        &[SqlValue::Integer(people), workspace(), SqlValue::Text(NOW.into())],    );    h.run(        "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM n WHERE i + 1 < ?1) \         INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) \         SELECT printf('handle-%08d', i), ?2, printf('person-%08d', i), 'email', \                CASE WHEN i < 40 THEN printf('sender%d@example.invalid', i) ELSE printf('person%d@example.invalid', i) END, \                CASE WHEN i < 40 THEN printf('sender%d@example.invalid', i) ELSE printf('person%d@example.invalid', i) END, \                'manual', ?3, ?3 FROM n",        &[SqlValue::Integer(people), workspace(), SqlValue::Text(NOW.into())],    );    (h, secret)}fn page(h: &Harness, secret: &str, filter: Value) -> Value {    call_tool(h, secret, "list_records", json!({ "table": "email_thread", "where": filter, "limit": 50 }))}/// Steps to read the Inbox's first page — the call's own statements, not the/// harness's bookkeeping after it.fn steps_to_read_the_inbox(h: &Harness, secret: &str) -> u64 {    h.db.watch_statements();    let answer = page(h, secret, json!({ "in_inbox": true, "binned": false }));    assert_eq!(answer["records"].as_array().map(Vec::len), Some(50), "{answer}");    h.db.steps_by_statement()        .into_iter()        .filter(|(_, sql)| !sql.contains("NOT EXISTS (SELECT 1 FROM _writes"))        .map(|(steps, _)| steps)        .sum()}fn ids(answer: &Value) -> Vec<String> {    answer["records"]        .as_array()        .expect("records")        .iter()        .map(|record| record["id"].as_str().expect("an id").to_string())        .collect()}/// RULE: A page of the Mail list assembles only the threads on that page — which threads are in the folder is asked of the emails' flags in SQL — so the threads it builds are the same 50 among 500 threads and 50,000, and only the folder's count grows with the file, by a few steps a thread.#[test]fn a_mail_page_assembles_its_own_threads_and_never_every_thread() {    let (small_file, small_secret) = file_with(500, 200);    let small = steps_to_read_the_inbox(&small_file, &small_secret);    let (large_file, large_secret) = file_with(50_000, 200);    let large = steps_to_read_the_inbox(&large_file, &large_secret);    // The count and the page's choice walk the folder's threads by index    // (the count must: the phone shows it); everything else is the page's.    let per_thread = (large - small) / (50_000 - 500);    assert!(        per_thread <= 40,        "a page read {large} steps among 50,000 threads and {small} among 500 — {per_thread} a thread"    );}/// RULE: Each folder answers the threads, the order and the count the whole walk answered: newest first, a thread in a folder when one of its emails is, starred or unread when one of the folder's emails is.#[test]fn every_folder_answers_its_own_threads_newest_first_with_its_count() {    let (h, secret) = file_with(210, 200);    // Thread i: in the inbox unless i % 3 == 0, starred when i % 5 == 0,    // unread when i is odd, binned when i % 7 == 0.    let expect = |keep: &dyn Fn(i64) -> bool| -> Vec<String> {        (0..210).rev().filter(|i| keep(*i)).map(|i| format!("thread-{i:08}")).collect()    };    let live = |i: i64| i % 7 != 0;    let folders: Vec<(Value, Vec<String>)> = vec![        (json!({ "in_inbox": true, "binned": false }), expect(&|i| live(i) && i % 3 != 0)),        (json!({ "in_inbox": false, "binned": false }), expect(&|i| live(i) && i % 3 == 0)),        (json!({ "starred": true, "binned": false }), expect(&|i| live(i) && i % 5 == 0)),        (json!({ "binned": true }), expect(&|i| !live(i))),        (json!({ "binned": false }), expect(&live)),        (json!({ "binned": false, "read_state": "unread" }), expect(&|i| live(i) && i % 2 == 1)),    ];    for (filter, wanted) in folders {        let first = page(&h, &secret, filter.clone());        assert_eq!(first["total"].as_i64(), Some(wanted.len() as i64), "{filter}");        assert_eq!(ids(&first), wanted.iter().take(50).cloned().collect::<Vec<_>>(), "{filter}");        let second = call_tool(            &h,            &secret,            "list_records",            json!({ "table": "email_thread", "where": filter, "limit": 50, "page": 50 }),        );        assert_eq!(ids(&second), wanted.iter().skip(50).take(50).cloned().collect::<Vec<_>>(), "{filter}");    }    // A thread on the page is the whole thread the walk built.    let inbox = page(&h, &secret, json!({ "in_inbox": true, "binned": false }));    let top = &inbox["records"][0];    assert_eq!(top["id"], "thread-00000209");    assert_eq!(top["data"]["sender"], "An Invented Sender", "{top}");    assert_eq!(top["data"]["read_state"], "unread", "{top}");    assert_eq!(top["data"]["people"], json!(["person-00000009"]), "{top}");}/// RULE: The People and Records stacks — a thread with someone in People, and one without — answer the threads the whole walk answered: a participant whose address is a handle of someone in People, never the owner's own address.#[test]fn the_people_and_records_stacks_split_the_threads_by_who_is_in_people() {    // Twenty of the forty senders are people: thread i's sender is i % 40.    let (h, secret) = file_with(210, 20);    let live = |i: i64| i % 7 != 0;    let expect = |keep: &dyn Fn(i64) -> bool| -> Vec<String> {        (0..210).rev().filter(|i| keep(*i)).map(|i| format!("thread-{i:08}")).collect()    };    for (filter, wanted) in [        (json!({ "people": { "present": true }, "binned": false }), expect(&|i| live(i) && i % 40 < 20)),        (json!({ "people": { "present": false }, "binned": false }), expect(&|i| live(i) && i % 40 >= 20)),    ] {        let first = page(&h, &secret, filter.clone());        assert_eq!(first["total"].as_i64(), Some(wanted.len() as i64), "{filter}");        assert_eq!(ids(&first), wanted.iter().take(50).cloned().collect::<Vec<_>>(), "{filter}");    }}/// RULE: A thread's people are found by its addresses through the handle index that leads with the workspace, so a page of mail costs the same among 200 people as among 20,000 — never a walk of every person per thread.#[test]fn a_threads_people_are_found_by_address_and_never_by_walking_everyone() {    let (few, few_secret) = file_with(500, 200);    let small = steps_to_read_the_inbox(&few, &few_secret);    let (many, many_secret) = file_with(500, 20_000);    let large = steps_to_read_the_inbox(&many, &many_secret);    assert!(large <= small + small / 4, "a page read {large} steps among 20,000 people and {small} among 200");}